repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Limon-O-O/Convex
Convex/TabBar.swift
1
3262
// // TabBar.swift // Example // // Created by Limon on 3/19/16. // Copyright © 2016 Convex. All rights reserved. // import UIKit class TabBar: UITabBar { override init(frame: CGRect) { super.init(frame: frame) if let upwrappedPlusButton = TabBarController.plusButton { addSubview(upwrappedPlusButton) } backgroundImage = getImageWithColor(UIColor.whiteColor()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() guard let unwrappedPlusButton = TabBarController.plusButton where TabBarController.plusButton is protocol<PlusButton> else { return } let barWidth = frame.size.width let barHeight: CGFloat = frame.size.height let barButtonWidth: CGFloat = barWidth / CGFloat(TabBarController.tabbarItemsCount + 1) var multiplerInCenterY: CGFloat = 0.0 var buttonIndex: Int = 0 multiplerInCenterY = (unwrappedPlusButton as! PlusButton).multiplerInCenterY unwrappedPlusButton.center = CGPoint(x: barWidth * 0.5, y: barHeight * multiplerInCenterY) let plusButtonIndex = (unwrappedPlusButton as! PlusButton).indexOfPlusButtonInTabBar unwrappedPlusButton.frame = CGRect(x: CGFloat(plusButtonIndex) * barButtonWidth, y: CGRectGetMinY(unwrappedPlusButton.frame), width: CGRectGetWidth(unwrappedPlusButton.frame), height: CGRectGetHeight(unwrappedPlusButton.frame)) let sortedSubviews = subviews.sort { (view1, view2) -> Bool in return view1.frame.origin.x < view2.frame.origin.x } // 调整加号按钮后面的 UITabBarItem 的位置 sortedSubviews.forEach { childView in guard "\(childView.dynamicType)" == "UITabBarButton" else { return } if buttonIndex == plusButtonIndex { buttonIndex += 1 } childView.frame = CGRect(x: CGFloat(buttonIndex) * barButtonWidth, y: CGRectGetMinY(childView.frame), width: barButtonWidth, height: CGRectGetHeight(childView.frame)) buttonIndex += 1 } bringSubviewToFront(unwrappedPlusButton) } // Capturing touches on a subview outside the frame of its superview override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? { if !clipsToBounds && !hidden && alpha > 0.0 { if let result = super.hitTest(point, withEvent: event) { return result } else { for (_, subview) in subviews.reverse().enumerate() { let subPoint = subview.convertPoint(point, fromView: self) return subview.hitTest(subPoint, withEvent: event) } } } return nil } private func getImageWithColor(color: UIColor) -> UIImage { let rect = CGRect(origin: CGPointZero, size: CGSize(width: 1, height: 1)) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
mit
SwampThingTom/Pokebase
Pokebase/AppDelegate.swift
1
650
// // AppDelegate.swift // Pokebase // // Created by Thomas Aylesworth on 12/10/16. // Copyright © 2016 Thomas H Aylesworth. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { } func applicationWillTerminate(_ aNotification: Notification) { } @IBAction func importFromCsv(_ sender: AnyObject) { guard let viewController = NSApplication.shared().mainWindow?.contentViewController as? ViewController else { return } viewController.importFromCsv() } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/07643-swift-boundgenerictype-get.swift
11
357
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol P { class B<f = compose(e == compose(A struct Q<b<I : T where S<I : A<f = " class B : Array<b> c { e) { struct Q<h : d where A<I : d = " func b> { class A : e == " typealias b) {
mit
xunildavid/QCamera
QCamera/QCamera/ViewController.swift
1
504
// // ViewController.swift // QCamera // // Created by 陆永权 on 15/8/20. // Copyright (c) 2015年 陆永权. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
mariopavlovic/codility-lessons
codility-lessons/tests/Lesson10Specs.swift
1
2868
import Quick import Nimble class Lesson10Specs: QuickSpec { override func spec() { var sut: Lesson10! beforeEach { sut = Lesson10() } describe("Given lesson 10 - minPerimeter") { context("when loaded", { it("should implemenet solution", closure: { expect(sut.minPerimeter(4)).toNot(beNil()) }) }) context("when calculating min perimeter", { it("should calculate correctly for small predictable input", closure: { expect(sut.minPerimeter(30)).to(equal(22)) }) it("should calculate correctly for small unpredictable input", closure: { expect(sut.minPerimeter(4)).to(equal(8)) expect(sut.minPerimeter(1)).to(equal(4)) }) }) } describe("Given lesson 10 - numFactors") { context("when loaded", { it("should implemenet solution", closure: { expect(sut.numFactors(4)).toNot(beNil()) }) }) context("when calculating number of factors", { it("should calculate correctly for small predictable input", closure: { expect(sut.numFactors(24)).to(equal(8)) expect(sut.numFactors(16)).to(equal(5)) }) it("should calculate correctly for small unpredictable input", closure: { expect(sut.numFactors(1)).to(equal(1)) expect(sut.numFactors(2)).to(equal(2)) expect(sut.numFactors(3)).to(equal(2)) expect(sut.numFactors(9)).to(equal(3)) }) }) } describe("Given lesson 10 - numPeakGroups") { context("when loaded", { it("should implemenet solution", closure: { expect(sut.numPeakGroups([1])).toNot(beNil()) }) }) context("when counting number of peak groups", { it("should calculate correctly for small predictable input", closure: { let input = [1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2] expect(sut.numPeakGroups(input)).to(equal(3)) expect(sut.numPeakGroups([1, 3, 1, 1, 1, 1])).to(equal(1)) }) it("should calculate correctly for small unpredictable input", closure: { let input = [1, 3, 1] expect(sut.numPeakGroups(input)).to(equal(1)) }) }) } } }
mit
Onefootball/TestingWithResettingData
TestingWithResettingDataTests/TestingWithResettingDataTests.swift
1
931
// // Copyright © 2015 Onefootball GmbH. All rights reserved. // import XCTest @testable import TestingWithResettingData class TestingWithResettingDataTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
gmilos/swift
test/SILGen/let_decls.swift
2
15830
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s func takeClosure(_ a : () -> Int) {} // Let decls don't get boxes for trivial types. // // CHECK-LABEL: sil hidden @{{.*}}test1 func test1(_ a : Int) -> Int { // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack let (b,c) = (a, 32) return b+c // CHECK: return } // rdar://15716277 // CHECK: @{{.*}}let_destructuring func let_destructuring() -> Int { let (a, b) = ((1,2), 5) return a.1+a.0+b } // Let decls being closed over. // // CHECK-LABEL: sil hidden @{{.*}}test2 func test2() { // No allocations. // CHECK-NOT: alloc_box // CHECK-NOT: alloc_stack let x = 42 takeClosure({x}) // CHECK: return } // The closure just returns its value, which it captured directly. // CHECK: sil shared @_TFF9let_decls5test2FT_T_U_FT_Si : $@convention(thin) (Int) -> Int // CHECK: bb0(%0 : $Int): // CHECK: return %0 : $Int // Verify that we can close over let decls of tuple type. struct RegularStruct { var a: Int } func testTupleLetCapture() { let t = (RegularStruct(a: 41), 42) takeClosure( { t.0.a }) } func getAString() -> String { return "" } func useAString(_ a : String) {} // rdar://15689514 - Verify that the cleanup for the let decl runs at the end of // the 'let' lifetime, not at the end of the initializing expression. // // CHECK-LABEL: sil hidden @{{.*}}test3 func test3() { // CHECK: [[GETFN:%[0-9]+]] = function_ref{{.*}}getAString // CHECK-NEXT: [[STR:%[0-9]+]] = apply [[GETFN]]() let o = getAString() // CHECK-NOT: destroy_value // CHECK: [[USEFN:%[0-9]+]] = function_ref{{.*}}useAString // CHECK-NEXT: [[STR_COPY:%.*]] = copy_value [[STR]] // CHECK-NEXT: [[USE:%[0-9]+]] = apply [[USEFN]]([[STR_COPY]]) useAString(o) // CHECK: destroy_value [[STR]] } // CHECK: } // end sil function '{{.*}}test3{{.*}}' struct AddressOnlyStruct<T> { var elt : T var str : String } func produceAddressOnlyStruct<T>(_ x : T) -> AddressOnlyStruct<T> {} // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyStructString func testAddressOnlyStructString<T>(_ a : T) -> String { return produceAddressOnlyStruct(a).str // CHECK: [[PRODFN:%[0-9]+]] = function_ref @{{.*}}produceAddressOnlyStruct // CHECK: [[TMPSTRUCT:%[0-9]+]] = alloc_stack $AddressOnlyStruct<T> // CHECK: apply [[PRODFN]]<T>([[TMPSTRUCT]], // CHECK-NEXT: [[STRADDR:%[0-9]+]] = struct_element_addr [[TMPSTRUCT]] : $*AddressOnlyStruct<T>, #AddressOnlyStruct.str // CHECK-NEXT: [[STRVAL:%[0-9]+]] = load [copy] [[STRADDR]] // CHECK-NEXT: destroy_addr [[TMPSTRUCT]] // CHECK-NEXT: dealloc_stack [[TMPSTRUCT]] // CHECK: return [[STRVAL]] } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyStructElt func testAddressOnlyStructElt<T>(_ a : T) -> T { return produceAddressOnlyStruct(a).elt // CHECK: [[PRODFN:%[0-9]+]] = function_ref @{{.*}}produceAddressOnlyStruct // CHECK: [[TMPSTRUCT:%[0-9]+]] = alloc_stack $AddressOnlyStruct<T> // CHECK: apply [[PRODFN]]<T>([[TMPSTRUCT]], // CHECK-NEXT: [[ELTADDR:%[0-9]+]] = struct_element_addr [[TMPSTRUCT]] : $*AddressOnlyStruct<T>, #AddressOnlyStruct.elt // CHECK-NEXT: copy_addr [[ELTADDR]] to [initialization] %0 : $*T // CHECK-NEXT: destroy_addr [[TMPSTRUCT]] } // rdar://15717123 - let decls of address-only type. // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyLet func testAddressOnlyLet<T>(_ a : T) { let x = produceAddressOnlyStruct(a) } func produceSubscriptableRValue() -> [String] {} // CHECK-LABEL: sil hidden @{{.*}}subscriptRValue func subscriptRValue() { var a = produceSubscriptableRValue()[0] } struct GetOnlySubscriptStruct { // get-only subscript subscript (i : Int) -> Int { get {} } } // CHECK-LABEL: sil hidden @{{.*}}testGetOnlySubscript func testGetOnlySubscript(_ x : GetOnlySubscriptStruct, idx : Int) -> Int { return x[idx] // CHECK: [[SUBFN:%[0-9]+]] = function_ref @{{.*}}g9subscript // CHECK-NEXT: [[CALL:%[0-9]+]] = apply [[SUBFN]]( // CHECK: return [[CALL]] } // Address-only let's get captured by box. extension Optional { func getLV() -> Int { } } struct CloseOverAddressOnlyConstant<T> { func isError() { let AOV: T? takeClosure({ AOV.getLV() }) } } // CHECK-LABEL: sil hidden @{{.*}}callThroughLet func callThroughLet(_ predicate: @escaping (Int, Int) -> Bool) { let p = predicate if p(1, 2) { } } // Verify that we can emit address-only rvalues directly into the result slot in // chained calls. struct GenericTestStruct<T> { func pass_address_only_rvalue_result(_ i: Int) -> T { return self[i] } subscript (i : Int) -> T { get {} set {} } } // CHECK-LABEL: sil hidden @{{.*}}pass_address_only_rvalue_result // CHECK: bb0(%0 : $*T, // CHECK: [[FN:%[0-9]+]] = function_ref @{{.*}}GenericTestStructg9subscript // CHECK: apply [[FN]]<T>(%0, struct NonMutableSubscriptable { subscript(x : Int) -> Int { get {} nonmutating set {} } } func produceNMSubscriptableRValue() -> NonMutableSubscriptable {} // CHECK-LABEL: sil hidden @{{.*}}test_nm_subscript_get // CHECK: bb0(%0 : $Int): // CHECK: [[FR1:%[0-9]+]] = function_ref @{{.*}}produceNMSubscriptableRValue // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[FR1]]() // CHECK: [[GETFN:%[0-9]+]] = function_ref @_TFV9let_decls23NonMutableSubscriptableg9subscript // CHECK-NEXT: [[RES2:%[0-9]+]] = apply [[GETFN]](%0, [[RES]]) // CHECK-NEXT: return [[RES2]] func test_nm_subscript_get(_ a : Int) -> Int { return produceNMSubscriptableRValue()[a] } // CHECK-LABEL: sil hidden @{{.*}}test_nm_subscript_set // CHECK: bb0(%0 : $Int): // CHECK: [[FR1:%[0-9]+]] = function_ref @{{.*}}produceNMSubscriptableRValue // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[FR1]]() // CHECK: [[SETFN:%[0-9]+]] = function_ref @_TFV9let_decls23NonMutableSubscriptables9subscript // CHECK-NEXT: [[RES2:%[0-9]+]] = apply [[SETFN]](%0, %0, [[RES]]) func test_nm_subscript_set(_ a : Int) { produceNMSubscriptableRValue()[a] = a } struct WeirdPropertyTest { // This property has a mutating getter and !mutating setter. var p : Int { mutating get {} nonmutating set {} } } // CHECK-LABEL: sil hidden @{{.*}}test_weird_property func test_weird_property(_ v : WeirdPropertyTest, i : Int) -> Int { var v = v // CHECK: [[VBOX:%[0-9]+]] = alloc_box ${ var WeirdPropertyTest } // CHECK: [[PB:%.*]] = project_box [[VBOX]] // CHECK: store %0 to [trivial] [[PB]] // The setter isn't mutating, so we need to load the box. // CHECK: [[VVAL:%[0-9]+]] = load [trivial] [[PB]] // CHECK: [[SETFN:%[0-9]+]] = function_ref @_TFV9let_decls17WeirdPropertyTests1pSi // CHECK: apply [[SETFN]](%1, [[VVAL]]) v.p = i // The getter is mutating, so it takes the box address. // CHECK: [[GETFN:%[0-9]+]] = function_ref @_TFV9let_decls17WeirdPropertyTestg1pSi // CHECK-NEXT: [[RES:%[0-9]+]] = apply [[GETFN]]([[PB]]) // CHECK: return [[RES]] return v.p } // CHECK-LABEL: sil hidden @{{.*}}generic_identity // CHECK: bb0(%0 : $*T, %1 : $*T): // CHECK-NEXT: debug_value_addr %1 : $*T // CHECK-NEXT: copy_addr %1 to [initialization] %0 : $*T // CHECK-NEXT: destroy_addr %1 // CHECK: } // end sil function '{{.*}}generic_identity{{.*}}' func generic_identity<T>(_ a : T) -> T { // Should be a single copy_addr, with no temporary. return a } struct StaticLetMember { static let x = 5 } // CHECK-LABEL: sil hidden @{{.*}}testStaticLetMember func testStaticLetMember() -> Int { // CHECK: function_ref @{{.*}}StaticLetMemberau1xSi // CHECK: load {{.*}} : $*Int // CHECK-NEXT: return return StaticLetMember.x } protocol SimpleProtocol { func doSomethingGreat() } // Verify that no temporaries+copies are produced when calling non-@mutable // methods on protocol and archetypes calls. // CHECK-LABEL: sil hidden @{{.*}}testLetProtocolBases // CHECK: bb0(%0 : $*SimpleProtocol): func testLetProtocolBases(_ p : SimpleProtocol) { // CHECK-NEXT: debug_value_addr // CHECK-NEXT: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: open_existential_addr // CHECK-NEXT: witness_method // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @{{.*}}testLetArchetypeBases // CHECK: bb0(%0 : $*T): func testLetArchetypeBases<T : SimpleProtocol>(_ p : T) { // CHECK-NEXT: debug_value_addr // CHECK-NEXT: witness_method $T // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: witness_method $T // CHECK-NEXT: apply p.doSomethingGreat() // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @{{.*}}testDebugValue // CHECK: bb0(%0 : $Int, %1 : $*SimpleProtocol): // CHECK-NEXT: debug_value %0 : $Int, let, name "a" // CHECK-NEXT: debug_value_addr %1 : $*SimpleProtocol, let, name "b" func testDebugValue(_ a : Int, b : SimpleProtocol) -> Int { // CHECK-NEXT: debug_value %0 : $Int, let, name "x" let x = a // CHECK: apply b.doSomethingGreat() // CHECK: destroy_addr // CHECK: return %0 return x } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyTupleArgument func testAddressOnlyTupleArgument(_ bounds: (start: SimpleProtocol, pastEnd: Int)) { // CHECK: bb0(%0 : $*SimpleProtocol, %1 : $Int): // CHECK-NEXT: %2 = alloc_stack $(start: SimpleProtocol, pastEnd: Int), let, name "bounds" // CHECK-NEXT: %3 = tuple_element_addr %2 : $*(start: SimpleProtocol, pastEnd: Int), 0 // CHECK-NEXT: copy_addr [take] %0 to [initialization] %3 : $*SimpleProtocol // CHECK-NEXT: %5 = tuple_element_addr %2 : $*(start: SimpleProtocol, pastEnd: Int), 1 // CHECK-NEXT: store %1 to [trivial] %5 : $*Int // CHECK-NEXT: debug_value_addr %2 // CHECK-NEXT: destroy_addr %2 : $*(start: SimpleProtocol, pastEnd: Int) // CHECK-NEXT: dealloc_stack %2 : $*(start: SimpleProtocol, pastEnd: Int) } func address_only_let_closure<T>(_ x:T) -> T { return { { x }() }() } struct GenericFunctionStruct<T, U> { var f: (T) -> U } // CHECK-LABEL: sil hidden @{{.*}}member_ref_abstraction_change // CHECK: function_ref reabstraction thunk helper // CHECK: return func member_ref_abstraction_change(_ x: GenericFunctionStruct<Int, Int>) -> (Int) -> Int { return x.f } // CHECK-LABEL: sil hidden @{{.*}}call_auto_closure // CHECK: bb0([[CLOSURE:%.*]] : $@callee_owned () -> Bool): // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[CLOSURE]] // CHECK: apply [[CLOSURE_COPY]]() : $@callee_owned () -> Bool // CHECK: destroy_value [[CLOSURE]] // CHECK: } // end sil function '{{.*}}call_auto_closure{{.*}}' func call_auto_closure(x: @autoclosure () -> Bool) -> Bool { return x() // Calls of autoclosures should be marked transparent. } class SomeClass {} struct AnotherStruct { var i : Int var c : SomeClass } struct StructMemberTest { var c : SomeClass var i = 42 var s : AnotherStruct var t : (Int, AnotherStruct) // rdar://15867140 - Accessing the int member here should not copy_value the // whole struct. func testIntMemberLoad() -> Int { return i } // CHECK-LABEL: sil hidden @{{.*}}testIntMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK: debug_value %0 : $StructMemberTest, let, name "self" // CHECK: %2 = struct_extract %0 : $StructMemberTest, #StructMemberTest.i // CHECK-NOT: destroy_value %0 : $StructMemberTest // CHECK: return %2 : $Int // Accessing the int member in s should not copy_value the whole struct. func testRecursiveIntMemberLoad() -> Int { return s.i } // CHECK-LABEL: sil hidden @{{.*}}testRecursiveIntMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK: debug_value %0 : $StructMemberTest, let, name "self" // CHECK: %2 = struct_extract %0 : $StructMemberTest, #StructMemberTest.s // CHECK: %3 = struct_extract %2 : $AnotherStruct, #AnotherStruct.i // CHECK-NOT: destroy_value %0 : $StructMemberTest // CHECK: return %3 : $Int func testTupleMemberLoad() -> Int { return t.1.i } // CHECK-LABEL: sil hidden @{{.*}}testTupleMemberLoad{{.*}} : $@convention(method) (@guaranteed StructMemberTest) // CHECK: bb0(%0 : $StructMemberTest): // CHECK-NEXT: debug_value %0 : $StructMemberTest, let, name "self" // CHECK-NEXT: [[T0:%.*]] = struct_extract %0 : $StructMemberTest, #StructMemberTest.t // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : $(Int, AnotherStruct), 0 // CHECK-NEXT: [[T2:%.*]] = tuple_extract [[T0]] : $(Int, AnotherStruct), 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T2]] : $AnotherStruct, #AnotherStruct.i // CHECK-NEXT: return [[T3]] : $Int } struct GenericStruct<T> { var a : T var b : Int func getA() -> T { return a } // CHECK-LABEL: sil hidden @{{.*}}GenericStruct4getA{{.*}} : $@convention(method) <T> (@in_guaranteed GenericStruct<T>) -> @out T // CHECK: bb0(%0 : $*T, %1 : $*GenericStruct<T>): // CHECK-NEXT: debug_value_addr %1 : $*GenericStruct<T>, let, name "self" // CHECK-NEXT: %3 = struct_element_addr %1 : $*GenericStruct<T>, #GenericStruct.a // CHECK-NEXT: copy_addr %3 to [initialization] %0 : $*T // CHECK-NEXT: %5 = tuple () // CHECK-NEXT: return %5 : $() func getB() -> Int { return b } // CHECK-LABEL: sil hidden @{{.*}}GenericStruct4getB{{.*}} : $@convention(method) <T> (@in_guaranteed GenericStruct<T>) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : $*GenericStruct<T>): // CHECK-NEXT: debug_value_addr [[SELF_ADDR]] : $*GenericStruct<T>, let, name "self" // CHECK-NEXT: [[PROJ_ADDR:%.*]] = struct_element_addr [[SELF_ADDR]] : $*GenericStruct<T>, #GenericStruct.b // CHECK-NEXT: [[PROJ_VAL:%.*]] = load [trivial] [[PROJ_ADDR]] : $*Int // CHECK-NOT: destroy_addr [[SELF]] : $*GenericStruct<T> // CHECK-NEXT: return [[PROJ_VAL]] : $Int } // rdar://15877337 struct LetPropertyStruct { let lp : Int } // CHECK-LABEL: sil hidden @{{.*}}testLetPropertyAccessOnLValueBase // CHECK: bb0(%0 : $LetPropertyStruct): // CHECK: [[ABOX:%[0-9]+]] = alloc_box ${ var LetPropertyStruct } // CHECK: [[A:%[0-9]+]] = project_box [[ABOX]] // CHECK: store %0 to [trivial] [[A]] : $*LetPropertyStruct // CHECK: [[STRUCT:%[0-9]+]] = load_borrow [[A]] : $*LetPropertyStruct // CHECK: [[PROP:%[0-9]+]] = struct_extract [[STRUCT]] : $LetPropertyStruct, #LetPropertyStruct.lp // CHECK: destroy_value [[ABOX]] : ${ var LetPropertyStruct } // CHECK: return [[PROP]] : $Int func testLetPropertyAccessOnLValueBase(_ a : LetPropertyStruct) -> Int { var a = a return a.lp } var addressOnlyGetOnlyGlobalProperty : SimpleProtocol { get {} } // CHECK-LABEL: sil hidden @{{.*}}testAddressOnlyGetOnlyGlobalProperty // CHECK: bb0(%0 : $*SimpleProtocol): // CHECK-NEXT: // function_ref // CHECK-NEXT: %1 = function_ref @{{.*}}addressOnlyGetOnlyGlobalProperty // CHECK-NEXT: %2 = apply %1(%0) : $@convention(thin) () -> @out SimpleProtocol // CHECK-NEXT: %3 = tuple () // CHECK-NEXT: return %3 : $() // CHECK-NEXT: } func testAddressOnlyGetOnlyGlobalProperty() -> SimpleProtocol { return addressOnlyGetOnlyGlobalProperty } // rdar://15962740 struct LetDeclInStruct { let immutable: Int init() { immutable = 1 } } // rdar://19854166 - Swift 1.2 uninitialized constant causes crash // The destroy_addr for a let stack temporary should be generated against // mark_uninitialized instruction, so DI will see it. func test_unassigned_let_constant() { let string : String } // CHECK: [[S:%[0-9]+]] = alloc_stack $String, let, name "string" // CHECK-NEXT: [[MUI:%[0-9]+]] = mark_uninitialized [var] [[S]] : $*String // CHECK-NEXT: destroy_addr [[MUI]] : $*String // CHECK-NEXT: dealloc_stack [[S]] : $*String
apache-2.0
zhixingxi/JJA_Swift
JJA_Swift/JJA_Swift/Modules/Main/NewFeatures/JJANewFeatureView.swift
1
2765
// // JJANewFeatureView.swift // JJA_Swift // // Created by MQL-IT on 2017/8/8. // Copyright © 2017年 MQL-IT. All rights reserved. // 引导图界面 import UIKit private let SCREEN_WIDTH: Double = Double(UIScreen.main.bounds.size.width) private let SCREEN_HEIGHT: Double = Double(UIScreen.main.bounds.size.height) class JJANewFeatureView: UIView { fileprivate lazy var scrollView: UIScrollView = { let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)) scrollView.backgroundColor = UIColor.clear scrollView.bounces = false scrollView.isPagingEnabled = true scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.delegate = self return scrollView }() fileprivate lazy var enterBtn: UIButton = { let btn = UIButton(type: UIButtonType.custom) btn.backgroundColor = UIColor.clear btn.frame = CGRect(x: 0, y: SCREEN_HEIGHT - ql_autoHeight(70), width: SCREEN_WIDTH, height: ql_autoHeight(70)) btn.addTarget(self, action: #selector(enterHome), for: .touchUpInside) btn.isHidden = true return btn }() fileprivate let imageArray = ["new_feature_1", "new_feature_2", "new_feature_3", "new_feature_4"] override init(frame: CGRect) { super.init(frame: frame) self.frame = UIScreen.main.bounds setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func enterHome(btn: UIButton) { removeFromSuperview() } } //MARK: - 界面 extension JJANewFeatureView { func setupUI() { let count = imageArray.count let rect = UIScreen.main.bounds for i in 0 ..< count { let iv = UIImageView(image: UIImage(named: imageArray[i])) //设置大小 iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0) iv.isUserInteractionEnabled = true scrollView.addSubview(iv) } scrollView.contentSize = CGSize(width: Double(count + 1) * SCREEN_WIDTH, height: SCREEN_HEIGHT) } } // MARK: - 代理 extension JJANewFeatureView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // 1.滚动到最后一屏, 视图删除 let page = Int(scrollView.contentOffset.x / scrollView.bounds.width) // 2. 判断是否是最后一页 if page == scrollView.subviews.count { removeFromSuperview() } if page == scrollView.subviews.count - 1 { enterBtn.isHidden = false } } }
mit
lllyyy/LY
U17-master/U17/Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQToolbar/IQToolbar.swift
2
9708
// // IQToolbar.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 /** @abstract IQToolbar for IQKeyboardManager. */ open class IQToolbar: UIToolbar , UIInputViewAudioFeedback { private static var _classInitialize: Void = classInitialize() private class func classInitialize() { let appearanceProxy = self.appearance() appearanceProxy.barTintColor = nil let positions : [UIBarPosition] = [.any,.bottom,.top,.topAttached]; for position in positions { appearanceProxy.setBackgroundImage(nil, forToolbarPosition: position, barMetrics: .default) appearanceProxy.setShadowImage(nil, forToolbarPosition: .any) } //Background color appearanceProxy.backgroundColor = nil } /** Previous bar button of toolbar. */ private var privatePreviousBarButton: IQBarButtonItem? open var previousBarButton : IQBarButtonItem { get { if privatePreviousBarButton == nil { privatePreviousBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil) privatePreviousBarButton?.accessibilityLabel = "Toolbar Previous Button" } return privatePreviousBarButton! } set (newValue) { privatePreviousBarButton = newValue } } /** Next bar button of toolbar. */ private var privateNextBarButton: IQBarButtonItem? open var nextBarButton : IQBarButtonItem { get { if privateNextBarButton == nil { privateNextBarButton = IQBarButtonItem(image: nil, style: .plain, target: nil, action: nil) privateNextBarButton?.accessibilityLabel = "Toolbar Next Button" } return privateNextBarButton! } set (newValue) { privateNextBarButton = newValue } } /** Title bar button of toolbar. */ private var privateTitleBarButton: IQTitleBarButtonItem? open var titleBarButton : IQTitleBarButtonItem { get { if privateTitleBarButton == nil { privateTitleBarButton = IQTitleBarButtonItem(title: nil) privateTitleBarButton?.accessibilityLabel = "Toolbar Title Button" } return privateTitleBarButton! } set (newValue) { privateTitleBarButton = newValue } } /** Done bar button of toolbar. */ private var privateDoneBarButton: IQBarButtonItem? open var doneBarButton : IQBarButtonItem { get { if privateDoneBarButton == nil { privateDoneBarButton = IQBarButtonItem(title: nil, style: .done, target: nil, action: nil) privateDoneBarButton?.accessibilityLabel = "Toolbar Done Button" } return privateDoneBarButton! } set (newValue) { privateDoneBarButton = newValue } } override init(frame: CGRect) { _ = IQToolbar._classInitialize super.init(frame: frame) sizeToFit() autoresizingMask = UIViewAutoresizing.flexibleWidth self.isTranslucent = true } required public init?(coder aDecoder: NSCoder) { _ = IQToolbar._classInitialize super.init(coder: aDecoder) sizeToFit() autoresizingMask = UIViewAutoresizing.flexibleWidth self.isTranslucent = true } override open func sizeThatFits(_ size: CGSize) -> CGSize { var sizeThatFit = super.sizeThatFits(size) sizeThatFit.height = 44 return sizeThatFit } override open var tintColor: UIColor! { didSet { if let unwrappedItems = items { for item in unwrappedItems { item.tintColor = tintColor } } } } override open var barStyle: UIBarStyle { didSet { if barStyle == .default { titleBarButton.selectableTextColor = UIColor.init(red: 0.0, green: 0.5, blue: 1.0, alpha: 1) } else { titleBarButton.selectableTextColor = UIColor.yellow } } } override open func layoutSubviews() { super.layoutSubviews() //If running on Xcode9 (iOS11) only then we'll validate for iOS version, otherwise for older versions of Xcode (iOS10 and below) we'll just execute the tweak #if swift(>=3.2) if #available(iOS 11, *) { return } else { var leftRect = CGRect.null var rightRect = CGRect.null var isTitleBarButtonFound = false let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in let x1 = view1.frame.minX let y1 = view1.frame.minY let x2 = view2.frame.minX let y2 = view2.frame.minY if x1 != x2 { return x1 < x2 } else { return y1 < y2 } }) for barButtonItemView in sortedSubviews { if isTitleBarButtonFound == true { rightRect = barButtonItemView.frame break } else if type(of: barButtonItemView) === UIView.self { isTitleBarButtonFound = true //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem) } else if barButtonItemView.isKind(of: UIControl.self) == true { leftRect = barButtonItemView.frame } } var x : CGFloat = 16 if (leftRect.isNull == false) { x = leftRect.maxX + 16 } let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX) if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height) newItem.customView?.frame = titleRect break } } } } #else var leftRect = CGRect.null var rightRect = CGRect.null var isTitleBarButtonFound = false let sortedSubviews = self.subviews.sorted(by: { (view1 : UIView, view2 : UIView) -> Bool in let x1 = view1.frame.minX let y1 = view1.frame.minY let x2 = view2.frame.minX let y2 = view2.frame.minY if x1 != x2 { return x1 < x2 } else { return y1 < y2 } }) for barButtonItemView in sortedSubviews { if isTitleBarButtonFound == true { rightRect = barButtonItemView.frame break } else if type(of: barButtonItemView) === UIView.self { isTitleBarButtonFound = true //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem) } else if barButtonItemView.isKind(of: UIControl.self) == true { leftRect = barButtonItemView.frame } } var x : CGFloat = 16 if (leftRect.isNull == false) { x = leftRect.maxX + 16 } let width : CGFloat = self.frame.width - 32 - (leftRect.isNull ? 0 : leftRect.maxX) - (rightRect.isNull ? 0 : self.frame.width - rightRect.minX) if let unwrappedItems = items { for item in unwrappedItems { if let newItem = item as? IQTitleBarButtonItem { let titleRect = CGRect(x: x, y: 0, width: width, height: self.frame.size.height) newItem.customView?.frame = titleRect break } } } #endif } open var enableInputClicksWhenVisible: Bool { return true } }
mit
DanielFulton/ImageLibraryTests
Pods/ImageLoader/ImageLoader/Manager.swift
1
4755
// // Manager.swift // ImageLoader // // Created by Hirohisa Kawasaki on 12/7/15. // Copyright © 2015 Hirohisa Kawasaki. All rights reserved. // import Foundation import UIKit /** Responsible for creating and managing `Loader` objects and controlling of `NSURLSession` and `ImageCache` */ public class Manager { let session: NSURLSession let cache: ImageLoaderCache let delegate: SessionDataDelegate = SessionDataDelegate() public var automaticallyAdjustsSize = true public var automaticallyAddTransition = true public var automaticallySetImage = true /** Use to kill or keep a fetching image loader when it's blocks is to empty by imageview or anyone. */ public var shouldKeepLoader = false let decompressingQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) public init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), cache: ImageLoaderCache = Disk() ) { session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) self.cache = cache } // MARK: state var state: State { return delegate.isEmpty ? .Ready : .Running } // MARK: loading func load(URL: URLLiteralConvertible) -> Loader { if let loader = delegate[URL.imageLoaderURL] { loader.resume() return loader } let request = NSMutableURLRequest(URL: URL.imageLoaderURL) request.setValue("image/*", forHTTPHeaderField: "Accept") let task = session.dataTaskWithRequest(request) let loader = Loader(task: task, delegate: self) delegate[URL.imageLoaderURL] = loader return loader } func suspend(URL: URLLiteralConvertible) -> Loader? { if let loader = delegate[URL.imageLoaderURL] { loader.suspend() return loader } return nil } func cancel(URL: URLLiteralConvertible, block: Block? = nil) -> Loader? { return cancel(URL, identifier: block?.identifier) } func cancel(URL: URLLiteralConvertible, identifier: Int?) -> Loader? { if let loader = delegate[URL.imageLoaderURL] { if let identifier = identifier { loader.remove(identifier) } if !shouldKeepLoader && loader.blocks.isEmpty { loader.cancel() delegate.remove(URL.imageLoaderURL) } return loader } return nil } class SessionDataDelegate: NSObject, NSURLSessionDataDelegate { let _ioQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) var loaders: [NSURL: Loader] = [:] subscript (URL: NSURL) -> Loader? { get { var loader : Loader? dispatch_sync(_ioQueue) { loader = self.loaders[URL] } return loader } set { if let newValue = newValue { dispatch_barrier_async(_ioQueue) { self.loaders[URL] = newValue } } } } var isEmpty: Bool { var isEmpty = false dispatch_sync(_ioQueue) { isEmpty = self.loaders.isEmpty } return isEmpty } private func remove(URL: NSURL) -> Loader? { if let loader = loaders[URL] { loaders[URL] = nil return loader } return nil } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let URL = dataTask.originalRequest?.URL, loader = self[URL] { loader.receive(data) } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { completionHandler(.Allow) } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let URL = task.originalRequest?.URL, loader = loaders[URL] { loader.complete(error) { [unowned self] in self.remove(URL) } } } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: (NSCachedURLResponse?) -> Void) { completionHandler(nil) } } deinit { session.invalidateAndCancel() } }
mit
VadimPavlov/SMVC
PerfectProject/Classes/Flow/AppFlow.swift
1
1560
// // AppFlow.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import UIKit class AppFlow { let session: Session let navigationController: UINavigationController init(session: Session, navigationController: UINavigationController) { self.session = session self.navigationController = navigationController } } extension AppFlow { func showLogin(animated: Bool) { let login = LoginFlow(session: session) { user in if let user = user { self.showUserScreen(user: user) } } if let login = login { navigationController.present(login.navigationController, animated: animated, completion: nil) login.showSignInScreen() } } func showUserScreen(user: User) { let actions = UserController.Actions() let controller = UserController(actions: actions, user: user) // let completion = { // // let view = UserView() //... somehow from storyboard // controller.view = view // self.navigationController.pushViewController(view, animated: true) // } // // if self.navigationController.presentedViewController != nil { // self.navigationController.dismiss(animated: true, completion: completion) // } else { // completion() // } } func showMainScreen() { } }
mit
Karumi/BothamUI
Example/ExampleAcceptanceTests/XCTestCase.swift
1
522
// // XCTest.swift // Example // // Created by Pedro Vicente Gomez on 26/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation import KIF extension XCTestCase { func tester(file: String = #file, line: Int = #line) -> KIFUITestActor { return KIFUITestActor(inFile: file, atLine: line, delegate: self) } func system(file: String = #file, line: Int = #line) -> KIFSystemTestActor { return KIFSystemTestActor(inFile: file, atLine: line, delegate: self) } }
apache-2.0
xenodium/dotfiles
emacs/yasnippets/personal/swift-mode/shellarguments.swift
2
387
#name : Shell script arguments #key : shellArgs # -- struct Script { let fileName: String let arguments: Arguments struct Arguments { let $1: $2 } init() { fileName = CommandLine.arguments[0] if CommandLine.arguments.count < 2 { fputs("Usage: \\(fileName) $3", stderr) exit(1) } arguments = Arguments($1: CommandLine.arguments[1]) } } $0
bsd-2-clause
nifty-swift/Nifty
Sources/asinh.swift
2
1643
/*************************************************************************************************** * asinh.swift * * This file provides inverse hyperbolic sine functionality. * * Author: Philip Erickson * Creation Date: 1 May 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ /// Return the inverse hyperbolic sine of x—value whose hyperbolic sine is x. #if os(Linux) @_exported import func Glibc.asinh #else @_exported import func Darwin.asinh #endif public func asinh(_ v: Vector<Double>) -> Vector<Double> { let newData = v.data.map({asinh($0)}) return Vector(newData, name: v.name, showName: v.showName) } public func asinh(_ m: Matrix<Double>) -> Matrix<Double> { let newData = m.data.map({asinh($0)}) return Matrix(m.size, newData, name: m.name, showName: m.showName) } public func asinh(_ t: Tensor<Double>) -> Tensor<Double> { let newData = t.data.map({asinh($0)}) return Tensor(t.size, newData, name: t.name, showName: t.showName) }
apache-2.0
ahoppen/swift
test/SymbolGraph/Symbols/Kinds/Struct.swift
22
415
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -module-name Struct -emit-module -emit-module-path %t/ // RUN: %target-swift-symbolgraph-extract -module-name Struct -I %t -pretty-print -output-dir %t // RUN: %FileCheck %s --input-file %t/Struct.symbols.json // CHECK: "identifier": "swift.struct" // CHECK-NEXT: "displayName": "Structure" // CHECK: pathComponents // CHECK-NEXT: "S" public struct S {}
apache-2.0
XQS6LB3A/LyricsX
LyricsX/Controller/AutoActivateWindowController.swift
2
549
// // AutoActivateWindowController.swift // LyricsX - https://github.com/ddddxxx/LyricsX // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // import Cocoa class AutoActivateWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() window?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } }
gpl-3.0
ahoppen/swift
validation-test/compiler_crashers_fixed/01403-swift-modulefile-getdecl.swift
65
469
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A { protocol P { } func b() -> [B } protocol B : d { typealias d
apache-2.0
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/Enrichment.swift
1
2192
/** * (C) Copyright IBM Corp. 2022. * * 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 /** Information about a specific enrichment. */ public struct Enrichment: Codable, Equatable { /** The type of this enrichment. */ public enum TypeEnum: String { case partOfSpeech = "part_of_speech" case sentiment = "sentiment" case naturalLanguageUnderstanding = "natural_language_understanding" case dictionary = "dictionary" case regularExpression = "regular_expression" case uimaAnnotator = "uima_annotator" case ruleBased = "rule_based" case watsonKnowledgeStudioModel = "watson_knowledge_studio_model" case classifier = "classifier" } /** The unique identifier of this enrichment. */ public var enrichmentID: String? /** The human readable name for this enrichment. */ public var name: String? /** The description of this enrichment. */ public var description: String? /** The type of this enrichment. */ public var type: String? /** An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. */ public var options: EnrichmentOptions? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case enrichmentID = "enrichment_id" case name = "name" case description = "description" case type = "type" case options = "options" } }
apache-2.0
ontouchstart/swift3-playground
Learn to Code 2.playgroundbook/Contents/Chapters/Document13.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/Assessments.swift
1
1121
// // Assessments.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // let success = "### Amazing! \nYou’ve started combining all of your coding skills in new and useful ways. Next, you'll see how to place a different type of item-a portal. \n\n[**Next Page**](@next)" let hints = [ "You'll need to make multiple [instances](glossary://instance) of the `Block` [type](glossary://type), and place them in locations that will enable you to solve the puzzle.", "By stacking one block on top of another, you may be able to cross bridges of higher elevations.", "Use the same `world.place` [method](glossary://method) as you used in the previous exercise.", "The placement code for one block might look something like this: `world.place(block1, atColumn: 2, row: 2)`.", "This puzzle is a **Challenge** and has no provided solution. Strengthen your coding skills by creating your own approach to solve it." ] let solution: String? = nil public func assessmentPoint() -> AssessmentResults { return updateAssessment(successMessage: success, failureHints: hints, solution: solution) }
mit
vandilsonlima/VLPin
VLPin/Classes/UIView+VLPin_Size.swift
1
1815
// // UIView+VLPin_Size.swift // Pods-VLPin_Example // // Created by Vandilson Lima on 09/07/17. // import UIKit public extension UIView { @discardableResult public func makeWidth(equalTo width: CGFloat, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { translatesAutoresizingMaskIntoConstraints = false let constraint = widthAnchor.constraint(equalToConstant: width) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult public func makeWidth(equalTo view: UIView, multiplier: CGFloat = 1, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: multiplier) return make(view: view, constraint: constraint, priority: priority) } @discardableResult public func makeHeight(equalTo height: CGFloat, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { translatesAutoresizingMaskIntoConstraints = false let constraint = heightAnchor.constraint(equalToConstant: height) constraint.priority = priority constraint.isActive = true return constraint } @discardableResult public func makeHeight(equalTo view: UIView, multiplier: CGFloat = 1, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { let constraint = heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: multiplier) return make(view: view, constraint: constraint, priority: priority) } }
mit
theisegeberg/BasicJSON
BasicJSON/PureJSON.swift
1
650
// // BasicJSON.swift // BasicJSON // // Created by Theis Egeberg on 20/04/2017. // Copyright © 2017 Theis Egeberg. All rights reserved. // import Foundation public typealias RawJSON = [String:Any] public typealias PureJSONValue = [String:JSONRepresentable] public struct PureJSON { public let value: PureJSONValue init() { value = PureJSONValue() } init(raw: RawJSON) { value = JSON.purify(raw: raw) } public subscript(key: String) -> JSONRepresentable { get { if let value = self.value[key] { return value } return "" } } }
mit
itouch2/LeetCode
LeetCode/H-Index.swift
1
1331
// // H-Index.swift // LeetCode // // Created by You Tu on 2017/5/24. // Copyright © 2017年 You Tu. All rights reserved. // /* Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3. Note: If there are several possible values for h, the maximum one is taken as the h-index. */ import Cocoa class H_Index: NSObject { func hIndex(_ citations: [Int]) -> Int { if citations.count == 0 { return 0; } let sorted = citations.sorted{ $0 > $1 } var t = 0 for i in 0 ..< sorted.count { if (i + 1) >= sorted[i] { return max(sorted[i], t) } else { t = i + 1 } } return t } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/28318-swift-constraints-constraintgraphnode-getmembertype.swift
1
475
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck // REQUIRES: asserts protocol A{ protocol A typealias e:A}struct c<I:A for c
apache-2.0
adrfer/swift
validation-test/compiler_crashers_fixed/27286-swift-extensiondecl-getmembers.swift
13
277
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d{{struct f{struct a{let b{{}{b=(}}}}{{}{}{var:{extension
apache-2.0
cxpyear/ZSZQApp
spdbapp/spdbapp/AppDelegate.swift
1
2938
// // AppDelegate.swift // spdbapp // // Created by tommy on 15/5/7. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit var server = Server() var current = GBCurrent() var totalMembers = NSArray() var member = GBMember() var bNeedLogin = true var appManager = AppManager() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundTransferCompletionHandler:(() -> Void)? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UIApplication.sharedApplication().idleTimerDisabled = true return true } func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { self.backgroundTransferCompletionHandler = completionHandler } 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. // NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsSettingsChanged", name: NSUserDefaultsDidChangeNotification, object: nil) } func applicationWillEnterForeground(application: UIApplication) { // var defaults = NSUserDefaults.standardUserDefaults() // defaults.synchronize() // 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:. UIApplication.sharedApplication().idleTimerDisabled = false } }
bsd-3-clause
mapsme/omim
iphone/Chart/Chart/Views/ChartXAxisView.swift
5
2792
import UIKit fileprivate class ChartXAxisInnerView: UIView { var lowerBound = 0 var upperBound = 0 var steps: [String] = [] var labels: [UILabel] = [] var font: UIFont = UIFont.systemFont(ofSize: 12, weight: .regular) { didSet { labels.forEach { $0.font = font } } } var textColor: UIColor = UIColor(white: 0, alpha: 0.3) { didSet { labels.forEach { $0.textColor = textColor } } } override var frame: CGRect { didSet { if upperBound > 0 { updateLabels() } } } func makeLabel(text: String) -> UILabel { let label = UILabel() label.font = font label.textColor = textColor label.text = text label.frame = CGRect(x: 0, y: 0, width: 50, height: 15) return label } func setBounds(lower: Int, upper: Int, steps: [String]) { lowerBound = lower upperBound = upper self.steps = steps labels.forEach { $0.removeFromSuperview() } labels.removeAll() for i in 0..<steps.count { let step = steps[i] let label = makeLabel(text: step) if i == 0 { label.textAlignment = .left } else if i == steps.count - 1 { label.textAlignment = .right } else { label.textAlignment = .center } labels.append(label) addSubview(label) } updateLabels() } func updateLabels() { let step = CGFloat(upperBound - lowerBound) / CGFloat(labels.count - 1) for i in 0..<labels.count { let x = bounds.width * step * CGFloat(i) / CGFloat(upperBound - lowerBound) let l = labels[i] var f = l.frame let adjust = bounds.width > 0 ? x / bounds.width : 0 f.origin = CGPoint(x: x - f.width * adjust, y: 0) l.frame = f.integral } } } class ChartXAxisView: UIView { var lowerBound = 0 var upperBound = 0 var values: [String] = [] var font: UIFont = UIFont.systemFont(ofSize: 12, weight: .regular) { didSet { labelsView?.font = font } } var textColor: UIColor = UIColor(white: 0, alpha: 0.3) { didSet { labelsView?.textColor = textColor } } private var labelsView: ChartXAxisInnerView? func setBounds(lower: Int, upper: Int) { lowerBound = lower upperBound = upper let step = CGFloat(upper - lower) / 5 var steps: [String] = [] for i in 0..<5 { let x = lower + Int(round(step * CGFloat(i))) steps.append(values[x]) } steps.append(values[upper]) let lv = ChartXAxisInnerView() lv.frame = bounds lv.textColor = textColor lv.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(lv) if let labelsView = labelsView { labelsView.removeFromSuperview() } lv.setBounds(lower: lower, upper: upper, steps: steps) labelsView = lv } }
apache-2.0
gxfeng/iOS-
MineViewController.swift
1
860
// // MineViewController.swift // ProjectSwift // // Created by ZJQ on 2016/12/22. // Copyright © 2016年 ZJQ. All rights reserved. // import UIKit class MineViewController: RootViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
JackLearning/Weibo
MainViewController.swift
1
865
// // MainViewController.swift // Weibo // // Created by apple on 15/12/13. // Copyright © 2015年 apple. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
BoltApp/bolt-ios
BoltExample/BoltExample/BoltAPI/BLTApiIManger.swift
1
7518
// // BLTNetworkManager.swift // BoltAPI // // Created by Bolt. // Copyright © 2018 Bolt. All rights reserved. // import Foundation enum BLTApiManagerError: Error, LocalizedError { case responseError(error: String) case responseErrors(errors: [String]) case tokenNotFound case badRequestData case badResponseData case createOrderFail var errorDescription: String? { switch self { case .responseError(let error): return NSLocalizedString(error, comment: "") case .responseErrors(let errors): return NSLocalizedString("\(errors)", comment: "") case .tokenNotFound: return NSLocalizedString("Token not found", comment: "") case .badRequestData: return NSLocalizedString("Bad request data", comment: "") case .createOrderFail: return NSLocalizedString("Create order fail", comment: "") case .badResponseData: return NSLocalizedString("Bad response data", comment: "") } } } class BLTNetworkService { /// fileprivate enum BLTEndpoint { case createOrder var path: String { switch self { case .createOrder: return "/v1/merchant/orders" } } } /// enum BLTApiUrl: String { case sandbox = "https://api-sandbox.bolt.com" case production = "https://api.bolt.com" } /// This is issued to process voids, captures and refunds from backoffice. let apiKey: String /// This is the URL used to communicate with Bolt's backend. let apiURL: String fileprivate func requestUrl(endpoint: BLTEndpoint) -> String { return apiURL + endpoint.path } // MARK: Initialization /** . - Parameter apiKey: . - Parameter apiUrl: . - Returns: */ internal init(apiKey: String, apiUrl: BLTApiUrl) { self.apiKey = apiKey self.apiURL = apiUrl.rawValue } // MARK: Request /** Create order with order data. - Parameter order: Order info. - Parameter successHandler: Returns orderID for checkout process */ public func createOrder(_ order: BLTOrder, successHandler: @escaping ((_ orderID: String) -> Swift.Void), errorHandler: @escaping ((_ error: Error) -> Swift.Void)) { guard let orderParameters = try? order.asDictionary(), let encodedOrder = try? JSONEncoder().encode(order), let jsonStringOrder = String(data: encodedOrder, encoding: .utf8), let postData = try? JSONSerialization.data(withJSONObject: orderParameters, options: []) else { errorHandler(BLTApiManagerError.badRequestData) return } let contentLength = "\(jsonStringOrder.count)" let xNonce = generateXNonce() let apiKey = self.apiKey let headers: [String : String] = ["Content-Type" : "application/json", "X-Api-Key" : apiKey, "Content-Length" : contentLength, "X-Nonce" : xNonce, "cache-control" : "no-cache"] let url = URL(string: requestUrl(endpoint: .createOrder))! var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = postData as Data DispatchQueue.global(qos: .background).async { let task = URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { guard error == nil else { errorHandler(error!) return } guard let httpResponse = response as? HTTPURLResponse else { errorHandler(BLTApiManagerError.createOrderFail) return } guard let data = data else { errorHandler(BLTApiManagerError.badResponseData) return } if let responseError = self.getErrorFromResponse(data: data, response: httpResponse) { errorHandler(responseError) return } guard let decodedJson = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject], let decodedData = decodedJson else { errorHandler(BLTApiManagerError.badResponseData) return } if let errors = decodedData["errors"] as? [String] { errorHandler(BLTApiManagerError.responseErrors(errors: errors)) return } else { if let token = decodedData["token"] as? String { successHandler(token) } else { errorHandler(BLTApiManagerError.tokenNotFound) return } } } } task.resume() } } // MARK: Helper public func getErrorFromResponse(data: Data, response: HTTPURLResponse) -> Error? { let statusCode = String(response.statusCode) let errorMessage = "Error: \(statusCode)" if response.statusCode != 200 && response.statusCode != 201 { print("statusCode should be 200, but is \(response.statusCode)") print("response = \(String(describing: response))") do { guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { return BLTApiManagerError.responseError(error: errorMessage) } if let errors = json["errors"] as? [String] { return BLTApiManagerError.responseErrors(errors: errors) } else if let errorMessage = json["error"] as? String { return BLTApiManagerError.responseError(error: errorMessage) } } catch let error as NSError { return error } return BLTApiManagerError.responseError(error: errorMessage) } return nil } /// A unique 12-16 digit for every request. Generated by the merchant. func generateXNonce() -> String { func random(digits: Int) -> Int { let min = Int(pow(Double(10), Double(digits-1))) - 1 let max = Int(pow(Double(10), Double(digits))) - 1 return Int.random(in: min...max) } let digitsCount = Int.random(in: 12...16) let value = random(digits: digitsCount) let nonce = "\(value)" return nonce } } extension Encodable { func asDictionary() throws -> [String: Any] { let data = try JSONEncoder().encode(self) guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { throw NSError() } return dictionary } }
mit
jlyu/swift-demo
Hypnosister/HypnosisterTests/HypnosisterTests.swift
1
890
// // HypnosisterTests.swift // HypnosisterTests // // Created by chain on 14-6-20. // Copyright (c) 2014年 chain. All rights reserved. // import XCTest class HypnosisterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
khizkhiz/swift
test/Interpreter/SDK/CoreGraphics_CGFloat.swift
2
3592
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // XFAIL: interpret import CoreGraphics import Foundation import StdlibUnittest var CGFloatTestSuite = TestSuite("CGFloat") CGFloatTestSuite.test("literals") { var flt: CGFloat = 4.125 expectEqual(4.125, flt) flt = 42 expectEqual(42, flt) } CGFloatTestSuite.test("init") { expectEqual(0.0, CGFloat()) expectEqual(4.125, CGFloat(Float(4.125))) expectEqual(4.125, CGFloat(Double(4.125))) expectEqual(42, CGFloat(Int(42))) expectEqual(42, CGFloat(Int8(42))) expectEqual(42, CGFloat(Int16(42))) expectEqual(42, CGFloat(Int32(42))) expectEqual(42, CGFloat(Int64(42))) expectEqual(42, CGFloat(UInt(42))) expectEqual(42, CGFloat(UInt8(42))) expectEqual(42, CGFloat(UInt16(42))) expectEqual(42, CGFloat(UInt32(42))) expectEqual(42, CGFloat(UInt64(42))) } CGFloatTestSuite.test("initOtherTypesFromCGFloat") { let flt: CGFloat = 4.125 expectEqual(4.125, Float(flt)) expectEqual(4.125, Double(flt)) expectEqual(4, Int(flt)) expectEqual(4, Int8(flt)) expectEqual(4, Int16(flt)) expectEqual(4, Int32(flt)) expectEqual(4, Int64(flt)) expectEqual(4, UInt(flt)) expectEqual(4, UInt8(flt)) expectEqual(4, UInt16(flt)) expectEqual(4, UInt32(flt)) expectEqual(4, UInt64(flt)) } CGFloatTestSuite.test("comparisons") { let x = 3.14 let y = 3.14 let z = 2.71 expectTrue(x == y) expectFalse(x != y) checkHashable(true, x, y) expectFalse(x == z) expectTrue(x != z) checkHashable(false, x, z) expectFalse(x < z) expectFalse(x <= z) expectTrue(x >= z) expectTrue(x > z) checkComparable(.gt, x, z) expectTrue(z < x) expectTrue(z <= x) expectFalse(z >= x) expectFalse(z > x) checkComparable(.lt, z, x) expectFalse(x < y) expectTrue(x <= y) expectTrue(x >= y) expectFalse(x > y) checkComparable(.eq, x, y) } CGFloatTestSuite.test("arithmetic") { let x: CGFloat = 0.25 let y: CGFloat = 4 let z: CGFloat = 0.5 expectEqual(4.25, x + y) expectEqual(-3.75, x - y) expectEqual(1.0, x * y) expectEqual(0.0625, x / y) expectEqual(0.25, x % z) } CGFloatTestSuite.test("striding") { if true { var result = [CGFloat]() for f in stride(from: (1.0 as CGFloat), to: 2.0, by: 0.5) { result.append(f) } expectEqual([ 1.0, 1.5 ], result) } if true { var result = [CGFloat]() for f in stride(from: (1.0 as CGFloat), through: 2.0, by: 0.5) { result.append(f) } expectEqual([ 1.0, 1.5, 2.0 ], result) } } CGFloatTestSuite.test("bridging") { // Bridging to NSNumber. if true { let flt: CGFloat = 4.125 // CGFloat -> NSNumber conversion. let nsnum: NSNumber = flt as NSNumber expectEqual("4.125", "\(nsnum)") // NSNumber -> CGFloat let bridgedBack: CGFloat = nsnum as! CGFloat expectEqual(flt, bridgedBack) } // Array bridging. if true { let originalArray: [CGFloat] = [ 4.125, 10.625 ] // Array -> NSArray let nsarr: NSArray = originalArray as NSArray expectEqual(2, nsarr.count) expectEqual("4.125", "\(nsarr[0])") expectEqual("10.625", "\(nsarr[1])") // NSArray -> Array expectEqualSequence(originalArray, nsarr as! [CGFloat]) } } CGFloatTestSuite.test("varargs") { let v: CVarArg = CGFloat(0) expectEqual( "0.023230", NSString(format: "%.6f", CGFloat(0.02323) as CVarArg)) expectEqual( "0.123450", NSString(format: "%.6f", CGFloat(0.12345) as CVarArg)) expectEqual( "1.234560", NSString(format: "%.6f", CGFloat(1.23456) as CVarArg)) } runAllTests()
apache-2.0
touchopia/HackingWithSwift
project38/Project38/Commit+CoreDataClass.swift
2
242
// // Commit+CoreDataClass.swift // Project38 // // Created by TwoStraws on 26/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import Foundation import CoreData @objc(Commit) public class Commit: NSManagedObject { }
unlicense
gcba/usig-normalizador-ios
Example/ViewController.swift
1
4298
// // ViewController.swift // Example // // Created by Rita Zerrizuela on 9/28/17. // Copyright © 2017 GCBA. All rights reserved. // import UIKit import CoreLocation import USIGNormalizador class ViewController: UIViewController { fileprivate var currentAddress: USIGNormalizadorAddress? fileprivate let locationManager = CLLocationManager() fileprivate var showPin = true fileprivate var forceNormalization = true fileprivate var includePlaces = true fileprivate var cabaOnly = true // MARK: - Outlets @IBOutlet weak var searchLabel: UILabel! @IBOutlet weak var searchButton: UIButton! @IBOutlet weak var geoLabel: UILabel! @IBOutlet weak var geoButton: UIButton! @IBOutlet weak var pinSwitch: UISwitch! @IBOutlet weak var mandatorySwitch: UISwitch! @IBOutlet weak var placesSwitch: UISwitch! @IBOutlet weak var cabaSwitch: UISwitch! // MARK: - Actions @IBAction func pinSwitchValueChanged(_ sender: Any) { showPin = pinSwitch.isOn } @IBAction func mandatorySwitchValueChanged(_ sender: Any) { forceNormalization = mandatorySwitch.isOn } @IBAction func placesSwitchValueChanged(_ sender: Any) { includePlaces = placesSwitch.isOn } @IBAction func cabaSwitchValueChanged(_ sender: Any) { cabaOnly = cabaSwitch.isOn } @IBAction func searchButtonTapped(sender: UIButton) { let searchController = USIGNormalizador.searchController() let navigationController = UINavigationController(rootViewController: searchController) searchController.delegate = self searchController.edit = searchLabel.text present(navigationController, animated: true, completion: nil) } @IBAction func geoButtonTapped(sender: UIButton) { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() requestLocation() } // MARK: - Overrides override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override func viewDidLoad() { super.viewDidLoad() searchLabel.sizeToFit() geoLabel.sizeToFit() } // MARK: - Location fileprivate func requestLocation() { guard CLLocationManager.authorizationStatus() == .authorizedWhenInUse, let currentLocation = locationManager.location else { return } USIGNormalizador.location(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude) { result, error in DispatchQueue.main.async { self.geoLabel.text = result?.address ?? error?.message } } } } extension ViewController: USIGNormalizadorControllerDelegate { func exclude(_ searchController: USIGNormalizadorController) -> String { return cabaOnly ? USIGNormalizadorExclusions.AMBA.rawValue : "" } func shouldShowPin(_ searchController: USIGNormalizadorController) -> Bool { return showPin } func shouldForceNormalization(_ searchController: USIGNormalizadorController) -> Bool { return forceNormalization } func shouldIncludePlaces(_ searchController: USIGNormalizadorController) -> Bool { return includePlaces } func didSelectValue(_ searchController: USIGNormalizadorController, value: USIGNormalizadorAddress) { currentAddress = value DispatchQueue.main.async { self.searchLabel.text = value.address } } func didSelectPin(_ searchController: USIGNormalizadorController) { DispatchQueue.main.async { self.searchLabel.text = "PIN" } } func didSelectUnnormalizedAddress(_ searchController: USIGNormalizadorController, value: String) { DispatchQueue.main.async { self.searchLabel.text = value } } func didCancelSelection(_ searchController: USIGNormalizadorController) { DispatchQueue.main.async { self.searchLabel.text = "CANCELADO" } } } extension ViewController: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { requestLocation() } }
mit
radazzouz/firefox-ios
Storage/SQL/BrowserTable.swift
1
40868
/* 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 import XCGLogger let BookmarksFolderTitleMobile: String = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let BookmarksFolderTitleMenu: String = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let BookmarksFolderTitleToolbar: String = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let BookmarksFolderTitleUnsorted: String = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let _TableBookmarks = "bookmarks" // Removed in v12. Kept for migration. let TableBookmarksMirror = "bookmarksMirror" // Added in v9. let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10. let TableBookmarksBuffer = "bookmarksBuffer" // Added in v12. bookmarksMirror is renamed to bookmarksBuffer. let TableBookmarksBufferStructure = "bookmarksBufferStructure" // Added in v12. let TableBookmarksLocal = "bookmarksLocal" // Added in v12. Supersedes 'bookmarks'. let TableBookmarksLocalStructure = "bookmarksLocalStructure" // Added in v12. let TableFavicons = "favicons" let TableHistory = "history" let TableCachedTopSites = "cached_top_sites" let TableDomains = "domains" let TableVisits = "visits" let TableFaviconSites = "favicon_sites" let TableQueuedTabs = "queue" let TableActivityStreamBlocklist = "activity_stream_blocklist" let TablePageMetadata = "page_metadata" let ViewBookmarksBufferOnMirror = "view_bookmarksBuffer_on_mirror" let ViewBookmarksBufferStructureOnMirror = "view_bookmarksBufferStructure_on_mirror" let ViewBookmarksLocalOnMirror = "view_bookmarksLocal_on_mirror" let ViewBookmarksLocalStructureOnMirror = "view_bookmarksLocalStructure_on_mirror" let ViewAllBookmarks = "view_all_bookmarks" let ViewAwesomebarBookmarks = "view_awesomebar_bookmarks" let ViewAwesomebarBookmarksWithIcons = "view_awesomebar_bookmarks_with_favicons" let ViewHistoryVisits = "view_history_visits" let ViewWidestFaviconsForSites = "view_favicons_widest" let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon" let ViewIconForURL = "view_icon_for_url" let IndexHistoryShouldUpload = "idx_history_should_upload" let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6. let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6. let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10. let IndexBookmarksLocalStructureParentIdx = "idx_bookmarksLocalStructure_parent_idx" // Added in v12. let IndexBookmarksBufferStructureParentIdx = "idx_bookmarksBufferStructure_parent_idx" // Added in v12. let IndexBookmarksMirrorStructureChild = "idx_bookmarksMirrorStructure_child" // Added in v14. let IndexPageMetadataCacheKey = "idx_page_metadata_cache_key_uniqueindex" // Added in v19 private let AllTables: [String] = [ TableDomains, TableFavicons, TableFaviconSites, TableHistory, TableVisits, TableCachedTopSites, TableBookmarksBuffer, TableBookmarksBufferStructure, TableBookmarksLocal, TableBookmarksLocalStructure, TableBookmarksMirror, TableBookmarksMirrorStructure, TableQueuedTabs, TableActivityStreamBlocklist, TablePageMetadata, ] private let AllViews: [String] = [ ViewHistoryIDsWithWidestFavicons, ViewWidestFaviconsForSites, ViewIconForURL, ViewBookmarksBufferOnMirror, ViewBookmarksBufferStructureOnMirror, ViewBookmarksLocalOnMirror, ViewBookmarksLocalStructureOnMirror, ViewAllBookmarks, ViewAwesomebarBookmarks, ViewAwesomebarBookmarksWithIcons, ViewHistoryVisits ] private let AllIndices: [String] = [ IndexHistoryShouldUpload, IndexVisitsSiteIDIsLocalDate, IndexBookmarksBufferStructureParentIdx, IndexBookmarksLocalStructureParentIdx, IndexBookmarksMirrorStructureParentIdx, IndexBookmarksMirrorStructureChild, IndexPageMetadataCacheKey ] private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables private let log = Logger.syncLogger /** * The monolithic class that manages the inter-related history etc. tables. * We rely on SQLiteHistory having initialized the favicon table first. */ open class BrowserTable: Table { static let DefaultVersion = 21 // Bug 1253656. // TableInfo fields. var name: String { return "BROWSER" } var version: Int { return BrowserTable.DefaultVersion } let sqliteVersion: Int32 let supportsPartialIndices: Bool public init() { let v = sqlite3_libversion_number() self.sqliteVersion = v self.supportsPartialIndices = v >= 3008000 // 3.8.0. let ver = String(cString: sqlite3_libversion()) log.info("SQLite version: \(ver) (\(v)).") } func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { let err = db.executeChange(sql, withArgs: args) if err != nil { log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)") log.error("SQL was \(sql)") } return err == nil } // TODO: transaction. func run(_ db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool { for (sql, args) in queries { if !run(db, sql: sql, args: args) { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool { for (sql, args) in queries { if let sql = sql { if !run(db, sql: sql, args: args) { return false } } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { return self.run(db, queries: optFilter(queries)) } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let now = Date.nowNumber() let status = SyncStatus.new.rawValue let localArgs: Args = [ BookmarkRoots.RootID, BookmarkRoots.RootGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarkRoots.RootGUID, status, now, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarkRoots.RootGUID, status, now, ] // Compute these args using the sequence in RootChildren, rather than hard-coding. var idx = 0 var structureArgs = Args() structureArgs.reserveCapacity(BookmarkRoots.RootChildren.count * 3) BookmarkRoots.RootChildren.forEach { guid in structureArgs.append(BookmarkRoots.RootGUID) structureArgs.append(guid) structureArgs.append(idx) idx += 1 } // Note that we specify an empty title and parentName for these records. We should // never need a parentName -- we don't use content-based reconciling or // reparent these -- and we'll use the current locale's string, retrieved // via titleForSpecialGUID, if necessary. let local = "INSERT INTO \(TableBookmarksLocal) " + "(id, guid, type, parentid, title, parentName, sync_status, local_modified) VALUES " + Array(repeating: "(?, ?, ?, ?, '', '', ?, ?)", count: BookmarkRoots.RootChildren.count + 1).joined(separator: ", ") let structure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES " + Array(repeating: "(?, ?, ?)", count: BookmarkRoots.RootChildren.count).joined(separator: ", ") return self.run(db, queries: [(local, localArgs), (structure, structureArgs)]) } let topSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" + "historyID INTEGER, " + "url TEXT NOT NULL, " + "title TEXT NOT NULL, " + "guid TEXT NOT NULL UNIQUE, " + "domain_id INTEGER, " + "domain TEXT NO NULL, " + "localVisitDate REAL, " + "remoteVisitDate REAL, " + "localVisitCount INTEGER, " + "remoteVisitCount INTEGER, " + "iconID INTEGER, " + "iconURL TEXT, " + "iconDate REAL, " + "iconType INTEGER, " + "iconWidth INTEGER, " + "frecencies REAL" + ")" let domainsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" let queueTableCreate = "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " let activityStreamBlocklistCreate = "CREATE TABLE IF NOT EXISTS \(TableActivityStreamBlocklist) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP " + ") " let pageMetadataCreate = "CREATE TABLE IF NOT EXISTS \(TablePageMetadata) (" + "id INTEGER PRIMARY KEY, " + "cache_key LONGVARCHAR UNIQUE, " + "site_url TEXT, " + "media_url LONGVARCHAR, " + "title TEXT, " + "type VARCHAR(32), " + "description TEXT, " + "provider_name TEXT, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " + "expired_at LONG" + ") " let indexPageMetadataCreate = "CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataCacheKey) ON page_metadata (cache_key)" let iconColumns = ", faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL" let mirrorColumns = ", is_overridden TINYINT NOT NULL DEFAULT 0" let serverColumns = ", server_modified INTEGER NOT NULL" + // Milliseconds. ", hasDupe TINYINT NOT NULL DEFAULT 0" // Boolean, 0 (false) if deleted. let localColumns = ", local_modified INTEGER" + // Can be null. Client clock. In extremis only. ", sync_status TINYINT NOT NULL" // SyncStatus enum. Set when changed or created. func getBookmarksTableCreationStringForTable(_ table: String, withAdditionalColumns: String="") -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = "CREATE TABLE IF NOT EXISTS \(table) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. // Record/envelope metadata that'll allow us to do merges. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", parentid TEXT" + // GUID ", parentName TEXT" + // Type-specific fields. These should be NOT NULL in many cases, but we're going // for a sparse schema, so this'll do for now. Enforce these in the application code. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES withAdditionalColumns + ", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" + ", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" + ")" return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksStructureTableCreationStringForTable(_ table: String, referencingMirror mirror: String) -> String { let sql = "CREATE TABLE IF NOT EXISTS \(table) " + "( parent TEXT NOT NULL REFERENCES \(mirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" return sql } fileprivate let bufferBookmarksView = "CREATE VIEW \(ViewBookmarksBufferOnMirror) AS " + "SELECT" + " -1 AS id" + ", mirror.guid AS guid" + ", mirror.type AS type" + ", mirror.is_deleted AS is_deleted" + ", mirror.parentid AS parentid" + ", mirror.parentName AS parentName" + ", mirror.feedUri AS feedUri" + ", mirror.siteUri AS siteUri" + ", mirror.pos AS pos" + ", mirror.title AS title" + ", mirror.description AS description" + ", mirror.bmkUri AS bmkUri" + ", mirror.keyword AS keyword" + ", mirror.folderName AS folderName" + ", null AS faviconID" + ", 0 AS is_overridden" + // LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer. // We don't have an is_overridden flag to help us here. " FROM \(TableBookmarksMirror) mirror LEFT JOIN" + " \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" + " WHERE buffer.guid IS NULL" + " UNION ALL " + "SELECT" + " -1 AS id" + ", guid" + ", type" + ", is_deleted" + ", parentid" + ", parentName" + ", feedUri" + ", siteUri" + ", pos" + ", title" + ", description" + ", bmkUri" + ", keyword" + ", folderName" + ", null AS faviconID" + ", 1 AS is_overridden" + " FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" // TODO: phrase this without the subselect… fileprivate let bufferBookmarksStructureView = // We don't need to exclude deleted parents, because we drop those from the structure // table when we see them. "CREATE VIEW \(ViewBookmarksBufferStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksBufferStructure) " + "UNION ALL " + // Exclude anything from the mirror that's present in the buffer -- dynamic is_overridden. "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "LEFT JOIN \(TableBookmarksBuffer) ON parent = guid WHERE guid IS NULL" fileprivate let localBookmarksView = "CREATE VIEW \(ViewBookmarksLocalOnMirror) AS " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri," + " siteUri, pos, title, description, bmkUri, folderName, faviconID, NULL AS local_modified, server_modified, 0 AS is_overridden " + "FROM \(TableBookmarksMirror) WHERE is_overridden IS NOT 1 " + "UNION ALL " + "SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri, siteUri, pos, title, description, bmkUri, folderName, faviconID," + " local_modified, NULL AS server_modified, 1 AS is_overridden " + "FROM \(TableBookmarksLocal) WHERE is_deleted IS NOT 1" // TODO: phrase this without the subselect… fileprivate let localBookmarksStructureView = "CREATE VIEW \(ViewBookmarksLocalStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksLocalStructure) " + "WHERE " + "((SELECT is_deleted FROM \(TableBookmarksLocal) WHERE guid = parent) IS NOT 1) " + "UNION ALL " + "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "WHERE " + "((SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = parent) IS NOT 1) " // This view exists only to allow for text searching of URLs and titles in the awesomebar. // As such, we cheat a little: we include buffer, non-overridden mirror, and local. // Usually this will be indistinguishable from a more sophisticated approach, and it's way // easier. fileprivate let allBookmarksView = "CREATE VIEW \(ViewAllBookmarks) AS " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksMirror) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksLocal) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, -1 AS faviconID FROM " + "\(TableBookmarksBuffer) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0" // This smushes together remote and local visits. So it goes. fileprivate let historyVisitsView = "CREATE VIEW \(ViewHistoryVisits) AS " + "SELECT h.url AS url, MAX(v.date) AS visitDate, h.domain_id AS domain_id FROM " + "\(TableHistory) h JOIN \(TableVisits) v ON v.siteID = h.id " + "GROUP BY h.id" // Join all bookmarks against history to find the most recent visit. // visits. fileprivate let awesomebarBookmarksView = "CREATE VIEW \(ViewAwesomebarBookmarks) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.faviconID AS faviconID, " + "h.visitDate AS visitDate " + "FROM \(ViewAllBookmarks) b " + "LEFT JOIN " + "\(ViewHistoryVisits) h ON b.url = h.url" fileprivate let awesomebarBookmarksWithIconsView = "CREATE VIEW \(ViewAwesomebarBookmarksWithIcons) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.visitDate AS visitDate, " + "f.id AS iconID, f.url AS iconURL, f.date AS iconDate, " + "f.type AS iconType, f.width AS iconWidth " + "FROM \(ViewAwesomebarBookmarks) b " + "LEFT JOIN " + "\(TableFavicons) f ON f.id = b.faviconID" func create(_ db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS \(TableFavicons) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " let history = "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " // Locally we track faviconID. // Local changes end up in the mirror, so we track it there too. // The buffer and the mirror additionally track some server metadata. let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksBuffer = getBookmarksTableCreationStringForTable(TableBookmarksBuffer, withAdditionalColumns: self.serverColumns) let bookmarksBufferStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksBufferStructure, referencingMirror: TableBookmarksBuffer) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" let queries: [String] = [ self.domainsTableCreate, history, favicons, visits, bookmarksBuffer, bookmarksBufferStructure, bookmarksLocal, bookmarksLocalStructure, bookmarksMirror, bookmarksMirrorStructure, indexBufferStructureParentIdx, indexLocalStructureParentIdx, indexMirrorStructureParentIdx, indexMirrorStructureChild, faviconSites, indexShouldUpload, indexSiteIDDate, widestFavicons, historyIDsWithIcon, iconForURL, pageMetadataCreate, indexPageMetadataCreate, self.queueTableCreate, self.topSitesTableCreate, self.localBookmarksView, self.localBookmarksStructureView, self.bufferBookmarksView, self.bufferBookmarksStructureView, allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView, activityStreamBlocklistCreate ] assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?") log.debug("Creating \(queries.count) tables, views, and indices.") return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = BrowserTable.DefaultVersion if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from == 0 { // This is likely an upgrade from before Bug 1160399. log.debug("Updating browser tables from zero. Assuming drop and recreate.") return drop(db) && create(db) } if from > to { // This is likely an upgrade from before Bug 1160399. log.debug("Downgrading browser tables. Assuming drop and recreate.") return drop(db) && create(db) } log.debug("Updating browser tables from \(from) to \(to).") if from < 4 && to >= 4 { return drop(db) && create(db) } if from < 5 && to >= 5 { if !self.run(db, sql: self.queueTableCreate) { return false } } if from < 6 && to >= 6 { if !self.run(db, queries: [ "DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", self.domainsTableCreate, "ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", ]) { return false } let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL", factory: { $0["url"] as! String }) if !fillDomainNamesFromCursor(urls, db: db) { return false } } if from < 8 && to == 8 { // Nothing to do: we're just shifting the favicon table to be owned by this class. return true } if from < 9 && to >= 9 { if !self.run(db, sql: getBookmarksTableCreationStringForTable(TableBookmarksMirror)) { return false } } if from < 10 && to >= 10 { if !self.run(db, sql: getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)) { return false } let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" if !self.run(db, sql: indexStructureParentIdx) { return false } } if from < 11 && to >= 11 { if !self.run(db, sql: self.topSitesTableCreate) { return false } } if from < 12 && to >= 12 { let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let prep = [ // Drop indices. "DROP INDEX IF EXISTS idx_bookmarksMirrorStructure_parent_idx", // Rename the old mirror tables to buffer. // The v11 one is the same shape as the current buffer table. "ALTER TABLE \(TableBookmarksMirror) RENAME TO \(TableBookmarksBuffer)", "ALTER TABLE \(TableBookmarksMirrorStructure) RENAME TO \(TableBookmarksBufferStructure)", // Create the new mirror and local tables. bookmarksLocal, bookmarksMirror, bookmarksLocalStructure, bookmarksMirrorStructure, ] // Only migrate bookmarks. The only folders are our roots, and we'll create those later. // There should be nothing else in the table, and no structure. // Our old bookmarks table didn't have creation date, so we use the current timestamp. let modified = Date.now() let status = SyncStatus.new.rawValue // We don't specify a title, expecting it to be generated on the fly, because we're smarter than Android. // We also don't migrate the 'id' column; we'll generate new ones that won't conflict with our roots. let migrateArgs: Args = [BookmarkRoots.MobileFolderGUID] let migrateLocal = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, faviconID, local_modified, sync_status, parentid, parentName) " + "SELECT guid, type, url AS bmkUri, title, faviconID, " + "\(modified) AS local_modified, \(status) AS sync_status, ?, '' " + "FROM \(_TableBookmarks) WHERE type IS \(BookmarkNodeType.bookmark.rawValue)" // Create structure for our migrated bookmarks. // In order to get contiguous positions (idx), we first insert everything we just migrated under // Mobile Bookmarks into a temporary table, then use rowid as our idx. let temporaryTable = "CREATE TEMPORARY TABLE children AS " + "SELECT guid FROM \(_TableBookmarks) WHERE " + "type IS \(BookmarkNodeType.bookmark.rawValue) ORDER BY id ASC" let createStructure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "SELECT ? AS parent, guid AS child, (rowid - 1) AS idx FROM children" let migrate: [(String, Args?)] = [ (migrateLocal, migrateArgs), (temporaryTable, nil), (createStructure, migrateArgs), // Drop the temporary table. ("DROP TABLE children", nil), // Drop the old bookmarks table. ("DROP TABLE \(_TableBookmarks)", nil), // Create indices for each structure table. (indexBufferStructureParentIdx, nil), (indexLocalStructureParentIdx, nil), (indexMirrorStructureParentIdx, nil) ] if !self.run(db, queries: prep) || !self.prepopulateRootFolders(db) || !self.run(db, queries: migrate) { return false } // TODO: trigger a sync? } // Add views for the overlays. if from < 14 && to >= 14 { let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" if !self.run(db, queries: [ self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView, indexMirrorStructureChild]) { return false } } if from == 14 && to >= 15 { // We screwed up some of the views. Recreate them. if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.bufferBookmarksView, self.bufferBookmarksStructureView, self.localBookmarksView, self.localBookmarksStructureView]) { return false } } if from < 16 && to >= 16 { if !self.run(db, queries: [ allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView]) { return false } } if from < 17 && to >= 17 { if !self.run(db, queries: [ // Adds the local_modified, server_modified times to the local bookmarks view "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.localBookmarksView]) { return false } } if from < 18 && to >= 18 { if !self.run(db, queries: [ // Adds the Activity Stream blocklist table activityStreamBlocklistCreate]) { return false } } if from < 19 && to >= 19 { if !self.run(db, queries: [ // Adds tables/indicies for metadata content pageMetadataCreate, indexPageMetadataCreate]) { return false } } if from < 20 && to >= 20 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", self.bufferBookmarksView]) { return false } } if from < 21 && to >= 21 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewHistoryVisits)", self.historyVisitsView]) { return false } } return true } fileprivate func fillDomainNamesFromCursor(_ cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool { if cursor.count == 0 { return true } // URL -> hostname, flattened to make args. var pairs = Args() pairs.reserveCapacity(cursor.count * 2) for url in cursor { if let url = url, let host = url.asURL?.normalizedHost { pairs.append(url) pairs.append(host) } } cursor.close() let tmpTable = "tmp_hostnames" let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)" if !self.run(db, sql: table, args: nil) { log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.") return false } // Now insert these into the temporary table. Chunk by an even number, for obvious reasons. let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2)) for chunk in chunks { let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " + Array<String>(repeating: "(?, ?)", count: chunk.count / 2).joined(separator: ", ") if !self.run(db, sql: ins, args: Array(chunk)) { log.error("Couldn't insert domains into temporary table. Aborting migration.") return false } } // Now make those into domains. let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)" // … and fill that temporary column. let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)" // Update the history table from the temporary table. let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)" // Clean up. let dropTemp = "DROP TABLE \(tmpTable)" // Now run these. if !self.run(db, queries: [domains, domainIDs, updateHistory, dropTemp]) { log.error("Unable to migrate domains.") return false } return true } /** * The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use * of Table, that means making sure that any of our tables and views exist. * We do that by fetching all tables from sqlite_master with matching names, and verifying * that we get back more than one. * Note that we don't check for views -- trust to luck. */ func exists(_ db: SQLiteDBConnection) -> Bool { return db.tablesExist(AllTables) } func drop(_ db: SQLiteDBConnection) -> Bool { log.debug("Dropping all browser tables.") let additional = [ "DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention. ] let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" } let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" } let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" } let queries = Array([views, indices, tables, additional].joined()) return self.run(db, queries: queries) } }
mpl-2.0
jindulys/Leetcode_Solutions_Swift
Sources/Tree/105_ConstructBinaryTreeFromPreorderAndInorderTraversal.swift
1
2420
// // 105_ConstructBinaryTreeFromPreorderAndInorderTraversal.swift // HRSwift // // Created by yansong li on 2016-08-06. // Copyright © 2016 yansong li. All rights reserved. // import Foundation /** Title:105 Construct Binary Tree From Preorder and Ignorer Traversal URL: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ Space: O(n) Time: O(n) */ class TreeBuildPreorderInorder_Solution { func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? { guard preorder.count > 0 && inorder.count > 0 && preorder.count == inorder.count else { return nil } return treeBuildHelper(preorder, preStartIndex: 0, preEndIndex: preorder.count - 1, inorder: inorder, inorderStartIndex: 0, inorderEndIndex: inorder.count - 1) } func treeBuildHelper(_ preorder: [Int], preStartIndex: Int, preEndIndex: Int, inorder: [Int], inorderStartIndex: Int, inorderEndIndex: Int) -> TreeNode? { guard preStartIndex <= preEndIndex && inorderStartIndex <= inorderEndIndex else { return nil } let rootVal = preorder[preStartIndex] let currentRoot = TreeNode(rootVal) var mid: Int = 0 for i in inorderStartIndex...inorderEndIndex { if inorder[i] == rootVal { mid = i break } } currentRoot.left = treeBuildHelper(preorder, preStartIndex: preStartIndex + 1, preEndIndex: preStartIndex + mid - inorderStartIndex, inorder: inorder, inorderStartIndex: inorderStartIndex, inorderEndIndex: mid - 1) currentRoot.right = treeBuildHelper(preorder, preStartIndex: preStartIndex + mid - inorderStartIndex + 1, preEndIndex: preEndIndex, inorder: inorder, inorderStartIndex: mid + 1, inorderEndIndex: inorderEndIndex) return currentRoot } }
mit
TouchInstinct/LeadKit
TINetworking/Sources/RequestPreprocessors/EndpointSecurityRequestPreprocessor.swift
1
1814
// // Copyright (c) 2022 Touch Instinct // // 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 TIFoundationUtils public protocol SecuritySchemePreprocessor { func preprocess<B,S>(request: EndpointRequest<B,S>, using security: SecurityScheme, completion: @escaping (Result<EndpointRequest<B,S>, Error>) -> Void) -> Cancellable } @available(iOS 13.0.0, *) public extension SecuritySchemePreprocessor { func preprocess<B,S>(request: EndpointRequest<B,S>, using security: SecurityScheme) async -> Result<EndpointRequest<B,S>, Error> { await withTaskCancellableClosure { completion in preprocess(request: request, using: security) { completion($0) } } } }
apache-2.0
pavelpark/RoundMedia
roundMedia/roundMedia/Constants.swift
1
224
// // Constants.swift // roundMedia // // Created by Pavel Parkhomey on 7/14/17. // Copyright © 2017 Pavel Parkhomey. All rights reserved. // import UIKit let SHADOW_GRAY: CGFloat = 120.0 / 255.0 let KEY_UID = "uid"
mit
brokenhandsio/vapor-oauth
Sources/VaporOAuth/Helper/OAuthHelper.swift
1
111
protocol OAuthHelper { func assertScopes(_ scopes: [String]?) throws func user() throws -> OAuthUser }
mit
prebid/prebid-mobile-ios
PrebidMobile/PrebidMobileRendering/Prebid/Integrations/MediationAPI/MediationBaseInterstitialAdUnit.swift
1
7506
/*   Copyright 2018-2021 Prebid.org, 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 @objcMembers public class MediationBaseInterstitialAdUnit : NSObject { public var bannerParameters: BannerParameters { get { adUnitConfig.adConfiguration.bannerParameters } } public var videoParameters: VideoParameters { get { adUnitConfig.adConfiguration.videoParameters } } public var isMuted: Bool { get { adUnitConfig.adConfiguration.videoControlsConfig.isMuted } set { adUnitConfig.adConfiguration.videoControlsConfig.isMuted = newValue } } public var isSoundButtonVisible: Bool { get { adUnitConfig.adConfiguration.videoControlsConfig.isSoundButtonVisible } set { adUnitConfig.adConfiguration.videoControlsConfig.isSoundButtonVisible = newValue } } public var closeButtonArea: Double { get { adUnitConfig.adConfiguration.videoControlsConfig.closeButtonArea } set { adUnitConfig.adConfiguration.videoControlsConfig.closeButtonArea = newValue } } public var closeButtonPosition: Position { get { adUnitConfig.adConfiguration.videoControlsConfig.closeButtonPosition } set { adUnitConfig.adConfiguration.videoControlsConfig.closeButtonPosition = newValue } } let adUnitConfig: AdUnitConfig public var configId: String { adUnitConfig.configId } var bidRequester: PBMBidRequester? var completion: ((ResultCode) -> Void)? let mediationDelegate: PrebidMediationDelegate init(configId: String, mediationDelegate: PrebidMediationDelegate) { self.mediationDelegate = mediationDelegate adUnitConfig = AdUnitConfig(configId: configId) adUnitConfig.adConfiguration.isInterstitialAd = true adUnitConfig.adPosition = .fullScreen adUnitConfig.adConfiguration.adFormats = [.display, .video] adUnitConfig.adConfiguration.bannerParameters.api = PrebidConstants.supportedRenderingBannerAPISignals super.init() videoParameters.placement = .Interstitial } public func fetchDemand(completion: ((ResultCode)->Void)?) { fetchDemand(connection: ServerConnection.shared, sdkConfiguration: Prebid.shared, targeting: Targeting.shared, completion: completion) } // MARK: - Context Data public func addContextData(_ data: String, forKey key: String) { adUnitConfig.addContextData(key: key, value: data) } public func updateContextData(_ data: Set<String>, forKey key: String) { adUnitConfig.updateContextData(key: key, value: data) } public func removeContextDate(forKey key: String) { adUnitConfig.removeContextData(for: key) } public func clearContextData() { adUnitConfig.clearContextData() } // MARK: - App Content public func setAppContent(_ appContent: PBMORTBAppContent) { adUnitConfig.setAppContent(appContent) } public func clearAppContent() { adUnitConfig.clearAppContent() } public func addAppContentData(_ dataObjects: [PBMORTBContentData]) { adUnitConfig.addAppContentData(dataObjects) } public func removeAppContentDataObject(_ dataObject: PBMORTBContentData) { adUnitConfig.removeAppContentData(dataObject) } public func clearAppContentDataObjects() { adUnitConfig.clearAppContentData() } // MARK: - User Data public func addUserData(_ userDataObjects: [PBMORTBContentData]) { adUnitConfig.addUserData(userDataObjects) } public func removeUserData(_ userDataObject: PBMORTBContentData) { adUnitConfig.removeUserData(userDataObject) } public func clearUserData() { adUnitConfig.clearUserData() } // MARK: - Internal Methods // NOTE: do not use `private` to expose this method to unit tests func fetchDemand(connection: ServerConnectionProtocol, sdkConfiguration: Prebid, targeting: Targeting, completion: ((ResultCode)->Void)?) { guard bidRequester == nil else { // Request in progress return } self.completion = completion mediationDelegate.cleanUpAdObject() bidRequester = PBMBidRequester(connection: connection, sdkConfiguration: sdkConfiguration, targeting: targeting, adUnitConfiguration: adUnitConfig) bidRequester?.requestBids(completion: { [weak self] (bidResponse, error) in if let response = bidResponse { self?.handleBidResponse(response) } else { self?.handleBidRequestError(error) } }) } // MARK: - Private Methods private func handleBidResponse(_ bidResponse: BidResponse) { var demandResult = ResultCode.prebidDemandNoBids if let winningBid = bidResponse.winningBid, let targetingInfo = winningBid.targetingInfo { var adObjectSetupDictionary: [String: Any] = [ PBMMediationConfigIdKey: configId, PBMMediationTargetingInfoKey: targetingInfo, PBMMediationAdUnitBidKey: winningBid ] if bidResponse.winningBid?.adFormat == .video { // Append video specific configurations let videoSetupDictionary: [String: Any] = [ PBMMediationVideoAdConfiguration: self.adUnitConfig.adConfiguration.videoControlsConfig, PBMMediationVideoParameters: self.adUnitConfig.adConfiguration.videoParameters ] adObjectSetupDictionary.merge(videoSetupDictionary, uniquingKeysWith: { $1 }) } if mediationDelegate.setUpAdObject(with: adObjectSetupDictionary) { demandResult = .prebidDemandFetchSuccess } else { demandResult = .prebidWrongArguments } } else { Log.error("The winning bid is absent in response!") } completeWithResult(demandResult) } private func handleBidRequestError(_ error: Error?) { completeWithResult(PBMError.demandResult(from: error)) } private func completeWithResult(_ demandResult: ResultCode) { if let completion = self.completion { DispatchQueue.main.async { completion(demandResult) } } self.completion = nil markLoadingFinished() } private func markLoadingFinished() { completion = nil bidRequester = nil } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/18692-swift-dictionarytype-get.swift
11
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation class A func b{ class A{func a<U:A.a
mit
xoyip/AzureStorageApiClient
Pod/Classes/AzureStorage/Queue/Request/PeekMessageRequest.swift
1
457
// // PeekMessageRequest.swift // AzureStorageApiClient // // Created by Hiromasa Ohno on 2015/08/06. // Copyright (c) 2015 Hiromasa Ohno. All rights reserved. // import Foundation public extension AzureQueue { public class PeekMessagesRequest: GetMessagesRequestBase { override func parameters() -> [String] { var array = super.parameters() array.append("peekonly=true") return array } } }
mit
radex/swift-compiler-crashes
crashes-fuzzing/12697-swift-parser-parseexprlist.swift
11
242
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var:{struct Q<T where B:a{enum a<T where g:I}struct B{struct B{var d=a(s(
mit
radex/swift-compiler-crashes
crashes-duplicates/14349-swift-sourcemanager-getmessage.swift
11
204
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var b = ( var f = [ { class case ,
mit
TherapyChat/Reach
Reach.playground/Contents.swift
1
283
import Foundation import Reach import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: # Reach let reach = Reach(with: "github.com") //: Start notifiy events reach.start() //: Check network status after 1 second delay(1) { print(reach.status) }
apache-2.0
xeo-it/zipbooks-invoices-swift
zipbooks-ios/Models/Expense.swift
1
2490
// // User.swift // zipbooks-ios // // Created by Francesco Pretelli on 11/01/16. // Copyright © 2016 Francesco Pretelli. All rights reserved. // import RealmSwift import ObjectMapper import Foundation class Expense: Object,Mappable { dynamic var id: Int = 0 dynamic var name: String? dynamic var created_at: String? dynamic var billed: Int = 0 dynamic var plaid_transaction_id: String? dynamic var customer_id: Int = 0 dynamic var category: String? dynamic var date: String? dynamic var customer: Customer? dynamic var bank_account_id: Int = 0 dynamic var image_filename: String? dynamic var meta: String? dynamic var type: String? dynamic var deleted_at: String? dynamic var pending: String? dynamic var note: String? dynamic var updated_at: String? dynamic var line_item_id: Int = 0 dynamic var account_id: Int = 0 dynamic var archived_at: String? dynamic var amount: String? dynamic var currency_code: String? dynamic var category_id: String? override static func primaryKey() -> String? { return "id" } // MARK: Mappable required convenience init?(map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] name <- map["name"] created_at <- map["created_at"] billed <- map["billed"] plaid_transaction_id <- map["plaid_transaction_id"] customer_id <- map["customer_id"] category <- map["category"] date <- map["date"] customer <- map["customer"] bank_account_id <- map["bank_account_id"] image_filename <- map["image_filename"] meta <- map["meta"] type <- map["type"] deleted_at <- map["deleted_at"] pending <- map["pending"] note <- map["note"] updated_at <- map["updated_at"] line_item_id <- map["line_item_id"] account_id <- map["account_id"] archived_at <- map["archived_at"] amount <- map["amount"] currency_code <- map["currency_code"] category_id <- map["category_id"] } } class ExpensePost: Object,Mappable { dynamic var amount: Double = 0 dynamic var date: String? dynamic var customer_id: Int = 0 dynamic var name: String? dynamic var category: String? dynamic var note: String? // MARK: Mappable required convenience init?(map: Map) { self.init() } func mapping(map: Map) { amount <- map["amount"] date <- map["date"] customer_id <- map["customer_id"] name <- map["name"] category <- map["category"] note <- map["note"] } }
mit
AndreMuis/FiziksFunhouse
FiziksFunhouse/Application/AppDelegate.swift
1
260
// // AppDelegate.swift // FiziksFunhouse // // Created by Andre Muis on 5/2/16. // Copyright © 2016 Andre Muis. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
mit
behoernchen/IcnsComposer
Icns Composer/NSImageExtensions.swift
1
4433
// // NSImageExtensions.swift // Icns Composer // https://github.com/raphaelhanneken/icnscomposer // import Cocoa extension NSImage { /// The height of the image. var height: CGFloat { return size.height } /// The width of the image. var width: CGFloat { return size.width } /// A PNG representation of the image. var PNGRepresentation: Data? { if let tiff = self.tiffRepresentation, let tiffData = NSBitmapImageRep(data: tiff) { return tiffData.representation(using: .png, properties: [:]) } return nil } // MARK: Resizing /// Resize the image to the given size. /// /// - Parameter size: The size to resize the image to. /// - Returns: The resized image. func resize(toSize size: NSSize) -> NSImage? { // Create a new rect with given width and height let frame = NSRect(x: 0, y: 0, width: size.width, height: size.height) // Get the best representation for the given size. guard let rep = self.bestRepresentation(for: frame, context: nil, hints: nil) else { return nil } // Create an empty image with the given size. let img = NSImage(size: size, flipped: false, drawingHandler: { (_) -> Bool in if rep.draw(in: frame) { return true } return false }) return img } /// Copy the image and resize it to the supplied size, while maintaining it's /// original aspect ratio. /// /// - Parameter size: The target size of the image. /// - Returns: The resized image. func resizeMaintainingAspectRatio(withSize size: NSSize) -> NSImage? { let newSize: NSSize let widthRatio = size.width / width let heightRatio = size.height / height if widthRatio > heightRatio { newSize = NSSize(width: floor(width * widthRatio), height: floor(height * widthRatio)) } else { newSize = NSSize(width: floor(width * heightRatio), height: floor(height * heightRatio)) } return resize(toSize: newSize) } // MARK: Cropping /// Resize the image, to nearly fit the supplied cropping size /// and return a cropped copy the image. /// /// - Parameter size: The size of the new image. /// - Returns: The cropped image. func crop(toSize: NSSize) -> NSImage? { // Resize the current image, while preserving the aspect ratio. guard let resized = self.resizeMaintainingAspectRatio(withSize: size) else { return nil } // Get some points to center the cropping area. let x = floor((resized.width - size.width) / 2) let y = floor((resized.height - size.height) / 2) // Create the cropping frame. let frame = NSRect(x: x, y: y, width: width, height: height) // Get the best representation of the image for the given cropping frame. guard let rep = resized.bestRepresentation(for: frame, context: nil, hints: nil) else { return nil } // Create a new image with the new size let img = NSImage(size: size) defer { img.unlockFocus() } img.lockFocus() if rep.draw(in: NSRect(x: 0, y: 0, width: width, height: height), from: frame, operation: NSCompositingOperation.copy, fraction: 1.0, respectFlipped: false, hints: [:]) { // Return the cropped image. return img } // Return nil in case anything fails. return nil } // MARK: Saving /// Save the images PNG representation to the supplied file URL. /// /// - Parameter url: The file URL to save the png file to. /// - Throws: An NSImageExtension Error. func savePngTo(url: URL) throws { if let png = self.PNGRepresentation { try png.write(to: url, options: .atomicWrite) } else { throw NSImageExtensionError.creatingPngRepresentationFailed } } } /// Exceptions for the image extension class. /// /// - creatingPngRepresentationFailed: Is thrown when the creation of the png representation failed. enum NSImageExtensionError: Error { case creatingPngRepresentationFailed }
mit
Raizlabs/ios-template
{{ cookiecutter.project_name | replace(' ', '') }}/app/Services/API/APIEndpoint+Codable.swift
1
604
// // APIEndpoint+Codable.swift // Services // // Created by {{ cookiecutter.lead_dev }} on {% now 'utc', '%D' %}. // Copyright © {% now 'utc', '%Y' %} {{ cookiecutter.company_name }}. All rights reserved. // import Foundation extension JSONDecoder { static let `default`: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return decoder }() } extension JSONEncoder { static let `default`: JSONEncoder = { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 return encoder }() }
mit
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/AccountBuilder.swift
2
1212
import Foundation @testable import WordPress /// Builds an Account for use with testing /// @objc class AccountBuilder: NSObject { private let coreDataStack: CoreDataStack private var account: WPAccount @objc init(_ coreDataStack: CoreDataStack) { self.coreDataStack = coreDataStack account = NSEntityDescription.insertNewObject(forEntityName: WPAccount.entityName(), into: coreDataStack.mainContext) as! WPAccount account.uuid = UUID().uuidString super.init() } @objc func with(id: Int64) -> AccountBuilder { account.userID = NSNumber(value: id) return self } @objc func with(uuid: String) -> AccountBuilder { account.uuid = uuid return self } @objc func with(username: String) -> AccountBuilder { account.username = username return self } @objc func with(email: String) -> AccountBuilder { account.email = email return self } @objc func with(blogs: [Blog]) -> AccountBuilder { account.blogs = Set(blogs) return self } @objc @discardableResult func build() -> WPAccount { account } }
gpl-2.0
jtbandes/swift-compiler-crashes
crashes-duplicates/26848-swift-metatypetype-get.swift
4
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var f{if{enum A{protocol a}}class A{struct B<f:f.c
mit
phdlove42/Vapor
Package.swift
1
429
import PackageDescription let package = Package( name: "hello-vapor", dependencies: [ .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 3), .Package(url: "https://github.com/vapor/postgresql-provider", majorVersion: 1, minor: 1) ], exclude: [ "Config", "Database", "Localization", "Public", "Resources", "Tests", ] )
mit
jpedrosa/sua
examples/murmur/Package.swift
1
138
import PackageDescription let package = Package( name: "Murmur", dependencies: [ .Package(url: "../../", majorVersion: 0) ] )
apache-2.0
mrommel/TreasureDungeons
TreasureDungeons/Source/Utils/Array2D.swift
1
1898
// // Array2D.swift // TreasureDungeons // // Created by Michael Rommel on 22.06.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation public class Array2D <T: Equatable> { fileprivate var columns: Int = 0 fileprivate var rows: Int = 0 fileprivate var array: Array<T?> = Array<T?>() public init(columns: Int, rows: Int) { self.columns = columns self.rows = rows self.array = Array<T?>(repeating: nil, count: rows * columns) } public subscript(column: Int, row: Int) -> T? { get { return array[(row * columns) + column] } set(newValue) { array[(row * columns) + column] = newValue } } public func columnCount() -> Int { return columns } public func rowCount() -> Int { return rows } } extension Array2D { subscript(point: Point) -> T? { get { return array[(point.y * columns) + point.x] } set(newValue) { array[(point.y * columns) + point.x] = newValue } } } extension Array2D { public func fill(with value: T) { for x in 0..<columns { for y in 0..<rows { self[x, y] = value } } } } extension Array2D: Sequence { public func makeIterator() -> Array2DIterator<T> { return Array2DIterator<T>(self) } } public struct Array2DIterator<T: Equatable>: IteratorProtocol { let array: Array2D<T> var index = 0 init(_ array: Array2D<T>) { self.array = array } mutating public func next() -> T? { let nextNumber = self.array.array.count - index guard nextNumber > 0 else { return nil } index += 1 return self.array.array[nextNumber] } }
apache-2.0
whiteshadow-gr/HatForIOS
HAT/Objects/HATNotificationNotice.swift
1
2081
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATNotificationNotice { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `noticeID` in JSON is `id` * `dateCreated` in JSON is `dateCreated` * `message` in JSON is `message` */ private enum CodingKeys: String, CodingKey { case noticeID = "id" case dateCreated = "dateCreated" case message = "message" } // MARK: - Variables /// The notification ID public var noticeID: Int = -1 /// The message of the notification public var message: String = "" /// The date the notification was created public var dateCreated: Date = Date() // MARK: - Initialisers /** The default initialiser. Initialises everything to default values. */ public init() { noticeID = -1 message = "" dateCreated = Date() } /** It initialises everything from the received JSON file from the HAT - dictionary: The JSON file received from the HAT */ public init(dictionary: Dictionary<String, JSON>) { if let tempNoticeID: Int = dictionary[CodingKeys.noticeID.rawValue]?.int { noticeID = tempNoticeID } if let tempMessage: String = dictionary[CodingKeys.message.rawValue]?.string { message = tempMessage } if let tempDateCreated: Int = dictionary[CodingKeys.dateCreated.rawValue]?.intValue { dateCreated = Date(timeIntervalSince1970: TimeInterval(tempDateCreated / 1000)) } } }
mpl-2.0
bsmith11/ScoreReporter
ScoreReporterCore/ScoreReporterCore/Models/Cluster.swift
1
1621
// // Cluster.swift // ScoreReporter // // Created by Bradley Smith on 7/18/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import CoreData public class Cluster: NSManagedObject { } // MARK: - Public public extension Cluster { func add(team: Team) { guard let games = games.allObjects as? [Game] else { return } games.forEach { $0.add(team: team) } } } // MARK: - Fetchable extension Cluster: Fetchable { public static var primaryKey: String { return #keyPath(Cluster.clusterID) } } // MARK: - CoreDataImportable extension Cluster: CoreDataImportable { public static func object(from dictionary: [String: Any], context: NSManagedObjectContext) -> Cluster? { guard let clusterID = dictionary[APIConstants.Response.Keys.clusterID] as? NSNumber else { return nil } guard let cluster = object(primaryKey: clusterID, context: context, createNew: true) else { return nil } cluster.clusterID = clusterID cluster.name = dictionary <~ APIConstants.Response.Keys.name let games = dictionary[APIConstants.Response.Keys.games] as? [[String: AnyObject]] ?? [] let gamesArray = Game.objects(from: games, context: context) for (index, game) in gamesArray.enumerated() { game.sortOrder = index as NSNumber } cluster.games = NSSet(array: gamesArray) if !cluster.hasPersistentChangedValues { context.refresh(cluster, mergeChanges: false) } return cluster } }
mit
Zewo/HashedPassword
Sources/HashedPassword.swift
1
4881
// HashedPassword.swift // // The MIT License (MIT) // // Copyright (c) 2016 Zewo // // 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, INCLUDINbG 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 CryptoSwift public enum HashedPasswordError: Error { case invalidString } public enum HashMethod: Equatable { case hash(variant: HMAC.Variant) case hmac(variant: HMAC.Variant) case pbkdf2(variant: HMAC.Variant, iterations: Int) internal init?(string: String) { let comps = string.components(separatedBy: "_") guard let methodStr = comps.first else { return nil } switch methodStr { case "hash": guard comps.count == 2, let hashType = HMAC.Variant(string: comps[1]) else { return nil } self = .hash(variant: hashType) case "hmac": guard comps.count == 2, let hashType = HMAC.Variant(string: comps[1]) else { return nil } self = .hmac(variant: hashType) case "pbkdf2": guard comps.count == 3, let hashType = HMAC.Variant(string: comps[1]), let iterations = Int(comps[2]) else { return nil } self = .pbkdf2(variant: hashType, iterations: iterations) default: return nil } } internal var string: String { switch self { case .hash(let variant): return "hash_" + variant.string case .hmac(let variant): return "hmac_" + variant.string case .pbkdf2(let variant, let iterations): return "pbkdf2_" + variant.string + "_" + String(iterations) } } internal func calculate(password: String, salt: String) throws -> String { guard let saltData = salt.data(using: .utf8)?.bytes, let passwordData = password.data(using: .utf8)?.bytes else { throw HashedPasswordError.invalidString } let data: [UInt8] switch self { case .hash(let variant): data = variant.calculateHash(saltData+passwordData) case .hmac(let variant): data = try HMAC(key: saltData, variant: variant).authenticate(passwordData) case .pbkdf2(let variant, let iterations): data = try PKCS5.PBKDF2(password: passwordData, salt: saltData, iterations: iterations, variant: variant).calculate() } return data.reduce("", { $0 + String(format: "%02x", $1) }) } public static func ==(lhs: HashMethod, rhs: HashMethod) -> Bool { return true } } public struct HashedPassword: Equatable, CustomStringConvertible { public let hash: String public let method: HashMethod public let salt: String public init(hash: String, method: HashMethod, salt: String) { self.hash = hash self.method = method self.salt = salt } public init(string: String) throws { let passwordComps = string.components(separatedBy: "$") guard passwordComps.count == 3, let method = HashMethod(string: passwordComps[1]) else { throw HashedPasswordError.invalidString } self.init(hash: passwordComps[0], method: method, salt: passwordComps[2]) } public init(password: String, method: HashMethod = .pbkdf2(variant: .sha256, iterations: 4096), saltLen: Int = 30) throws { let pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] var salt = "" for _ in 0 ..< saltLen { let i = Random.number(max: pool.count - 1) salt += pool[i] } self.method = method self.salt = salt self.hash = try method.calculate(password: password, salt: salt) } public var description: String { return "\(hash)$\(method.string)$\(salt)" } public static func ==(lhs: HashedPassword, rhs: HashedPassword) -> Bool { return lhs.hash == rhs.hash && lhs.method == rhs.method && lhs.salt == rhs.salt } } public func ==(lhs: HashedPassword, rhs: String) -> Bool { return (try? lhs.method.calculate(password: rhs, salt: lhs.salt)) == lhs.hash.lowercased() } public func ==(lhs: String, rhs: HashedPassword) -> Bool { return rhs == lhs }
mit
barbaramartina/styling-in-swift
Option - Configuration files/Styling/AppDelegate.swift
1
2178
// // AppDelegate.swift // Styling // // Created by Barbara Rodeker on 05/08/16. // Copyright © 2016 Barbara Rodeker. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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:. } }
gpl-3.0
openHPI/xikolo-ios
iOS/Data/Model/Actions/Course+Actions.swift
1
4557
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import UIKit extension Course { func shareAction(handler: @escaping () -> Void) -> Action { let title = NSLocalizedString("course.action-menu.share", comment: "Title for course item share action") return Action(title: title, image: Action.Image.share, handler: handler) } func showCourseDatesAction(handler: @escaping () -> Void) -> Action? { guard self.hasEnrollment && Brand.default.features.showCourseDates else { return nil } let title = NSLocalizedString("course.action-menu.show-course-dates", comment: "Title for show course dates action") return Action(title: title, image: Action.Image.calendar, handler: handler) } func openHelpdeskAction(handler: @escaping () -> Void) -> Action { let title = NSLocalizedString("settings.cell-title.app-helpdesk", comment: "cell title for helpdesk") return Action(title: title, image: Action.Image.helpdesk, handler: handler) } func automatedDownloadAction(handler: @escaping () -> Void) -> Action? { guard self.offersNotificationsForNewContent else { return nil } let title = NSLocalizedString("automated-downloads.setup.action.title", comment: "Automated Downloads: Action title for managing notifications for new content") return Action(title: title, image: Action.Image.notification, handler: handler) } @available(iOS 13.0, *) var unenrollAction: UIAction? { guard let enrollment = self.enrollment else { return nil } let unenrollActionTitle = NSLocalizedString("enrollment.options-alert.unenroll-action.title", comment: "title for unenroll action") return UIAction(title: unenrollActionTitle, image: Action.Image.unenroll, attributes: .destructive) { _ in EnrollmentHelper.delete(enrollment) } } @available(iOS 13.0, *) var markAsCompletedMenu: UIMenu? { // For this, we require the subtitle of the confirm action. The subtitle is only available on iOS 15 and later. guard #available(iOS 15, *) else { return nil } guard let enrollment = self.enrollment, !enrollment.completed else { return nil } let cancelActionTitle = NSLocalizedString("global.alert.cancel", comment: "title to cancel alert") let cancelAction = UIAction(title: cancelActionTitle, image: Action.Image.cancel) { _ in } let confirmActionTitle = NSLocalizedString("global.alert.ok", comment: "title to confirm alert") let confirmActionSubtitle = NSLocalizedString("enrollment.mark-as-completed.message.no-undo", comment: "message for the mark as completed action that this action can not be undone") let markAsCompletedAction = UIAction(title: confirmActionTitle, subtitle: confirmActionSubtitle, image: Action.Image.ok) { _ in EnrollmentHelper.markAsCompleted(self) } let completedActionTitle = NSLocalizedString("enrollment.options-alert.mask-as-completed-action.title", comment: "title for 'mask as completed' action") return UIMenu(title: completedActionTitle, image: Action.Image.markAsCompleted, children: [markAsCompletedAction, cancelAction]) } @available(iOS 13.0, *) var manageEnrollmentMenu: UIMenu? { let enrollmentActions: [UIMenuElement] = [ self.markAsCompletedMenu, self.unenrollAction, ].compactMap { $0 } if enrollmentActions.isEmpty { return nil } else { return UIMenu(title: "", options: .displayInline, children: enrollmentActions) } } var isEligibleForContentNotifications: Bool { guard #available(iOS 13, *) else { return false } guard self.hasEnrollment else { return false } guard self.endsAt?.inFuture ?? false else { return false } return true } var offersNotificationsForNewContent: Bool { guard self.isEligibleForContentNotifications else { return false } return FeatureHelper.hasFeature(.newContentNotification, for: self) } var offersAutomatedBackgroundDownloads: Bool { guard self.offersNotificationsForNewContent else { return false } return FeatureHelper.hasFeature(.newContentBackgroundDownload, for: self) } }
gpl-3.0
vpeschenkov/LetterAvatarKit
LetterAvatarKitExample/LetterAvatarKitExample/LetterAvatarController.swift
1
1671
// // ViewController.swift // LetterAvatarKitExample // // Copyright 2017 Victor Peschenkov // // Permission is hereby granted, free of charge, to any person obtaining a copy // o this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import LetterAvatarKit class LetterAvatarController: UIViewController { @IBOutlet var avatarImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let width = UIScreen.main.bounds.size.width let height = width let avatarImage = LetterAvatarMaker() .setUsername("Letter Avatar") .setSize(CGSize(width: width, height: height)) .build() avatarImageView.image = avatarImage } }
mit
GenerallyHelpfulSoftware/Scalar2D
Font/Sources/CoreText+FontDescription.swift
1
18499
// // CoreText+FontDescription.swift // Scalar2D // // Created by Glenn Howes on 9/8/17. // Copyright © 2017-2019 Generally Helpful Software. All rights reserved. // // // // // The MIT License (MIT) // Copyright (c) 2016-2019 Generally Helpful Software // 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 CoreText import Scalar2D_Utils #if os(iOS) || os(tvOS) || os(watchOS) import UIKit // for NSAttributedString.Key.underlineStyle #elseif os(OSX) import AppKit // for NSAttributedString.Key.underlineStyle #endif fileprivate let gSystemFontProperties : [AnyHashable : Any] = {return createSystemFontProperties()}() fileprivate let gFontMappings = {return ["Arial" : "ArialMT", "Times New Roman" : "TimesNewRomanPSMT", "Times" : "TimesNewRomanPSMT", "Courier New" : "CourierNewPSMT", "Palatino": "Palatino-Roman"]}() fileprivate let fontAttributesCache : NSCache<AnyObject, AnyObject> = { let result = NSCache<AnyObject, AnyObject>() result.name = "com.genhelp.scalard2d.fontcache" return result }() public protocol FontContext { var initial : Dictionary<AnyHashable, Any> {get} var inherited : Dictionary<AnyHashable, Any> {get} var defaultFontSize : CGFloat {get} var baseFontSize : CGFloat {get} } public protocol CoreTextProperty : InheritableProperty { func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) } extension FontWeight : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { var existingTraits : [AnyHashable : Any] = (properties[kCTFontTraitsAttribute] as? [AnyHashable:Any]) ?? [AnyHashable:Any]() var explicitWeight = (existingTraits[kCTFontWeightTrait] as? NSNumber)?.intValue let fontTraitMaskRaw : UInt32 = UInt32((properties[kCTFontSymbolicTrait] as? Int) ?? 0) var symbolicTraits = CTFontSymbolicTraits(rawValue: fontTraitMaskRaw) switch self { case .bold: symbolicTraits.formUnion(.boldTrait) explicitWeight = nil case .lighter, .bolder, .custom(_): let startWeight = (explicitWeight ?? (symbolicTraits.contains(.boldTrait) ? 700 : 400)) explicitWeight = self.equivalentWeight(forStartWeight: startWeight) if explicitWeight == FontWeight.boldWeight { explicitWeight = nil symbolicTraits.formUnion(.boldTrait) } else if explicitWeight == FontWeight.normalWeight { explicitWeight = nil symbolicTraits.remove(.boldTrait) } case .normal: explicitWeight = nil symbolicTraits.remove(.boldTrait) case .inherit: return case .initial: explicitWeight = nil } if let weightToSet = explicitWeight { existingTraits[kCTFontWeightTrait] = weightToSet properties[kCTFontTraitsAttribute] = existingTraits symbolicTraits.remove(.boldTrait) } else { existingTraits.removeValue(forKey: kCTFontWeightTrait) if existingTraits.isEmpty { properties.removeValue(forKey: kCTFontTraitsAttribute) } else { properties[kCTFontTraitsAttribute] = existingTraits } } if symbolicTraits.rawValue == 0 { properties.removeValue(forKey: kCTFontSymbolicTrait) } else { properties[kCTFontSymbolicTrait] = NSNumber(value: symbolicTraits.rawValue) } } } public extension FontFamily { var stylisticTraits : CTFontStylisticClass { switch self { case .cursive: return .scriptsClass case .fantasy: return .ornamentalsClass case .serif: return .modernSerifsClass case .sansSerif: return .sansSerifClass default: return CTFontStylisticClass(rawValue: 0) } } var symbolicTraits : CTFontSymbolicTraits { switch self { case .monospace: return .traitMonoSpace default: return CTFontSymbolicTraits(rawValue: 0) } } } extension TextDecoration : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { switch self { case .noDecoration, .initial: properties.removeValue(forKey: NSAttributedString.Key.underlineStyle) case .inherit: return case .underline: properties[NSAttributedString.Key.underlineStyle] = NSNumber(value: 1) case .lineThrough: properties[NSAttributedString.Key.strikethroughStyle] = NSNumber(value: 1) case .overline: // don't know how to render this break } } } extension FontVariant { public func add(toDescriptor descriptor: CTFontDescriptor, withContext context: FontContext ) -> CTFontDescriptor { var result = descriptor switch self { case .smallCaps: result = CTFontDescriptorCreateCopyWithFeature(result, 3 as CFNumber, 3 as CFNumber) default: break } return result } } extension FontStretch : CoreTextProperty { public func merge(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { switch self { case .normal, .initial: properties.removeValue(forKey: kCTFontWidthTrait) case .inherit: return default: guard let width = self.normalizedWidth else { properties.removeValue(forKey: kCTFontWidthTrait) return } properties[kCTFontWidthTrait] = NSNumber(value: width) } } var normalizedWidth : Double? { switch self { case .condensed: return -0.5 case .expanded: return 0.5 case .extraCondensed: return -0.75 case .extraExpanded: return 0.75 case .semiCondensed: return -0.25 case .semiExpanded: return 0.25 case .ultraExpanded: return 1.0 case .ultraCondensed: return -1.0 default: return nil } } } public extension FontContext { var initial : Dictionary<AnyHashable, Any> { return Dictionary<AnyHashable, Any>() } var inherited : Dictionary<AnyHashable, Any> { return self.initial } var defaultFont : CTFont { guard let result = CTFontCreateUIFontForLanguage(.user, 0.0, nil) else { return CTFontCreateWithName("Helvetica" as CFString, 14.0, nil) } return result } var defaultFontSize : CGFloat { let defaultFontRef = self.defaultFont return CTFontGetSize(defaultFontRef) } var defaultAttributes : [AnyHashable : Any] { let fontDescriptor = CTFontCopyFontDescriptor(self.defaultFont) return CTFontDescriptorCopyAttributes(fontDescriptor) as! [AnyHashable : Any] } var baseFontSize : CGFloat { return defaultFontSize } func fontSize(fromFontSize fontSize: FontSize) -> CGFloat { let standardScaling: CGFloat = 1.2 switch fontSize { case .inherit, .initial, .medium: return baseFontSize case .small: return defaultFontSize / standardScaling case .large: return defaultFontSize * standardScaling case .xSmall: return defaultFontSize / (standardScaling*standardScaling) case .xLarge: return defaultFontSize * standardScaling * standardScaling case .xxSmall: return defaultFontSize / (standardScaling*standardScaling*standardScaling) case .xxLarge: return defaultFontSize * standardScaling * standardScaling * standardScaling case .larger: return baseFontSize * standardScaling case .smaller: return baseFontSize / standardScaling case .pixel(let value): return CGFloat(value) // have to re-examine this later with a mechanism to get the pixel height case .point(let value): return CGFloat(value) case .percentage(let percent): return baseFontSize * CGFloat(percent / 100.0) case .em(let scaling): return baseFontSize * CGFloat(scaling) case .rem(let scaling): return defaultFontSize * CGFloat(scaling) case .dynamic: return baseFontSize // TODO support dynamic sizing case .ch(_): return baseFontSize // TODO support ch sizing case .ex(_): return baseFontSize // TODO support ex sizing case .viewPortH(_), .viewPortW(_): return baseFontSize // TODO support viewport based sizing } } private static func map(fontName: String) -> String { guard let mappedName = gFontMappings[fontName] else { return fontName } return mappedName } private static func createFontAttributes(forName name: String) -> [AnyHashable : Any]? { let testFont = CTFontCreateWithName(name as CFString, 0.0, nil) let descriptor = CTFontCopyFontDescriptor(testFont) var fontAttributes = CTFontDescriptorCopyAttributes(descriptor) as! [AnyHashable : Any] if !fontAttributes.isEmpty { fontAttributes.removeValue(forKey: kCTFontSizeAttribute) return fontAttributes } return nil } private static func fontAttributes(forName name: String) -> [AnyHashable : Any]? { let realName = self.map(fontName: name) if realName.isEmpty { return nil } if let savedProperties = fontAttributesCache.object(forKey: realName as NSString) { if savedProperties is NSNull { return nil } else if let result = savedProperties as? [AnyHashable : Any] { return result } } else { if let createdProperties = createFontAttributes(forName: realName) { fontAttributesCache.setObject(createdProperties as AnyObject, forKey: realName as NSString, cost: 100) return createdProperties } else { fontAttributesCache.setObject(NSNull(), forKey: realName as NSString, cost: 100) } } return nil } func fontFamilyProperties(from fontDescriptor: FontDescription) -> [AnyHashable : Any] { let fontFamilies = fontDescriptor.families if fontFamilies.isEmpty { return self.defaultAttributes } else { var result = self.defaultAttributes var looped = false var fallbacks : [[AnyHashable : Any]]? fontFamilies.forEach { aFamily in var symbolicTraits: CTFontSymbolicTraits? = nil var stylisticTraits: CTFontStylisticClass? = nil if looped { fallbacks = [[AnyHashable : Any]]() } looped = true switch aFamily { case .system: if fallbacks != nil { fallbacks!.append(gSystemFontProperties) } else { result = gSystemFontProperties } return case .cursive: stylisticTraits = .scriptsClass case .fantasy: stylisticTraits = .ornamentalsClass case .monospace: symbolicTraits = .monoSpaceTrait case .sansSerif: stylisticTraits = .sansSerifClass case .serif: stylisticTraits = .classModernSerifs case .named(let name): if let attributes = Self.fontAttributes(forName: name) { if fallbacks != nil { fallbacks!.append(attributes) } else { result = attributes } return } case .initial: break case .inherit: break } let rawTraits = (symbolicTraits?.rawValue ?? 0) + (stylisticTraits?.rawValue ?? 0) if rawTraits != 0 { let symbolRecord = [kCTFontSymbolicTrait : rawTraits] if fallbacks != nil { fallbacks!.append([kCTFontTraitsAttribute : symbolRecord]) } else { result[kCTFontTraitsAttribute] = symbolRecord } } } if (fallbacks?.count ?? 0) > 0 { result[kCTFontCascadeListAttribute] = fallbacks } return result } } var baseFontAttributes : [AnyHashable : Any] { return [AnyHashable : Any]() } } public class DefaultFontContext : FontContext { public static var shared : DefaultFontContext = { return DefaultFontContext() }() } public extension FontDescription { var symbolicTraits : CTFontSymbolicTraits { var result = CTFontSymbolicTraits(rawValue: 0) switch self.weight { case .bold: result = .boldTrait default: break } switch self.stretch { case .condensed: result.insert(.condensedTrait) case .expanded: result.insert(.expandedTrait) default: break } return result } var ctDescriptor : CTFontDescriptor { return self.coreTextDescriptor() } private func mergeParagraphStyles(properties: inout Dictionary<AnyHashable, Any>, withContext context: FontContext) { // let existingParagraphStyles = properties[kCTParagraphStyleAttributeName] as? [CTParagraphStyleSetting] ?? [CTParagraphStyleSetting]() } func coreTextDescriptor(context: FontContext = DefaultFontContext.shared) -> CTFontDescriptor { var record = context.baseFontAttributes let familyProperties = context.fontFamilyProperties(from: self) record = record.merging(familyProperties, uniquingKeysWith:{(_, new) in new}) self.weight.merge(properties: &record, withContext: context) self.stretch.merge(properties: &record, withContext: context) self.decorations.forEach{$0.merge(properties:&record, withContext: context)} record[kCTFontSizeAttribute as String] = context.fontSize(fromFontSize: self.size) let keySet = Set(record.keys) var coreTextDescriptor = CTFontDescriptorCreateWithAttributes(record as CFDictionary) if let missSizedResult = CTFontDescriptorCreateMatchingFontDescriptor(coreTextDescriptor, keySet as CFSet) { coreTextDescriptor = CTFontDescriptorCreateCopyWithAttributes(missSizedResult, record as CFDictionary) } let coreTextDescriptorWithVariant = self.variant.add(toDescriptor: coreTextDescriptor, withContext: context) return coreTextDescriptorWithVariant } } fileprivate func createSystemFontProperties() -> [AnyHashable : Any] { let defaultFontRef = CTFontCreateUIFontForLanguage(CTFontUIFontType.system, 0.0, nil)! let postscriptNameCF = CTFontCopyPostScriptName(defaultFontRef) let fontTraits = CTFontCopyTraits(defaultFontRef) var mutableResult = fontTraits as! [String : Any] mutableResult[kCTFontNameAttribute as String] = postscriptNameCF return mutableResult }
mit
kevinvanderlugt/Exercism-Solutions
swift/exercism-test-runner/exercism-test-runnerTests/SpaceAgeTest.swift
1
1452
import XCTest class SpaceAgeTest: XCTestCase { func test_age_in_seconds(){ let age = SpaceAge(1_000_000) XCTAssertTrue(1_000_000 == age.seconds) } func test_age_in_earth_years(){ let age = SpaceAge(1_000_000_000) XCTAssertTrue(31.69 == age.on_earth) } func test_age_in_mercury_years(){ let age = SpaceAge(2_134_835_688) XCTAssertTrue(67.65 == age.on_earth) XCTAssertTrue(280.88 == age.on_mercury) } func test_age_in_venus_years(){ let age = SpaceAge(189_839_836) XCTAssertTrue(6.02 == age.on_earth) XCTAssertTrue(9.78 == age.on_venus) } func test_age_on_mars(){ let age = SpaceAge(2_329_871_239) XCTAssertTrue(73.83 == age.on_earth) XCTAssertTrue(39.25 == age.on_mars) } func test_age_on_jupiter(){ let age = SpaceAge(901_876_382) XCTAssertTrue(28.58 == age.on_earth) XCTAssertTrue(2.41 == age.on_jupiter) } func test_age_on_saturn(){ let age = SpaceAge(3_000_000_000) XCTAssertTrue(95.06 == age.on_earth) XCTAssertTrue(3.23 == age.on_saturn) } func test_age_on_uranus(){ let age = SpaceAge(3_210_123_456) XCTAssertTrue(101.72 == age.on_earth) XCTAssertTrue(1.21 == age.on_uranus) } func test_age_on_neptune(){ let age = SpaceAge(8_210_123_456) XCTAssertTrue(260.16 == age.on_earth) XCTAssertTrue(1.58 == age.on_neptune) } }
mit
PANDA-Guide/PandaGuideApp
Pods/ActionCableClient/Source/Classes/JSONSerializer.swift
2
7048
// // Copyright (c) 2016 Daniel Rhodes <rhodes.daniel@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // import Foundation internal class JSONSerializer { static let nonStandardMessageTypes: [MessageType] = [.ping, .welcome] static func serialize(_ channel : Channel, command: Command, data: ActionPayload?) throws -> String { do { var identifierDict : ChannelIdentifier if let identifier = channel.identifier { identifierDict = identifier } else { identifierDict = Dictionary() } identifierDict["channel"] = "\(channel.name)" let JSONData = try JSONSerialization.data(withJSONObject: identifierDict, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let identifierString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } var commandDict = [ "command" : command.string, "identifier" : identifierString ] as [String : Any] if let _ = data { let JSONData = try JSONSerialization.data(withJSONObject: data!, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let dataString = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } commandDict["data"] = dataString } let CmdJSONData = try JSONSerialization.data(withJSONObject: commandDict, options: JSONSerialization.WritingOptions(rawValue: 0)) guard let JSONString = NSString(data: CmdJSONData, encoding: String.Encoding.utf8.rawValue) else { throw SerializationError.json } return JSONString as String } catch { throw SerializationError.json } } static func deserialize(_ string: String) throws -> Message { do { guard let JSONData = string.data(using: String.Encoding.utf8) else { throw SerializationError.json } guard let JSONObj = try JSONSerialization.jsonObject(with: JSONData, options: .allowFragments) as? Dictionary<String, AnyObject> else { throw SerializationError.json } var messageType: MessageType = .unrecognized if let typeObj = JSONObj["type"], let typeString = typeObj as? String { messageType = MessageType(string: typeString) } var channelName: String? if let idObj = JSONObj["identifier"] { var idJSON: Dictionary<String, AnyObject> if let idString = idObj as? String { guard let JSONIdentifierData = idString.data(using: String.Encoding.utf8) else { throw SerializationError.json } if let JSON = try JSONSerialization.jsonObject(with: JSONIdentifierData, options: .allowFragments) as? Dictionary<String, AnyObject> { idJSON = JSON } else { throw SerializationError.json } } else if let idJSONObj = idObj as? Dictionary<String, AnyObject> { idJSON = idJSONObj } else { throw SerializationError.protocolViolation } if let nameStr = idJSON["channel"], let name = nameStr as? String { channelName = name } } switch messageType { // Subscriptions case .confirmSubscription, .rejectSubscription, .cancelSubscription, .hibernateSubscription: guard let _ = channelName else { throw SerializationError.protocolViolation } return Message(channelName: channelName, actionName: nil, messageType: messageType, data: nil, error: nil) // Welcome/Ping messages case .welcome, .ping: return Message(channelName: nil, actionName: nil, messageType: messageType, data: nil, error: nil) case .message, .unrecognized: var messageActionName : String? var messageValue : AnyObject? var messageError : Swift.Error? do { // No channel name was extracted from identifier guard let _ = channelName else { throw SerializationError.protocolViolation } // No message was extracted from identifier guard let messageObj = JSONObj["message"] else { throw SerializationError.protocolViolation } if let actionObj = messageObj["action"], let actionStr = actionObj as? String { messageActionName = actionStr } messageValue = messageObj } catch { messageError = error } return Message(channelName: channelName!, actionName: messageActionName, messageType: MessageType.message, data: messageValue, error: messageError) } } catch { throw error } } }
gpl-3.0
bradleypj823/Swift-Workshop
IntermediateSwiftTutorial/IntermediateSwiftTutorial/ViewController.swift
2
1269
// // ViewController.swift // IntermediateSwiftTutorial // // Created by Bradley Johnson on 6/27/14. // Copyright (c) 2014 Bradley Johnson. All rights reserved. // import UIKit class ViewController: UIViewController { //2 creating a variable to hold the function var miscFunc : (name : String) -> () = doSomething override func viewDidLoad() { super.viewDidLoad() //4 calling it with our function as ap roperty self.doSomethingWithName("Brad", funcAsParam: self.miscFunc) //5calling the same function with a closure expression self.doSomethingWithName("Brad", funcAsParam: { //can get rid of String here and return expression (name: String)->() in //code }) //6 calling it with a trailing closure self.doSomethingWithName("Brad"){ (name: String) -> () in //code } } //3 heres a method that takes a function as a parameter func doSomethingWithName(name : String, funcAsParam : (name : String) -> ()) -> (){ funcAsParam(name: name) } } // 1 functions are first class, define this function and then store it in a variable func doSomething(name : String) -> () {}
mit
RevenueCat/purchases-ios
Sources/Misc/FatalErrorUtil.swift
1
1030
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // FatalErrorUtil.swift // // Created by Andrés Boedo on 9/16/21. import Foundation #if DEBUG enum FatalErrorUtil { fileprivate static var fatalErrorClosure: (String, StaticString, UInt) -> Never = defaultFatalErrorClosure private static let defaultFatalErrorClosure = { Swift.fatalError($0, file: $1, line: $2) } static func replaceFatalError(closure: @escaping (String, StaticString, UInt) -> Never) { fatalErrorClosure = closure } static func restoreFatalError() { fatalErrorClosure = defaultFatalErrorClosure } } func fatalError(_ message: @autoclosure () -> String = "", file: StaticString = #fileID, line: UInt = #line) -> Never { FatalErrorUtil.fatalErrorClosure(message(), file, line) } #endif
mit
madeatsampa/MacMagazine-iOS
MacMagazine/Theme/Extensions/With.swift
2
688
// // With.swift // MacMagazine // // Created by Cassio Rossi on 28/02/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import Foundation public protocol With {} public extension With where Self: Any { /// Makes it available to set properties with closures just after initializing. /// /// let label = UILabel().with { /// $0.textAlignment = .center /// $0.textColor = UIColor.black /// $0.text = "Hello, World!" /// } @discardableResult func with(_ block: (Self) -> Void) -> Self { // https://github.com/devxoul/Then block(self) return self } } extension NSObject: With {}
mit
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/Utils.swift
1
7569
// // Utils.swift // uoat // // Created by Pyro User on 17/5/16. // Copyright © 2016 Zed. All rights reserved. // import Foundation class Utils { static func md5( string string: String ) -> String { var digest = [UInt8](count: Int( CC_MD5_DIGEST_LENGTH ), repeatedValue: 0) if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { CC_MD5( data.bytes, CC_LONG( data.length ), &digest ) } var digestHex = "" for index in 0..<Int( CC_MD5_DIGEST_LENGTH ) { digestHex += String( format: "%02x", digest[index] ) } return digestHex } static func alertMessage(viewController:UIViewController, title:String, message:String, onAlertClose:((action:UIAlertAction)->Void)?) { if let _ = viewController.presentedViewController { return } let alert = UIAlertController( title:title, message:message, preferredStyle:.Alert ) //options. let actionOk = UIAlertAction( title:"Ok", style:.Default, handler:onAlertClose) alert.addAction( actionOk ) //viewController.presentViewController( alert, animated: true, completion:nil ) if let _ = viewController.parentViewController { viewController.parentViewController!.presentViewController( alert, animated: true, completion:nil ) } else { viewController.presentViewController( alert, animated: true, completion:nil ) } } static func blurEffectView(view:UIView, radius:Int) -> UIVisualEffectView { let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")! let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type let blurEffect = customBlurObject.init() as! UIBlurEffect blurEffect.setValue(radius, forKeyPath: "blurRadius") let blurEffectView = UIVisualEffectView( effect: blurEffect ) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] return blurEffectView } static func flipImage( named name:String, orientation:UIImageOrientation ) -> UIImage { let image:UIImage = UIImage( named: name )! //Filp arrow image. let imageFlip:UIImage = UIImage( CGImage: image.CGImage!, scale: image.scale, orientation: orientation ) return imageFlip } static func randomString(length:Int) -> String { let baseString:NSString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString:NSMutableString = NSMutableString( capacity:length ) for _:Int in 0...length { let len = UInt32( baseString.length ) let rand = arc4random_uniform( len ) randomString.appendFormat( "%C", baseString.characterAtIndex( Int( rand ) ) ) } return String(randomString) } /* RELOCATED INTO MODELS/USER/USERMODEL.SWIFT static func loadUserFriends(userId:String,callback:(friends:[(id:String,nick:String)]?)->Void) { let criteria:[String:AnyObject] = ["me":"pub_\(userId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery KuasarsEntity.query( query, entityType: "friends", occEnabled: false, completion:{ (response:KuasarsResponse!, error:KuasarsError!) -> Void in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) } else { let batch = KuasarsBatch() let entities = response.contentObjects as! [KuasarsEntity] for entity:KuasarsEntity in entities { let friendId:String = (entity.customData!["friend"])! as! String print("Amigo encontrado:\(friendId)") let criteria:[String:AnyObject] = ["id":"\(friendId)"] let query = KuasarsQuery( criteria, retrievingFields: nil ) as KuasarsQuery let request:KuasarsRequest = KuasarsServices.queryEntities(query, type: "users", occEnabled: false) batch.addRequest(request) } batch.performRequests({ (response:KuasarsResponse!, error:KuasarsError!) in if( error != nil ) { print( "Error from kuasars: \(error.description)" ) callback(friends:nil) } else { var friends:[(id:String,nick:String)] = [(id:String,nick:String)]() let responses = response.contentObjects as! [NSDictionary] for index in 0 ..< responses.count { let rsp:NSDictionary = responses[index] as NSDictionary let body:[NSDictionary] = rsp["body"] as! [NSDictionary] let friendNick = body[0]["nick"] as! String /* print("Amigo :\(friendNick)") let usr = UILabel( frame: CGRectMake( 0, CGFloat(0 + 42*index), self.friendsScrollView.frame.width, 40 ) ); usr.text = friendNick usr.backgroundColor = UIColor.whiteColor() usr.textColor = UIColor.grayColor() self.friendsScrollView.addSubview( usr ) self.friendsScrollView.contentSize = CGSize( width:self.friendsScrollView.frame.width, height: CGFloat( 42 * index) ) */ let id:String = entities[index].customData["friend"] as! String friends.append( (id:id, nick:friendNick) ) } callback(friends: friends) } }) } }) } */ static func saveImageFromView(view:UIView)->Bool { UIGraphicsBeginImageContextWithOptions( view.bounds.size, true, 0 ) view.drawViewHierarchyInRect( view.bounds, afterScreenUpdates:true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //Save image in device. //.:Generate image name. let today:NSDate = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let strDateFormat = formatter.stringFromDate( today ) let fileName:String = "ouat-snapshot-\(strDateFormat).jpg" //.:Get path to save. let documentsURL:NSURL = NSFileManager.defaultManager().URLsForDirectory( .DocumentDirectory, inDomains:.UserDomainMask )[0] let fileURL:NSURL = documentsURL.URLByAppendingPathComponent( fileName ) let imagePath:String = fileURL.path! print("PATH to save image:\(imagePath)") //.:Save image as jpg file. let jpgImageData:NSData = UIImageJPEGRepresentation( image, 1.0 )! let isSavedOk:Bool = jpgImageData.writeToFile( imagePath, atomically:true ) return isSavedOk; } }
apache-2.0
RainbowMango/UIImagePickerControllerDemo
UIImagePickerControllerDemo/UIImagePickerControllerDemoTests/UIImagePickerControllerDemoTests.swift
1
950
// // UIImagePickerControllerDemoTests.swift // UIImagePickerControllerDemoTests // // Created by ruby on 14-12-26. // Copyright (c) 2014年 ruby. All rights reserved. // import UIKit import XCTest class UIImagePickerControllerDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
apache-2.0
nervousnet/nervousnet-iOS
nervous/Controllers/AccelerometerController.swift
1
3271
// // AccelerometerController.swift // nervousnet-iOS // // Created by Sid on 03 Mar 2016. // Copyright (c) 2016 ETHZ . All rights reserved. import Foundation import CoreMotion import CoreData import UIKit private let _ACC = AccelerometerController() class AccelerometerController : NSObject, SensorProtocol { private var auth: Int = 0 private var manager: CMMotionManager private let VM = VMController.sharedInstance internal var timestamp: UInt64 = 0 internal var x: Float = 0.0 internal var y: Float = 0.0 internal var z: Float = 0.0 override init() { self.manager = CMMotionManager() } class var sharedInstance: AccelerometerController { return _ACC } func requestAuthorization() { print("requesting authorization for acc") let val1 = self.VM.defaults.boolForKey("kill") //objectForKey("kill") as! Bool let val2 = self.VM.defaults.boolForKey("switchAcc") //objectForKey("switchAcc") as! Bool if !val1 && val2 { if self.manager.accelerometerAvailable { self.auth = 1 } } else { self.auth = 0 } } func initializeUpdate(freq: Double) { self.manager.accelerometerUpdateInterval = freq self.manager.startAccelerometerUpdates() } // requestAuthorization must be before this is function is called func startSensorUpdates() { if self.auth == 0 { return } let queue = NSOperationQueue() let currentTimeA :NSDate = NSDate() self.manager.startAccelerometerUpdatesToQueue(queue,withHandler: {data, error in self.timestamp = UInt64(currentTimeA.timeIntervalSince1970*1000) // time to timestamp //if let data = self.manager.accelerometerData { guard let data = data else { return } self.x = Float(data.acceleration.x) self.y = Float(data.acceleration.y) self.z = Float(data.acceleration.z) //print("accelerometer") //print(self.x) // store the current data in the CoreData database let val = self.VM.defaults.objectForKey("logAcc") as! Bool if val { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let entity = NSEntityDescription.entityForName("Accelerometer", inManagedObjectContext: managedContext) let acc = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) acc.setValue(NSNumber(unsignedLongLong: self.timestamp) , forKey: "timestamp") acc.setValue(self.x, forKey: "x") acc.setValue(self.y, forKey: "y") acc.setValue(self.z, forKey: "z") } }) } func stopSensorUpdates() { self.manager.stopAccelerometerUpdates() self.auth = 0 } }
gpl-3.0
onevcat/CotEditor
Tests/IncompatibleCharacterTests.swift
1
3168
// // IncompatibleCharacterTests.swift // Tests // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-05-29. // // --------------------------------------------------------------------------- // // © 2016-2022 1024jp // // 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 // // https://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 XCTest @testable import CotEditor final class IncompatibleCharacterTests: XCTestCase { func testIncompatibleCharacterScan() throws { let string = "abc\\ \n ¥ \n ~" let incompatibles = try string.scanIncompatibleCharacters(with: .plainShiftJIS) XCTAssertEqual(incompatibles.count, 2) let backslash = incompatibles.first! XCTAssertEqual(backslash.character, "\\") XCTAssertEqual(backslash.convertedCharacter, "\") XCTAssertEqual(backslash.location, 3) XCTAssertEqual(backslash.lineNumber, 1) let tilde = incompatibles[1] XCTAssertEqual(tilde.character, "~") XCTAssertEqual(tilde.convertedCharacter, "?") XCTAssertEqual(tilde.location, 11) XCTAssertEqual(tilde.lineNumber, 3) } func testSequencialIncompatibleCharactersScan() throws { let string = "~~" let incompatibles = try string.scanIncompatibleCharacters(with: .plainShiftJIS) XCTAssertEqual(incompatibles.count, 2) let tilde = incompatibles[1] XCTAssertEqual(tilde.character, "~") XCTAssertEqual(tilde.convertedCharacter, "?") XCTAssertEqual(tilde.location, 1) XCTAssertEqual(tilde.lineNumber, 1) } func testIncompatibleCharacterScanWithLengthShift() throws { let string = "family 👨‍👨‍👦 with 🐕" let incompatibles = try string.scanIncompatibleCharacters(with: .japaneseEUC) XCTAssertEqual(incompatibles.count, 2) XCTAssertEqual(incompatibles[0].character, "👨‍👨‍👦") XCTAssertEqual(incompatibles[0].convertedCharacter, "????????") XCTAssertEqual(incompatibles[0].location, 7) XCTAssertEqual(incompatibles[0].lineNumber, 1) XCTAssertEqual(incompatibles[1].character, "🐕") XCTAssertEqual(incompatibles[1].convertedCharacter, "??") XCTAssertEqual(incompatibles[1].location, 21) XCTAssertEqual(incompatibles[1].lineNumber, 1) } } private extension String.Encoding { static let plainShiftJIS = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.shiftJIS.rawValue))) }
apache-2.0
BrainDDump/Extractor
Extractor/AppDelegate.swift
1
4234
// // AppDelegate.swift // Extractor // // Created by Кирилл on 2/27/16. // Copyright © 2016 BrainDump. All rights reserved. // import UIKit import Parse import ParseFacebookUtilsV4 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let storyboard = UIStoryboard(name: "Main", bundle: nil) // MARK: - Application delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { User.initialize() Node.initialize() List.initialize() Parse.setApplicationId("K3iaNav9TphE8eopgbHoJUjWf7yNT5KGOsNG0Fb2", clientKey: "rVacb4z5iexRmUubmtdQtRY72KX2N0B6g5BuYQj3") PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions) FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) // Push notifications let settings = UIUserNotificationSettings(forTypes: [.Sound, .Badge], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() if let launchOptions = launchOptions as? [String : AnyObject] { if let notificationDictionary = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] { self.application(application, didReceiveRemoteNotification: notificationDictionary) } } tryToLoadMainApp() // Setup appearance configureView() return true } func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } // MARK: - Help methods func configureView() { UINavigationBar.appearance().barTintColor = UIColor(red: 237/255.0, green: 174/255.0, blue: 47/255.0, alpha: 1) UINavigationBar.appearance().translucent = false UINavigationBar.appearance().tintColor = UIColor.whiteColor() if let barFont = UIFont(name: "Avenir-Light", size: 24.0) { UINavigationBar.appearance().titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: barFont ] } } // MARK: - Push notifications func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { if PFUser.currentUser() != nil { let installation = PFInstallation.currentInstallation() installation["user"] = PFUser.currentUser() installation.setDeviceTokenFromData(deviceToken) installation.saveInBackground() } } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { PFPush.handlePush(userInfo) print(userInfo) NSNotificationCenter.defaultCenter().postNotificationName("refreshChatRoom", object: nil) } // MARK: - Global functions func tryToLoadMainApp() { if PFUser.currentUser() == nil { let loginVC = storyboard.instantiateInitialViewController() window?.rootViewController = loginVC } else { let mainVC = storyboard.instantiateViewControllerWithIdentifier("MainNavigationVC") window?.rootViewController = mainVC } } func logoutUser() { PFUser.logOutInBackgroundWithBlock { (error: NSError?) -> Void in if error != nil { print("Error occured while logging ") return } self.tryToLoadMainApp() } } }
apache-2.0
Piwigo/Piwigo-Mobile
piwigoKit/Supporting Files/URL+AppTools.swift
1
1493
// // URL+AppTools.swift // piwigo // // Created by Eddy Lelièvre-Berna on 06/02/2021. // Copyright © 2021 Piwigo.org. All rights reserved. // import Foundation extension URL { // Return the MD5 checksum of a file /// https://developer.apple.com/forums/thread/115401 public func MD5checksum() -> (String, NSError?) { var fileData: Data = Data() do { try fileData = NSData(contentsOf: self, options: .alwaysMapped) as Data // Determine MD5 checksum of video file to upload let md5Checksum = fileData.MD5checksum() return (md5Checksum, nil) } catch let error as NSError { // Report failure return ("", error) } } // Returns the file attributes var attributes: [FileAttributeKey : Any]? { do { return try FileManager.default.attributesOfItem(atPath: path) } catch let error as NSError { print("FileAttribute error: \(error)") } return nil } // Returns the file size var fileSize: UInt64 { return attributes?[.size] as? UInt64 ?? UInt64(0) } // Returns the unit of the file size var fileSizeString: String { return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file) } // Returns the creation date of the file var creationDate: Date? { return attributes?[.creationDate] as? Date } }
mit
thomashocking/SimpleGeo
Constants.swift
1
2125
// // Constants.swift // LSGeo // // Created by Thomas Hocking on 11/18/16. // Copyright © 2016 Thomas Hocking. All rights reserved. // import Foundation let NamesResultsKey : String = "NamesResultsKey" let TotalResultsCountKey : String = "TotalResultsCountKey" let AdminCode1Key : String = "AdminCode1Key" let AdminCode2Key : String = "AdminCode2Key" let AdminCode3Key : String = "AdminCode3Key" let AdminName1Key : String = "AdminName1Key" let AdminName2Key : String = "AdminName2Key" let AdminName3Key : String = "AdminName3Key" let AdminName4Key : String = "AdminName4Key" let NameKey : String = "NameKey" let ToponymNameKey : String = "ToponymNameKey" let ContinentCodeKey : String = "ContinentCodeKey" let CountryCodeKey : String = "CountryCodeKey" let CountryNameKey : String = "CountryNameKey" let PopulationKey : String = "PopulationKey" //used for wikipedia requests. let WikiTitleKey : String = "WikiTitleKey" let WikiSummaryKey : String = "WikiSummaryKey" let WikiURLKey : String = "WikiURLKey" let WikiFeatureKey : String = "WikiFeatureKey" let AlternateNamesKey : String = "AlternateNamesKey" let AlternateNameKey : String = "AlternateNameKey" let AlternateLanguageKey : String = "AlternateLanguageKey" let IDKey : String = "IDKey" let FeatureClassKey : String = "FeatureClassKey" let FeatureCodeKey : String = "FeatureCodeKey" let FeatureClassNameKey : String = "FeatureClassNameKey" let FeatureNameKey : String = "FeatureNameKey" let NamesScoreKey : String = "NamesScoreKey" let LatitudeKey : String = "LatitudeKey" let LongitudeKey : String = "LongitudeKey" let DistanceKey : String = "DistanceKey" let ElevationKey : String = "ElevationKey" let LanguageKey : String = "LanguageKey" //Wiki let RankKey : String = "RankKey" //Wiki let TimeZoneInfoKey : String = "TimeZoneInfoKey" let TimeZoneDSTOffsetKey : String = "TimeZoneDSTOffsetKey" let TimeZoneGMTOffsetKey : String = "TimeZoneGMTOffsetKey" let TimeZoneIDKey : String = "TimeZoneIDKey" let ErrorResponseKey : String = "ErrorResponseKey" let ErrorMessageKey : String = "ErrorMessageKey" let ErrorCodeKey : String = "ErrorCodeKey"
gpl-3.0
practicalswift/swift
test/IRGen/generic_types.swift
12
5100
// RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // REQUIRES: CPU=x86_64 // CHECK: [[A:%T13generic_types1AC]] = type <{ [[REF:%swift.refcounted]], [[INT:%TSi]] }> // CHECK: [[INT]] = type <{ i64 }> // CHECK: [[B:%T13generic_types1BC]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%TSp]] }> // CHECK: [[C:%T13generic_types1CC]] = type // CHECK: [[D:%T13generic_types1DC]] = type // CHECK-LABEL: @"$s13generic_types1ACMI" = internal global [16 x i8*] zeroinitializer, align 8 // CHECK-LABEL: @"$s13generic_types1ACMn" = hidden constant // CHECK-SAME: i32 -2147483440, // CHECK-SAME: @"$s13generic_typesMXM" // <name> // CHECK-SAME: @"$s13generic_types1ACMa" // -- superclass // CHECK-SAME: i32 0, // -- negative size in words // CHECK-SAME: i32 2, // -- positive size in words // CHECK-SAME: i32 17, // -- num immediate members // CHECK-SAME: i32 7, // -- num fields // CHECK-SAME: i32 1, // -- field offset vector offset // CHECK-SAME: i32 11, // -- instantiation cache // CHECK-SAME: @"$s13generic_types1ACMI" // -- instantiation pattern // CHECK-SAME: @"$s13generic_types1ACMP" // -- num generic params // CHECK-SAME: i16 1, // -- num generic requirement // CHECK-SAME: i16 0, // -- num key arguments // CHECK-SAME: i16 1, // -- num extra arguments // CHECK-SAME: i16 0, // -- parameter descriptor 1 // CHECK-SAME: i8 -128, // CHECK-LABEL: @"$s13generic_types1ACMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1ACMi" // -- heap destructor // CHECK-SAME: void ([[A]]*)* @"$s13generic_types1ACfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1BCMI" = internal global [16 x i8*] zeroinitializer, align 8 // CHECK-LABEL: @"$s13generic_types1BCMn" = hidden constant // CHECK-SAME: @"$s13generic_types1BCMa" // CHECK-SAME: @"$s13generic_types1BCMI" // CHECK-SAME: @"$s13generic_types1BCMP" // CHECK-LABEL: @"$s13generic_types1BCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1BCMi" // -- heap destructor // CHECK-SAME: void ([[B]]*)* @"$s13generic_types1BCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1CCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1CCMi" // -- heap destructor // CHECK-SAME: void ([[C]]*)* @"$s13generic_types1CCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } // CHECK-LABEL: @"$s13generic_types1DCMP" = internal constant // -- instantiation function // CHECK-SAME: @"$s13generic_types1DCMi" // -- heap destructor // CHECK-SAME: void ([[D]]*)* @"$s13generic_types1DCfD" // -- ivar destroyer // CHECK-SAME: i32 0, // -- class flags // CHECK-SAME: i32 {{3|2}}, // CHECK-SAME: } class A<T> { var x = 0 func run(_ t: T) {} init(y : Int) {} } class B<T> { var ptr : UnsafeMutablePointer<T> init(ptr: UnsafeMutablePointer<T>) { self.ptr = ptr } deinit { ptr.deinitialize(count: 1) } } class C<T> : A<Int> {} class D<T> : A<Int> { override func run(_ t: Int) {} } struct E<T> { var x : Int func foo() { bar() } func bar() {} } class ClassA {} class ClassB {} // This type is fixed-size across specializations, but it needs to use // a different implementation in IR-gen so that types match up. // It just asserts if we get it wrong. struct F<T: AnyObject> { var value: T } func testFixed() { var a = F(value: ClassA()).value var b = F(value: ClassB()).value } // Checking generic requirement encoding protocol P1 { } protocol P2 { associatedtype A } struct X1: P1 { } struct X2: P2 { typealias A = X1 } // Check for correct generic parameters in the nominal type descriptor // CHECK-LABEL: @"$s13generic_types2X3VMn" = // Root: generic parameter 1 // CHECK-SAME: @"symbolic q_" // U.A (via P2) // CHECK-SAME: @"symbolic 1A_____Qy_ 13generic_types2P2P struct X3<T, U> where U: P2, U.A: P1 { } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1ACMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2) // CHECK-NEXT: ret %swift.type* [[METADATA]] // CHECK: } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal %swift.type* @"$s13generic_types1BCMi"(%swift.type_descriptor*, i8**, i8*) {{.*}} { // CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type** // CHECK: %T = load %swift.type*, %swift.type** [[T0]], // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2) // CHECK-NEXT: ret %swift.type* [[METADATA]] // CHECK: }
apache-2.0
yanif/circator
MetabolicCompass/View Controller/AuthorizationViewControllers/AdditionalInfoViewController.swift
1
2519
// // AdditionalInfoViewController.swift // MetabolicCompass // // Created by Anna Tkach on 4/28/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit import MetabolicCompassKit import SwiftyUserDefaults import Crashlytics class AdditionalInfoViewController: BaseViewController { weak var registerViewController: RegisterViewController? var dataSource = AdditionalInfoDataSource() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() setupScrollViewForKeyboardsActions(collectionView) dataSource.collectionView = self.collectionView configureNavBar() } private func configureNavBar() { let cancelButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Cancel".localized) cancelButton.addTarget(self, action: #selector(cancelAction), forControlEvents: .TouchUpInside) let cancelBarButton = UIBarButtonItem(customView: cancelButton) let nextButton = ScreenManager.sharedInstance.appNavButtonWithTitle("Next".localized) nextButton.addTarget(self, action: #selector(nextAction), forControlEvents: .TouchUpInside) let nextBarButton = UIBarButtonItem(customView: nextButton) self.navigationItem.rightBarButtonItems = [nextBarButton] self.navigationItem.leftBarButtonItems = [cancelBarButton] self.navigationItem.title = NSLocalizedString("PHYSIOLOGICAL DATA", comment: "additional info data") } func cancelAction () { self.dismissViewControllerAnimated(true, completion: { [weak controller = self.registerViewController] in Answers.logCustomEventWithName("Register Additional", customAttributes: ["WithAdditional": false]) controller?.registrationComplete() }); } func nextAction() { startAction() dataSource.model.additionalInfoDict { (error, additionalInfo) in guard error == nil else { UINotifications.genericError(self, msg: error!) return } UserManager.sharedManager.saveAdditionalProfileData(additionalInfo) self.dismissViewControllerAnimated(true, completion: { [weak controller = self.registerViewController] in Answers.logCustomEventWithName("Register Additional", customAttributes: ["WithAdditional": true]) controller?.registrationComplete() }) } } }
apache-2.0
Authman2/Pix
Pods/Hero/Sources/Array+HeroModifier.swift
1
2186
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit internal extension Array { func get(_ index: Int) -> Element? { if index < count { return self[index] } return nil } func getCGFloat(_ index: Int) -> CGFloat? { if let s = get(index) as? String, let f = Float(s) { return CGFloat(f) } return nil } func getDouble(_ index: Int) -> Double? { if let s = get(index) as? String, let f = Double(s) { return f } return nil } func getFloat(_ index: Int) -> Float? { if let s = get(index) as? String, let f = Float(s) { return f } return nil } func getBool(_ index: Int) -> Bool? { if let s = get(index) as? String, let f = Bool(s) { return f } return nil } mutating func filterInPlace(_ comparator: (Element) -> Bool) -> [Element] { var array2: [Element] = [] self = self.filter { (element) -> Bool in if comparator(element) { return true } else { array2.append(element) return false } } return array2 } }
gpl-3.0
Yoloabdo/CS-193P
SmashTag/SmashTag/Reachability.swift
1
985
// // Reachability.swift // SmashTag // // Created by abdelrahman mohamed on 3/8/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } }
mit
huonw/swift
validation-test/compiler_crashers_fixed/00437-swift-nominaltypedecl-getdeclaredtypeincontext.swift
65
636
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol a { class b: a { } func f<T : Boolean>(b: T) { } func a(x: Any, y: Any) -> (((Any, Any) -> Any) -g { } if c == .b { } struct j<l : o> { } func a<l>() -> [j<l>] { } func f<l>() -> .l == l> { } protocol b { } struct j<n : b> : b {
apache-2.0
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Parser/Regex.swift
7
891
// // Regex.swift // Kaleidoscope // // Created by Matthew Cheok on 15/11/15. // Copyright © 2015 Matthew Cheok. All rights reserved. // import Foundation var expressions = [String: NSRegularExpression]() public extension String { public func match(regex: String) -> (String, CountableRange<Int>)? { let expression: NSRegularExpression if let exists = expressions[regex] { expression = exists } else { do { expression = try NSRegularExpression(pattern: "^\(regex)", options: []) expressions[regex] = expression } catch { return nil } } let range = expression.rangeOfFirstMatch(in: self, options: [], range: NSRange(0 ..< self.utf16.count)) if range.location != NSNotFound { return ((self as NSString).substring(with: range), range.location ..< range.location + range.length ) } return nil } }
mit
lionheart/LionheartExtensions
Pod/Classes/Core/NSDecimalNumber+LionheartExtensions.swift
2
2652
// // NSDecimalNumber.swift // Pods // // Created by Daniel Loewenherz on 3/16/16. // // import Foundation /** - source: https://gist.github.com/mattt/1ed12090d7c89f36fd28 */ extension NSDecimalNumber: Comparable {} public extension NSDecimalNumber { /// Returns `true` if two `NSDecimalNumber` values are equal, `false` otherwise. static func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedSame } /// Returns `true` if the first `NSDecimalNumber` parameter is less than the second, `false` otherwise. static func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedAscending } /// Returns `true` if the first `NSDecimalNumber` parameter is greater than the second, `false` otherwise. static func >(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool { return lhs.compare(rhs) == .orderedDescending } /// Returns the [additive inverse](https://en.wikipedia.org/wiki/Additive_inverse) of the provided `NSDecimalNumber`. static prefix func -(value: NSDecimalNumber) -> NSDecimalNumber { return value.multiplying(by: NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true)) } /// Returns the sum of two `NSDecimalNumber` values. static func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.adding(rhs) } /// Returns the difference of two `NSDecimalNumber` values. static func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.subtracting(rhs) } /// Returns the product of two `NSDecimalNumber` values. static func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.multiplying(by: rhs) } /// Returns the quotient of two `NSDecimalNumber` values. static func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber { return lhs.dividing(by: rhs) } /// Returns the result of raising the provided `NSDecimalNumber` to a specified power. static func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber { return lhs.raising(toPower: rhs) } // MARK: - Assignment static func +=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs + rhs } static func -=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs - rhs } static func *=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs * rhs } static func /=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) { lhs = lhs / rhs } }
apache-2.0
fellipecaetano/Democracy-iOS
Tests/Support/TestData.swift
1
913
import RandomKit import Fakery @testable import Democracy struct TestData { fileprivate static var randomGenerator = Xoroshiro.default fileprivate static var fakeDataGenerator = Faker() } extension TestData { static func error() -> Error { let domain = String.random(using: &randomGenerator) let code = Int.random(using: &randomGenerator) return NSError(domain: domain, code: code, userInfo: nil) } static func politicians(count: Int) -> [Politician] { return Array( Generator(count: count) { Politician( name: .random(using: &randomGenerator), photoUrl: URL(string: fakeDataGenerator.internet.url())!, partyAcronym: .random(using: &randomGenerator), federativeUnit: .random(using: &randomGenerator) ) } ) } }
mit
googlearchive/science-journal-ios
ScienceJournal/UI/SnapshotCardCell.swift
1
9567
/* * Copyright 2019 Google LLC. All Rights Reserved. * * 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 /// A cell displaying the results of sensor(s) snapshot in an Experiment. The cell contains one or /// more SnapshotCardViews, a header and an optional caption. class SnapshotCardCell: FrameLayoutMaterialCardCell { // MARK: - Properties weak var delegate: ExperimentCardCellDelegate? private let captionView = ExperimentCardCaptionView() private let headerView = ExperimentCardHeaderView() private var snapshotViews = [SnapshotCardView]() private var snapshotViewsContainer = UIView() private let separator = SeparatorView(direction: .horizontal, style: .dark) private var snapshotNote: DisplaySnapshotNote? // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override func layoutSubviews() { super.layoutSubviews() var nextOriginY: CGFloat = 0 if !headerView.isHidden { headerView.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: ExperimentCardHeaderView.height) nextOriginY = headerView.frame.maxY } separator.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: SeparatorView.Metrics.dimension) if let snapshots = snapshotNote?.snapshots { let snapshotViewsHeight = ceil(SnapshotCardCell.height(forSnapshots: snapshots, inWidth: cellContentView.bounds.width)) snapshotViewsContainer.frame = CGRect(x: 0, y: separator.frame.maxY, width: cellContentView.bounds.width, height: snapshotViewsHeight) for (index, snapshotView) in snapshotViews.enumerated() { let snapshotViewHeight = snapshotViewsHeight / CGFloat(snapshotViews.count) snapshotView.frame = CGRect(x: 0, y: snapshotViewHeight * CGFloat(index), width: cellContentView.bounds.width, height: snapshotViewHeight) } } if let caption = snapshotNote?.caption { let captionViewHeight = ceil(ExperimentCardCaptionView.heightWithCaption(caption, inWidth: cellContentView.bounds.width)) captionView.frame = CGRect(x: 0, y: snapshotViewsContainer.frame.maxY, width: cellContentView.bounds.width, height: captionViewHeight) } } override func prepareForReuse() { super.prepareForReuse() snapshotNote = nil } /// Sets the snapshot note to show in the cell and whether or not to show the header and /// inline timestamp. /// /// - Parameters: /// - snapshotNote: The snapshot note to show in the cell. /// - shouldShowHeader: Whether or not to show the header. /// - shouldShowInlineTimestamp: Whether or not to show the inline timestamp. /// - shouldShowCaptionButton: Whether or not to show the caption button. func setSnapshotNote(_ snapshotNote: DisplaySnapshotNote, showHeader shouldShowHeader: Bool, showInlineTimestamp shouldShowInlineTimestamp: Bool, showCaptionButton shouldShowCaptionButton: Bool, experimentDisplay: ExperimentDisplay = .normal) { self.snapshotNote = snapshotNote // Remove any snapshot views that are not needed. if snapshotViews.count > snapshotNote.snapshots.count { let rangeOfSnapshotViewsToRemove = snapshotNote.snapshots.count..<snapshotViews.count snapshotViews[rangeOfSnapshotViewsToRemove].forEach { $0.removeFromSuperview() } snapshotViews.removeSubrange(rangeOfSnapshotViewsToRemove) } // Add any snapshot views that are needed. for _ in snapshotViews.count..<snapshotNote.snapshots.count { let snapshotCardView = SnapshotCardView(preferredMaxLayoutWidth: bounds.width, showTimestamp: shouldShowInlineTimestamp) snapshotViews.append(snapshotCardView) snapshotViewsContainer.addSubview(snapshotCardView) } // Update snapshot views with snapshots. for (index, snapshot) in snapshotNote.snapshots.enumerated() { let snapshotView = snapshotViews[index] snapshotView.showTimestamp = shouldShowInlineTimestamp snapshotView.snapshot = snapshot } // Header. headerView.isHidden = !shouldShowHeader // Timestamp. headerView.headerTimestampLabel.text = snapshotNote.timestamp.string headerView.accessibilityLabel = snapshotNote.timestamp.string headerView.isTimestampRelative = snapshotNote.timestamp.isRelative // Caption and add caption button. if let caption = snapshotNote.caption { headerView.showCaptionButton = false captionView.isHidden = false captionView.captionLabel.text = caption } else { headerView.showCaptionButton = shouldShowCaptionButton captionView.isHidden = true } headerView.showMenuButton = experimentDisplay.showMenuButton setNeedsLayout() } /// Calculates the height required to display this view, given the data provided in `snapshots`. /// /// - Parameters: /// - width: Maximum width for this view, used to constrain measurements. /// - snapshotNote: The snapshot note to measure. /// - showingHeader: Whether or not the cell will be showing the header. /// - Returns: The total height of this view. Ideally, controllers would cache this value as it /// will not change for different instances of this view type. static func height(inWidth width: CGFloat, snapshotNote: DisplaySnapshotNote, showingHeader: Bool) -> CGFloat { // Measure the height of the snapshots. var totalHeight = SnapshotCardCell.height(forSnapshots: snapshotNote.snapshots, inWidth: width) // Add the separator height. totalHeight += SeparatorView.Metrics.dimension if showingHeader { // Add the header stack view's height. totalHeight += ExperimentCardHeaderView.height } // The caption, if necessary. if let caption = snapshotNote.caption { totalHeight += ExperimentCardCaptionView.heightWithCaption(caption, inWidth: width) } return totalHeight } // MARK: - Private private func configureView() { // Header view. cellContentView.addSubview(headerView) headerView.timestampButton.addTarget(self, action: #selector(timestampButtonPressed), for: .touchUpInside) headerView.commentButton.addTarget(self, action: #selector(commentButtonPressed), for: .touchUpInside) headerView.menuButton.addTarget(self, action: #selector(menuButtonPressed(sender:)), for: .touchUpInside) // Separator view. cellContentView.addSubview(separator) // Snapshot views container. cellContentView.addSubview(snapshotViewsContainer) // Caption view. cellContentView.addSubview(captionView) // Accessibility wrapping view, which sits behind all other elements to allow a user to "grab" // a cell by tapping anywhere in the empty space of a cell. let accessibilityWrappingView = UIView() cellContentView.configureAccessibilityWrappingView( accessibilityWrappingView, withLabel: String.noteContentDescriptionSnapshot, hint: String.doubleTapToViewDetails) // Set the order of elements to be the wrapping view first, then the header. accessibilityElements = [accessibilityWrappingView, headerView, snapshotViewsContainer] } private static func height(forSnapshots snapshots: [DisplaySnapshotValue], inWidth width: CGFloat) -> CGFloat { return snapshots.reduce(0) { (result, snapshot) in result + SnapshotCardView.heightForSnapshot(snapshot, inWidth: width) } } // MARK: - User actions @objc private func commentButtonPressed() { delegate?.experimentCardCellCommentButtonPressed(self) } @objc private func menuButtonPressed(sender: MenuButton) { delegate?.experimentCardCellMenuButtonPressed(self, button: sender) } @objc private func timestampButtonPressed() { delegate?.experimentCardCellTimestampButtonPressed(self) } }
apache-2.0
yscode001/YSExtension
YSExtension/YSExtension/YSExtension/UIViewController/UIViewController+ysExtension.swift
1
3135
import UIKit extension UIViewController{ /// push public func ys_pushTo(_ viewController:UIViewController, animated:Bool){ navigationController?.pushViewController(viewController, animated: animated) } /// pop public func ys_pop(animated:Bool){ navigationController?.popViewController(animated: animated) } public func ys_popToVC(_ viewController:UIViewController, animated:Bool){ navigationController?.popToViewController(viewController, animated: animated) } public func ys_popToRootVC(animated:Bool){ navigationController?.popToRootViewController(animated: animated) } /// 添加子控制器 public func ys_addChildViewController(childViewController:UIViewController, intoView:UIView, childViewFrame:CGRect? = nil){ addChild(childViewController) childViewController.view.frame = childViewFrame == nil ? intoView.bounds : childViewFrame! intoView.addSubview(childViewController.view) childViewController.didMove(toParent: self) } /// 弹出框 public func ys_alert(title:String?, message:String?, confirm:String, confirmClosure:@escaping(()->())){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let confirmAction = UIAlertAction(title: confirm, style: .default) { (_) in confirmClosure() } alertVC.addAction(confirmAction) present(alertVC, animated: true, completion: nil) } public func ys_alert(title:String?,message:String?,title1:String,title2:String,titleClosure1:@escaping(()->()),titleClosure2:@escaping(()->())) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let action1 = UIAlertAction(title: title1, style: .default) { (_) in titleClosure1() } let action2 = UIAlertAction(title: title2, style: .default) { (_) in titleClosure2() } alertVC.addAction(action1) alertVC.addAction(action2) present(alertVC, animated: true, completion: nil) } public func ys_confirm(title:String?, message:String?, cancel:String, confirm:String, cancelClosure:@escaping(()->()),confirmClosure:@escaping(()->())){ let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: cancel, style: .cancel) { (_) in cancelClosure() } let confirmAction = UIAlertAction(title: confirm, style: .default) { (_) in confirmClosure() } alertVC.addAction(cancelAction) alertVC.addAction(confirmAction) present(alertVC, animated: true, completion: nil) } public var ys_vcName:String{ // 示例:"<period.ArticleListVC: 0x7f818dc2b390>" let descString = self.description if let startRange = descString.range(of: "."),let endRange = descString.range(of: ":"){ return String(descString[startRange.upperBound..<endRange.lowerBound]) } return "" } }
mit
rporzuc/FindFriends
FindFriends/FindFriends/MyAccount/Edit User Data/EditUserNameViewController.swift
1
3445
// // EditUserNameViewController.swift // FindFriends // // Created by MacOSXRAFAL on 3/23/17. // Copyright © 2017 MacOSXRAFAL. All rights reserved. // import UIKit var editUserNameViewController :EditUserNameViewController! class EditUserNameViewController: UIViewController, UITextFieldDelegate { static var delegate : DelegateProtocolSendDataToMyAccount! var userImage = UIImage(named: "ImagePersonRounded") var firstName = "" var lastName = "" @IBOutlet var userImageView: UIImageView! @IBOutlet var textFieldFirstName: UITextField! @IBOutlet var textFieldLastName: UITextField! @IBOutlet var btnSave: UIButton! @IBOutlet var backgroundView: UIView! @IBAction func btnReturnClicked(_ sender: UIButton) { _ = self.navigationController?.popViewController(animated: true) editUserNameViewController = nil } @IBAction func btnSaveClicked(_ sender: Any) { let name_RegEx = "^[A-Za-z.ąęćółżźńś]{2,25}$" let nameTest = NSPredicate(format: "SELF MATCHES %@", name_RegEx) if (textFieldFirstName.text != "" && textFieldLastName.text != "" && nameTest.evaluate(with: textFieldFirstName.text) == true && nameTest.evaluate(with: textFieldLastName.text) == true) { EditUserNameViewController.delegate.saveValueFromEditUserNameViewController(firstName: textFieldFirstName.text!, lastName: textFieldLastName.text!, userImage: self.userImage!) _ = self.navigationController?.popViewController(animated: true) }else { self.showInformationAlertView(message: "Incorrect First or Last Name. Please enter a correct data.") } } @IBAction func editUserImageClicked(_ sender: UIButton) { self.performSegue(withIdentifier: "segueEditUserImage", sender: nil) } override func viewDidLoad() { super.viewDidLoad() userImageView.image = userImage userImageView.layer.cornerRadius = userImageView.frame.width / 2 textFieldFirstName.text = firstName textFieldLastName.text = lastName for txtField in [textFieldFirstName, textFieldLastName] { txtField?.setBottomBorderWithoutPlaceholder(viewColor: UIColor.white, borderColor: UIColor.lightGray, borderSize: 1) } backgroundView.layer.borderColor = UIColor.gray.cgColor backgroundView.layer.borderWidth = 1 editUserNameViewController = self } override func viewWillAppear(_ animated: Bool) { self.userImageView.image = self.userImage! } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let tagTouch = touches.first?.view?.tag if tagTouch == 99 { self.view.endEditing(true) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueEditUserImage" { let destination = segue.destination as! EditUserImageViewController destination.modalPresentationStyle = .overCurrentContext destination.userImage = self.userImage! } } }
gpl-3.0
PerrchicK/swift-app
SomeApp/SomeApp/Data/CloudUser.swift
1
1182
// // CloudUser.swift // SomeApp // // Created by Perry on 12/01/2018. // Copyright © 2018 PerrchicK. All rights reserved. // import Foundation import FirebaseAuth import Firebase //protocol FirebaseDictionaryConveratable { // func toFirebaseDictionary() //} // //extension FirebaseDictionaryConveratable { // /// https://stackoverflow.com/questions/25463146/iterate-over-object-class-attributes-in-swift // func toFirebaseDictionary() -> [String:Any] { // let mirrored_object = Mirror(reflecting: self) // var firebaseDictionary = [String:Any]() // for (index, attr) in mirrored_object.children.enumerated() { // if let propertyName = attr.label { // let propertyValue = attr.value // print("Attr \(index): \(propertyName) = \(propertyValue)") // firebaseDictionary[propertyName] = propertyValue // } // } // // return firebaseDictionary // } //} class CloudUser: DictionaryConvertible { private(set) var uid: String var fcmToken: String? init(from user: User, fcmToken: String?) { uid = user.uid self.fcmToken = fcmToken } }
apache-2.0
king7532/TaylorSource
examples/Gallery/Pods/HanekeSwift/Haneke/Haneke.swift
48
1367
// // Haneke.swift // Haneke // // Created by Hermes Pique on 9/9/14. // Copyright (c) 2014 Haneke. All rights reserved. // import UIKit public struct HanekeGlobals { public static let Domain = "io.haneke" } public struct Shared { public static var imageCache : Cache<UIImage> { struct Static { static let name = "shared-images" static let cache = Cache<UIImage>(name: name) } return Static.cache } public static var dataCache : Cache<NSData> { struct Static { static let name = "shared-data" static let cache = Cache<NSData>(name: name) } return Static.cache } public static var stringCache : Cache<String> { struct Static { static let name = "shared-strings" static let cache = Cache<String>(name: name) } return Static.cache } public static var JSONCache : Cache<JSON> { struct Static { static let name = "shared-json" static let cache = Cache<JSON>(name: name) } return Static.cache } } func errorWithCode(code : Int, #description : String) -> NSError { let userInfo = [NSLocalizedDescriptionKey: description] return NSError(domain: HanekeGlobals.Domain, code: code, userInfo: userInfo) }
mit
DarthStrom/BlackBox
Black Box/Models/Board.swift
1
1937
struct Board { var slots = [Location: Bool]() var entries = [Location: Int]() init() { clearSlots() populateEntries() } mutating func clearSlots() { for y in 0...7 { for x in 0...7 { slots[Location(x, y)] = false } } } mutating func populateEntries() { for n in 1...8 { entries[Location(-1, n-1)] = n } for n in 9...16 { entries[Location(n-9, 8)] = n } for n in 17...24 { entries[Location(8, 24-n)] = n } for n in 25...32 { entries[Location(32-n, -1)] = n } } mutating func placeAt(column: Int, andRow row: Int) { slots[Location(column, row)] = true } func getEntryPointAt(column: Int, andRow row: Int) -> Int? { return entries[Location(column, row)] } func getSlotAt(column: Int, andRow row: Int) -> Bool { if let result = slots[Location(column, row)] { return result } return false } func getLocationFor(entry: Int) -> Location? { switch entry { case 1...8: return Location(-1, entry - 1) case 9...16: return Location(entry - 9, 8) case 17...24: return Location(8, 24 - entry) case 25...32: return Location(32 - entry, -1) default: return nil } } func getDirectionFor(entry: Int) -> Direction? { switch entry { case 1...8: return .right case 9...16: return .up case 17...24: return .left case 25...32: return .down default: return nil } } func isInBox(position: Location) -> Bool { if slots[position] != nil { return true } return false } }
mit
ykws/yomblr
yomblr/ViewController.swift
1
8395
// // ViewController.swift // yomblr // // Created by Yoshiyuki Kawashima on 2017/06/21. // Copyright © 2017 ykws. All rights reserved. // import UIKit import TMTumblrSDK import SDWebImage import MBProgressHUD import ChameleonFramework class ViewController: UITableViewController { // MARK: - Properties private let limit: Int = 20 var user: User! var posts: [PhotoPost] = Array() var offset: Int = 0 var ignoreLikes: Int = 0 // MARK: - Actions @IBAction func dashboard(_ sender: Any) { TMTumblrAppClient.viewDashboard() } // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() setApplicationColor() refreshControl = UIRefreshControl() refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl?.addTarget(self, action: #selector(requestLikes), for: UIControlEvents.valueChanged) tableView.addSubview(refreshControl!) guard let oAuthToken = UserDefaults.standard.string(forKey: "OAuthToken"), let oAuthTokenSecret = UserDefaults.standard.string(forKey: "OAuthTokenSecret") else { requestAuthenticate() return } TMAPIClient.sharedInstance().oAuthToken = oAuthToken TMAPIClient.sharedInstance().oAuthTokenSecret = oAuthTokenSecret requestUserInfo() } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - TableView override func numberOfSections(in tableView: UITableView) -> Int { return posts.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts[section].photos.count } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 0 : 20 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let screenWidth = UIScreen.main.bounds.size.width guard let altSize = posts[indexPath.section].photos[indexPath.row].altSizes.first else { return screenWidth } let scale = screenWidth / CGFloat(altSize.width) return CGFloat(altSize.height) * scale } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = UIView() header.backgroundColor = UIColor.clear return header } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == (offset + limit - 1) { refreshView(withOffset: offset + limit) } let cell: CustomCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell guard let url = posts[indexPath.section].photos[indexPath.row].altSizes.first?.url else { showMessage("Can't retrieve url.") return cell } cell.photo.sd_setShowActivityIndicatorView(true) cell.photo.sd_setIndicatorStyle(.gray) cell.photo.sd_setImage(with: URL(string: url), placeholderImage: nil) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { logEvent(title: "Photo", type: "Image") let cell: CustomCell = tableView.cellForRow(at: indexPath) as! CustomCell crop(postIndex: indexPath.section, photoIndex: indexPath.row, image: cell.photo.image!) } // MARK: - Tumblr func requestAuthenticate() { TMAPIClient.sharedInstance().authenticate("yomblr", from: self, callback: { error in if (error != nil) { self.showError(error!) return } guard let oAuthToken = TMAPIClient.sharedInstance().oAuthToken, let oAuthTokenSecret = TMAPIClient.sharedInstance().oAuthTokenSecret else { self.showMessage("Can't retrieve OAuthToken or OAuthTokenSecret") return } UserDefaults.standard.set(oAuthToken, forKey: "OAuthToken") UserDefaults.standard.set(oAuthTokenSecret, forKey: "OAuthTokenSecret") self.requestUserInfo() }) } func requestUserInfo() { let hud = showProgress(withMessage: "Requesting user's information...") TMAPIClient.sharedInstance().userInfo({ response, error in self.hideProgress(hud: hud) if (error != nil) { self.showError(error!) return } do { self.user = try User.init(json: response!) } catch { self.showError(error) return } self.refreshView() }) } func requestDashboard(withOffset offset: Int = 0) { let hud = showProgress(withMessage: "Requesting dashboard...") TMAPIClient.sharedInstance().dashboard(["offset": offset, "type": "photo"], callback: { response, error in self.hideProgress(hud: hud) if (error != nil) { self.showError(error!) return } do { let dashboard = try Dashboard.init(json: response!) self.updatePosts(posts: dashboard.posts, offset: self.offset) } catch { self.showError(error) return } }) } func requestLikes(sender: AnyObject /*withOffset offset: Int = 0*/) { let hud = showProgress(withMessage: "Requesting likes...") TMAPIClient.sharedInstance().likes(user.blogs.first?.name, parameters: ["offset": offset], callback: { response, error in self.hideProgress(hud: hud) if (error != nil) { self.refreshControl?.endRefreshing() self.showError(error!) return } do { let likes = try Likes.init(json: response!) // Cancel displaying previous photo if no more previous likes photo if likes.likedPosts.count == 0 { self.refreshControl?.endRefreshing() self.showMessage("No more likes") return } self.updatePosts(posts: likes.likedPosts, offset: self.offset) self.ignoreLikes += likes.ignoreCount self.refreshControl?.endRefreshing() } catch { self.refreshControl?.endRefreshing() self.showError(error) return } }) } // MARK: - View func refreshView(withOffset offset: Int = 0) { self.offset = offset == 0 ? offset : offset + ignoreLikes requestLikes(sender: refreshControl!) } func updatePosts(posts: [PhotoPost], offset: Int) { if offset == 0 { self.posts = posts } else { posts.forEach { post in self.posts.append(post) } } self.offset = offset == 0 ? offset : offset - ignoreLikes tableView.reloadData() } // MARK: - Controller func browse(postIndex: Int) { let webViewController: WebViewController = storyboard?.instantiateViewController(withIdentifier: "web") as! WebViewController initWebViewController(webViewController, postIndex: postIndex) navigationController?.pushViewController(webViewController, animated: true) } func crop(postIndex: Int, photoIndex: Int, image: UIImage) { let cropViewController: CropViewController = storyboard?.instantiateViewController(withIdentifier: "crop") as! CropViewController cropViewController.blogName = user.blogs.first?.name cropViewController.image = image cropViewController.postUrl = posts[postIndex].photos[photoIndex].altSizes.first?.url navigationController?.pushViewController(cropViewController, animated: true) } // MARK: - Initializer func initWebViewController(_ webViewController: WebViewController, postIndex: Int) { webViewController.blogName = user.blogs.first?.name let targetString = posts[postIndex].sourceUrl ?? posts[postIndex].postUrl if targetString.contains("%") { webViewController.urlString = targetString return } let encodedString = targetString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) webViewController.urlString = encodedString } }
mit
crashoverride777/Swift-2-iAds-AdMob-CustomAds-Helper
Sources/Internal/SwiftyAdsBanner.swift
2
12842
// The MIT License (MIT) // // Copyright (c) 2015-2021 Dominik Ringler // // 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 GoogleMobileAds final class SwiftyAdsBanner: NSObject { // MARK: - Types private enum Configuration { static let visibleConstant: CGFloat = 0 static let hiddenConstant: CGFloat = 400 } // MARK: - Properties private let environment: SwiftyAdsEnvironment private let isDisabled: () -> Bool private let hasConsent: () -> Bool private let request: () -> GADRequest private var onOpen: (() -> Void)? private var onClose: (() -> Void)? private var onError: ((Error) -> Void)? private var onWillPresentScreen: (() -> Void)? private var onWillDismissScreen: (() -> Void)? private var onDidDismissScreen: (() -> Void)? private var bannerView: GADBannerView? private var position: SwiftyAdsBannerAdPosition = .bottom(isUsingSafeArea: true) private var animation: SwiftyAdsBannerAdAnimation = .none private var bannerViewConstraint: NSLayoutConstraint? private var animator: UIViewPropertyAnimator? // MARK: - Initialization init(environment: SwiftyAdsEnvironment, isDisabled: @escaping () -> Bool, hasConsent: @escaping () -> Bool, request: @escaping () -> GADRequest) { self.environment = environment self.isDisabled = isDisabled self.hasConsent = hasConsent self.request = request super.init() } // MARK: - Methods func prepare(withAdUnitId adUnitId: String, in viewController: UIViewController, position: SwiftyAdsBannerAdPosition, animation: SwiftyAdsBannerAdAnimation, onOpen: (() -> Void)?, onClose: (() -> Void)?, onError: ((Error) -> Void)?, onWillPresentScreen: (() -> Void)?, onWillDismissScreen: (() -> Void)?, onDidDismissScreen: (() -> Void)?) { self.position = position self.animation = animation self.onOpen = onOpen self.onClose = onClose self.onError = onError self.onWillPresentScreen = onWillPresentScreen self.onWillDismissScreen = onWillDismissScreen self.onDidDismissScreen = onDidDismissScreen // Create banner view let bannerView = GADBannerView() // Keep reference to created banner view self.bannerView = bannerView // Set ad unit id bannerView.adUnitID = adUnitId // Set the root view controller that will display the banner view bannerView.rootViewController = viewController // Set the banner view delegate bannerView.delegate = self // Add banner view to view controller add(bannerView, to: viewController) // Hide banner without animation hide(bannerView, from: viewController, skipAnimation: true) } } // MARK: - SwiftyAdsBannerType extension SwiftyAdsBanner: SwiftyAdsBannerType { func show(isLandscape: Bool) { guard !isDisabled() else { return } guard hasConsent() else { return } guard let bannerView = bannerView else { return } guard let currentView = bannerView.rootViewController?.view else { return } // Determine the view width to use for the ad width. let frame = { () -> CGRect in switch position { case .top(let isUsingSafeArea), .bottom(let isUsingSafeArea): if isUsingSafeArea { return currentView.frame.inset(by: currentView.safeAreaInsets) } else { return currentView.frame } } }() // Get Adaptive GADAdSize and set the ad view. if isLandscape { bannerView.adSize = GADLandscapeAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } else { bannerView.adSize = GADPortraitAnchoredAdaptiveBannerAdSizeWithWidth(frame.size.width) } // Create an ad request and load the adaptive banner ad. bannerView.load(request()) } func hide() { guard let bannerView = bannerView else { return } guard let rootViewController = bannerView.rootViewController else { return } hide(bannerView, from: rootViewController) } func remove() { guard bannerView != nil else { return } bannerView?.delegate = nil bannerView?.removeFromSuperview() bannerView = nil bannerViewConstraint = nil onClose?() } } // MARK: - GADBannerViewDelegate extension SwiftyAdsBanner: GADBannerViewDelegate { // Request lifecycle events func bannerViewDidRecordImpression(_ bannerView: GADBannerView) { if case .development = environment { print("SwiftyAdsBanner did record impression for banner ad") } } func bannerViewDidReceiveAd(_ bannerView: GADBannerView) { show(bannerView, from: bannerView.rootViewController) if case .development = environment { print("SwiftyAdsBanner did receive ad from: \(bannerView.responseInfo?.adNetworkClassName ?? "not found")") } } func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) { hide(bannerView, from: bannerView.rootViewController) onError?(error) } // Click-Time lifecycle events func bannerViewWillPresentScreen(_ bannerView: GADBannerView) { onWillPresentScreen?() } func bannerViewWillDismissScreen(_ bannerView: GADBannerView) { onWillDismissScreen?() } func bannerViewDidDismissScreen(_ bannerView: GADBannerView) { onDidDismissScreen?() } } // MARK: - Private Methods private extension SwiftyAdsBanner { func add(_ bannerView: GADBannerView, to viewController: UIViewController) { // Add banner view to view controller bannerView.translatesAutoresizingMaskIntoConstraints = false viewController.view.addSubview(bannerView) // Add constraints // We don't give the banner a width or height constraint, as the provided ad size will give the banner // an intrinsic content size switch position { case .top(let isUsingSafeArea): if isUsingSafeArea { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor) } else { bannerViewConstraint = bannerView.topAnchor.constraint(equalTo: viewController.view.topAnchor) } case .bottom(let isUsingSafeArea): if let tabBarController = viewController as? UITabBarController { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: tabBarController.tabBar.topAnchor) } else { if isUsingSafeArea { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor) } else { bannerViewConstraint = bannerView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor) } } } // Activate constraints NSLayoutConstraint.activate([ bannerView.centerXAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.centerXAnchor), bannerViewConstraint ].compactMap { $0 }) } func show(_ bannerAd: GADBannerView, from viewController: UIViewController?) { // Stop current animations stopCurrentAnimatorAnimations() // Show banner incase it was hidden bannerAd.isHidden = false // Animate if needed switch animation { case .none: animator = nil case .fade(let duration): animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 1 } case .slide(let duration): /// We can only animate the banner to its on-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its on-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its on-screen position if its not already visible guard bannerViewConstraint.constant != Configuration.visibleConstant else { return } /// Set banner constraint bannerViewConstraint.constant = Configuration.visibleConstant /// Animate constraint changes animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } // Add animation completion if needed animator?.addCompletion { [weak self] _ in self?.onOpen?() } // Start animation if needed animator?.startAnimation() } func hide(_ bannerAd: GADBannerView, from viewController: UIViewController?, skipAnimation: Bool = false) { // Stop current animations stopCurrentAnimatorAnimations() // Animate if needed switch animation { case .none: animator = nil bannerAd.isHidden = true case .fade(let duration): if skipAnimation { bannerView?.alpha = 0 } else { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { [weak bannerView] in bannerView?.alpha = 0 } } case .slide(let duration): /// We can only animate the banner to its off-screen position with a valid view controller guard let viewController = viewController else { return } /// We can only animate the banner to its off-screen position if it has a constraint guard let bannerViewConstraint = bannerViewConstraint else { return } /// We can only animate the banner to its off-screen position if its already visible guard bannerViewConstraint.constant == Configuration.visibleConstant else { return } /// Get banner off-screen constant var newConstant: CGFloat { switch position { case .top: return -Configuration.hiddenConstant case .bottom: return Configuration.hiddenConstant } } /// Set banner constraint bannerViewConstraint.constant = newConstant /// Animate constraint changes if !skipAnimation { animator = UIViewPropertyAnimator(duration: duration, curve: .easeOut) { viewController.view.layoutIfNeeded() } } } // Add animation completion if needed animator?.addCompletion { [weak self, weak bannerAd] _ in bannerAd?.isHidden = true self?.onClose?() } // Start animation if needed animator?.startAnimation() } func stopCurrentAnimatorAnimations() { animator?.stopAnimation(false) animator?.finishAnimation(at: .current) } } // MARK: - Deprecated extension SwiftyAdsBanner { @available(*, deprecated, message: "Please use new hide method without animated parameter") func hide(animated: Bool) { hide() } }
mit
kesun421/firefox-ios
Storage/SQL/SQLiteMetadata.swift
7
2337
/* 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 Deferred import Shared /// The sqlite-backed implementation of the metadata protocol containing images and content for pages. open class SQLiteMetadata { let db: BrowserDB required public init(db: BrowserDB) { self.db = db } } extension SQLiteMetadata: Metadata { // A cache key is a conveninent, readable identifier for a site in the metadata database which helps // with deduping entries for the same page. typealias CacheKey = String /// Persists the given PageMetadata object to browser.db in the page_metadata table. /// /// - parameter metadata: Metadata object /// - parameter pageURL: URL of page metadata was fetched from /// - parameter expireAt: Expiration/TTL interval for when this metadata should expire at. /// /// - returns: Deferred on success public func storeMetadata(_ metadata: PageMetadata, forPageURL pageURL: URL, expireAt: UInt64) -> Success { guard let cacheKey = pageURL.displayURL?.absoluteString else { return succeed() } // Replace any matching cache_key entries if they exist let selectUniqueCacheKey = "COALESCE((SELECT cache_key FROM \(TablePageMetadata) WHERE cache_key = ?), ?)" let args: Args = [cacheKey, cacheKey, metadata.siteURL, metadata.mediaURL, metadata.title, metadata.type, metadata.description, metadata.providerName, expireAt] let insert = "INSERT OR REPLACE INTO \(TablePageMetadata)" + "(cache_key, site_url, media_url, title, type, description, provider_name, expired_at) " + "VALUES ( \(selectUniqueCacheKey), ?, ?, ?, ?, ?, ?, ?)" return self.db.run(insert, withArgs: args) } /// Purges any metadata items living in page_metadata that are expired. /// /// - returns: Deferred on success public func deleteExpiredMetadata() -> Success { let sql = "DELETE FROM page_metadata WHERE expired_at <= (CAST(strftime('%s', 'now') AS LONG)*1000)" return self.db.run(sql) } }
mpl-2.0
alexsosn/Word2Vec-iOS
Word2Vec-iOS/AppDelegate.swift
1
2152
// // AppDelegate.swift // Word2Vec-iOS // // Created by Alex on 10/8/15. // Copyright © 2015 OWL. All rights reserved. // import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? 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:. } }
apache-2.0
austinzheng/swift-compiler-crashes
crashes-duplicates/16404-swift-sourcemanager-getmessage.swift
11
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { func a { init( = [ { let d{ class d{ class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/17727-no-stacktrace.swift
11
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol c { class A { func i( ) -> { for in { if true { class case ,
mit
audiokit/AudioKit
Sources/AudioKit/Nodes/Effects/Guitar Processors/DynaRageCompressor.swift
1
5110
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit /// DynaRage Tube Compressor | Based on DynaRage Tube Compressor RE for Reason /// by Devoloop Srls /// public class DynaRageCompressor: Node, AudioUnitContainer, Toggleable { /// Unique four-letter identifier "dyrc" public static let ComponentDescription = AudioComponentDescription(effect: "dyrc") /// Internal type of audio unit for this node public typealias AudioUnitType = InternalAU /// Internal audio unit public private(set) var internalAU: AudioUnitType? // MARK: - Parameters /// Specification details for ratio public static let ratioDef = NodeParameterDef( identifier: "ratio", name: "Ratio to compress with, a value > 1 will compress", address: akGetParameterAddress("DynaRageCompressorParameterRatio"), range: 1.0 ... 20.0, unit: .generic, flags: .default) /// Ratio to compress with, a value > 1 will compress @Parameter public var ratio: AUValue /// Specification details for threshold public static let thresholdDef = NodeParameterDef( identifier: "threshold", name: "Threshold (in dB) 0 = max", address: akGetParameterAddress("DynaRageCompressorParameterThreshold"), range: -100.0 ... 0.0, unit: .decibels, flags: .default) /// Threshold (in dB) 0 = max @Parameter public var threshold: AUValue /// Specification details for attack duration public static let attackDurationDef = NodeParameterDef( identifier: "attackDuration", name: "Attack Duration", address: akGetParameterAddress("DynaRageCompressorParameterAttackDuration"), range: 0.1 ... 500.0, unit: .seconds, flags: .default) /// Attack dration @Parameter public var attackDuration: AUValue /// Specification details for release duration public static let releaseDurationDef = NodeParameterDef( identifier: "releaseDuration", name: "Release Duration", address: akGetParameterAddress("DynaRageCompressorParameterReleaseDuration"), range: 1.0 ... 20.0, unit: .seconds, flags: .default) /// Release duration @Parameter public var releaseDuration: AUValue /// Specification details for rage amount public static let rageDef = NodeParameterDef( identifier: "rage", name: "Rage", address: akGetParameterAddress("DynaRageCompressorParameterRage"), range: 0.1 ... 20.0, unit: .generic, flags: .default) /// Rage Amount @Parameter public var rage: AUValue /// Specification details for range enabling public static let rageEnabledDef = NodeParameterDef( identifier: "rageEnabled", name: "Rage Enabled", address: akGetParameterAddress("DynaRageCompressorParameterRageEnabled"), range: 0.0 ... 1.0, unit: .boolean, flags: .default) /// Rage ON/OFF Switch @Parameter public var rageEnabled: Bool // MARK: - Audio Unit /// Internal audio unit for DynaRageCompressor public class InternalAU: AudioUnitBase { /// Get an array of the parameter definitions /// - Returns: Array of parameter definitions public override func getParameterDefs() -> [NodeParameterDef] { [DynaRageCompressor.ratioDef, DynaRageCompressor.thresholdDef, DynaRageCompressor.attackDurationDef, DynaRageCompressor.releaseDurationDef, DynaRageCompressor.rageDef, DynaRageCompressor.rageEnabledDef] } /// Create the DSP Refence for this node /// - Returns: DSP Reference public override func createDSP() -> DSPRef { akCreateDSP("DynaRageCompressorDSP") } } // MARK: - Initialization /// Initialize this compressor node /// /// - Parameters: /// - input: Input node to process /// - ratio: Ratio to compress with, a value > 1 will compress /// - threshold: Threshold (in dB) 0 = max /// - attackDuration: Attack duration in seconds /// - releaseDuration: Release duration in seconds /// public init( _ input: Node, ratio: AUValue = 1, threshold: AUValue = 0.0, attackDuration: AUValue = 0.1, releaseDuration: AUValue = 0.1, rage: AUValue = 0.1, rageEnabled: Bool = true ) { super.init(avAudioNode: AVAudioNode()) instantiateAudioUnit { avAudioUnit in self.avAudioUnit = avAudioUnit self.avAudioNode = avAudioUnit self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType self.ratio = ratio self.threshold = threshold self.attackDuration = attackDuration self.releaseDuration = releaseDuration self.rage = rage self.rageEnabled = rageEnabled } connections.append(input) } }
mit
AstronautSloth/Ultimate-Tic-Tac-Toe
Quantum Tic-Tac-ToeUITests/Quantum_Tic_Tac_ToeUITests.swift
1
1286
// // Quantum_Tic_Tac_ToeUITests.swift // Quantum Tic-Tac-ToeUITests // // Created by Colin Thompson on 9/19/15. // Copyright © 2015 Colin Thompson. All rights reserved. // import XCTest class Quantum_Tic_Tac_ToeUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
CatchChat/Yep
Yep/Extensions/CGImage+Yep.swift
1
1331
// // CGImage+Yep.swift // Yep // // Created by nixzhu on 16/1/27. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation extension CGImage { var yep_extendedCanvasCGImage: CGImage { let width = CGImageGetWidth(self) let height = CGImageGetHeight(self) guard width > 0 && height > 0 else { return self } func hasAlpha() -> Bool { let alpha = CGImageGetAlphaInfo(self) switch alpha { case .First, .Last, .PremultipliedFirst, .PremultipliedLast: return true default: return false } } var bitmapInfo = CGBitmapInfo.ByteOrder32Little.rawValue if hasAlpha() { bitmapInfo |= CGImageAlphaInfo.PremultipliedFirst.rawValue } else { bitmapInfo |= CGImageAlphaInfo.NoneSkipFirst.rawValue } guard let context = CGBitmapContextCreate(nil, width, height, 8, 0, CGColorSpaceCreateDeviceRGB(), bitmapInfo) else { return self } CGContextDrawImage(context, CGRect(x: 0, y: 0, width: width, height: height), self) guard let newCGImage = CGBitmapContextCreateImage(context) else { return self } return newCGImage } }
mit
cuappdev/tempo
Tempo/Views/LikedPostView.swift
1
7020
// // LikedPostView.swift // Tempo // // Created by Logan Allen on 11/18/16. // Copyright © 2016 CUAppDev. All rights reserved. // import UIKit import MediaPlayer import Haneke class LikedPostView: PostView { fileprivate var tapGestureRecognizer: UITapGestureRecognizer? fileprivate var longPressGestureRecognizer: UILongPressGestureRecognizer? let artworkImageLength: CGFloat = 54 let addButtonLength: CGFloat = 20 let padding: CGFloat = 22 let addButtonPadding: CGFloat = 17 let separatorHeight: CGFloat = 1 var labelWidth: CGFloat = 0 var isSpotifyAvailable: Bool = false var songNameLabel: UILabel? var songArtistLabel: UILabel? var albumArtworkImageView: UIImageView? var addButton: UIButton? var songStatus: SavedSongStatus = .notSaved var postViewDelegate: PostViewDelegate! var playerDelegate: PlayerDelegate! var playerController: PlayerTableViewController? override var post: Post? { didSet { // update stuff if let post = post { songNameLabel?.text = post.song.title songArtistLabel?.text = post.song.artist albumArtworkImageView?.hnk_setImageFromURL(post.song.smallArtworkURL ?? URL(fileURLWithPath: "")) if let _ = User.currentUser.currentSpotifyUser?.savedTracks[post.song.spotifyID] { songStatus = .saved } updateAddButton() } } } override func didMoveToSuperview() { super.didMoveToSuperview() backgroundColor = .unreadCellColor albumArtworkImageView = UIImageView(frame: CGRect(x: padding, y: padding, width: artworkImageLength, height: artworkImageLength)) albumArtworkImageView?.center.y = center.y albumArtworkImageView?.clipsToBounds = true albumArtworkImageView?.translatesAutoresizingMaskIntoConstraints = true addSubview(albumArtworkImageView!) let labelX = (albumArtworkImageView?.frame.maxX)! + padding let shorterlabelWidth = bounds.width - labelX - addButtonLength - 2*addButtonPadding let longerLabelWidth = bounds.width - labelX - padding let currLabelWidth = isSpotifyAvailable ? shorterlabelWidth : longerLabelWidth songNameLabel = UILabel(frame: CGRect(x: labelX, y: padding, width: currLabelWidth, height: 22)) songNameLabel?.font = UIFont(name: "AvenirNext-Regular", size: 16.0) songNameLabel?.textColor = .white songNameLabel?.translatesAutoresizingMaskIntoConstraints = false addSubview(songNameLabel!) songArtistLabel = UILabel(frame: CGRect(x: labelX, y: (songNameLabel?.frame.maxY)! + 2, width: currLabelWidth, height: 22)) songArtistLabel?.font = UIFont(name: "AvenirNext-Regular", size: 14.0) songArtistLabel?.textColor = .paleRed songArtistLabel?.translatesAutoresizingMaskIntoConstraints = false addSubview(songArtistLabel!) addButton = UIButton(frame: CGRect(x: frame.width - addButtonLength - addButtonPadding, y: 34, width: addButtonLength, height: addButtonLength)) addButton?.center.y = center.y addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddButton"), for: .normal) addButton?.translatesAutoresizingMaskIntoConstraints = true addButton?.tag = 1 // this tag makes the hitbox bigger addButton?.isHidden = !isSpotifyAvailable addSubview(addButton!) } override func updatePlayingStatus() { updateSongLabel() updateBackground() } override func didMoveToWindow() { if tapGestureRecognizer == nil { tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(likedPostViewPressed(_:))) tapGestureRecognizer?.delegate = self tapGestureRecognizer?.cancelsTouchesInView = false addGestureRecognizer(tapGestureRecognizer!) } if longPressGestureRecognizer == nil { longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(likedPostViewPressed(_:))) longPressGestureRecognizer?.delegate = self longPressGestureRecognizer?.minimumPressDuration = 0.5 longPressGestureRecognizer?.cancelsTouchesInView = false addGestureRecognizer(longPressGestureRecognizer!) } isUserInteractionEnabled = true } // Customize view to be able to re-use it for search results. func flagAsSearchResultPost() { songArtistLabel?.text = "\(post!.song.title) · \(post!.song.album)" } func updateAddButton() { if let _ = post { if songStatus == .saved { self.addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddedButton"), for: .normal) } else { self.addButton?.setBackgroundImage(#imageLiteral(resourceName: "AddButton"), for: .normal) } } } func updateSongLabel() { if let post = post { let duration = TimeInterval(0.3) let color: UIColor = post.player.isPlaying ? .tempoRed : .white let font: UIFont = post.player.isPlaying ? UIFont(name: "AvenirNext-Medium", size: 16.0)! : UIFont(name: "AvenirNext-Regular", size: 16.0)! guard let label = songNameLabel else { return } if !label.textColor.isEqual(color) { UIView.transition(with: label, duration: duration, options: .transitionCrossDissolve, animations: { label.textColor = color label.font = font }) } } } func updateViews() { if isSpotifyAvailable { songNameLabel?.frame.size.width = labelWidth songArtistLabel?.frame.size.width = labelWidth addButton!.isHidden = false } else { let newLabelWidth = bounds.width - (songNameLabel?.frame.minX)! - padding songNameLabel?.frame.size.width = newLabelWidth songArtistLabel?.frame.size.width = newLabelWidth addButton!.isHidden = true } } override func updateBackground() { if let post = post { backgroundColor = post.player.isPlaying ? .readCellColor : .unreadCellColor } } func likedPostViewPressed(_ sender: UIGestureRecognizer) { guard let _ = post else { return } if sender is UITapGestureRecognizer { let tapPoint = sender.location(in: self) let hitView = hitTest(tapPoint, with: nil) if hitView == addButton { if songStatus == .notSaved { SpotifyController.sharedController.saveSpotifyTrack(post!) { success in if success { self.songStatus = .saved self.updateAddButton() self.playerDelegate.didToggleAdd?() self.postViewDelegate?.didTapAddButtonForPostView?(true) } } } else if songStatus == .saved { SpotifyController.sharedController.removeSavedSpotifyTrack(post!) { success in if success { self.songStatus = .notSaved self.updateAddButton() self.playerDelegate.didToggleAdd?() self.postViewDelegate?.didTapAddButtonForPostView?(false) } } } } } } func updateSavedStatus() { if let selectedPost = post { if let _ = User.currentUser.currentSpotifyUser?.savedTracks[selectedPost.song.spotifyID] { songStatus = .saved } else { songStatus = .notSaved } } } func updateAddStatus() { if let _ = post { updateSavedStatus() let image = (songStatus == .saved) ? #imageLiteral(resourceName: "AddedButton") : #imageLiteral(resourceName: "AddButton") addButton?.setBackgroundImage(image, for: .normal) } } }
mit
CodePath2017Group4/travel-app
Pods/CDYelpFusionKit/Source/CDYelpAutoCompleteResponse.swift
1
1772
// // CDYelpAutoCompleteResponse.swift // CDYelpFusionKit // // Created by Christopher de Haan on 5/7/17. // // Copyright (c) 2016-2017 Christopher de Haan <contact@christopherdehaan.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 ObjectMapper public class CDYelpAutoCompleteResponse: Mappable { public var terms: [CDYelpTerm]? public var businesses: [CDYelpBusiness]? public var categories: [CDYelpCategory]? public var error: CDYelpError? public required init?(map: Map) { } public func mapping(map: Map) { terms <- map["terms"] businesses <- map["businesses"] categories <- map["categories"] error <- map["error"] } }
mit
rhcad/SwiftGraphics
Demos/SwiftGraphics_OSX_UITest/HandleEditor/Dragging.swift
4
1940
// // Dragging.swift // HandleEditor // // Created by Jonathan Wight on 11/12/14. // Copyright (c) 2014 schwa.io. All rights reserved. // import Cocoa import SwiftGraphics protocol Draggable { var position: CGPoint { get set } } class Drag: NSObject, NSGestureRecognizerDelegate { var draggedObject:Draggable! var offset:CGPoint = CGPointZero var panGestureRecogniser:NSPanGestureRecognizer! var objectForPoint:((CGPoint) -> (Draggable?))! var objectDidChange:((Draggable) -> (Void))! var dragDidFinish:((Void) -> (Void))! override init() { super.init() panGestureRecogniser = NSPanGestureRecognizer(target: self, action:"pan:") panGestureRecogniser.delegate = self } internal func pan(recognizer:NSPanGestureRecognizer) { switch recognizer.state { case .Began: let location = recognizer.locationInView(recognizer.view) draggedObject = objectForPoint(location) if draggedObject != nil { offset = location - draggedObject.position } case .Changed: if draggedObject != nil { let location = recognizer.locationInView(recognizer.view) draggedObject.position = location objectDidChange?(draggedObject) } break case .Ended: draggedObject = nil dragDidFinish?() default: break } } func gestureRecognizerShouldBegin(gestureRecognizer: NSGestureRecognizer) -> Bool { switch gestureRecognizer { case panGestureRecogniser: let location = panGestureRecogniser.locationInView(panGestureRecogniser.view) return objectForPoint(location) != nil default: return true } } }
bsd-2-clause
apple/swift
test/SourceKit/CodeFormat/indent-trailing/trailing-parameter-list-empty.swift
22
166
class Foo { func foo( // RUN: %sourcekitd-test -req=format -line=3 -length=1 %s | %FileCheck --strict-whitespace %s // CHECK: key.sourcetext: " "
apache-2.0
jbrayton/Golden-Hill-HTTP-Library
GoldenHillHTTPLibrary/HTTPAPIResult.swift
1
298
// // HTTPAPIResult.swift // Filters // // Created by John Brayton on 10/2/16. // Copyright © 2016 John Brayton. All rights reserved. // import Foundation public typealias HTTPAPIResult<T> = Result<T,HTTPAPIError> public typealias HTTPAPIResultHandler<T> = (Result<T,HTTPAPIError>) -> Void
mit