repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
safx/TypetalkApp
|
refs/heads/master
|
TypetalkApp/OSX/ViewControllers/EditTopicViewController.swift
|
mit
|
1
|
//
// EditTopicViewController.swift
// TypetalkApp
//
// Created by Safx Developer on 2015/02/22.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import Cocoa
import TypetalkKit
import RxSwift
class EditTopicViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
let viewModel = EditTopicViewModel()
@IBOutlet weak var topicNameLabel: NSTextField!
@IBOutlet weak var teamListBox: NSComboBox!
@IBOutlet weak var idLabel: NSTextField!
@IBOutlet weak var createdLabel: NSTextField!
@IBOutlet weak var updatedLabel: NSTextField!
@IBOutlet weak var lastPostedLabel: NSTextField!
@IBOutlet weak var acceptButton: NSButton!
@IBOutlet weak var membersTableView: NSTableView!
@IBOutlet weak var invitesTableView: NSTableView!
private let disposeBag = DisposeBag()
var topic: Topic? = nil {
didSet {
self.viewModel.fetch(topic!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
membersTableView.setDelegate(self)
membersTableView.setDataSource(self)
invitesTableView.setDelegate(self)
invitesTableView.setDataSource(self)
teamListBox.editable = false
acceptButton.enabled = false
precondition(topic != nil)
self.topicNameLabel.stringValue = topic!.name
self.idLabel.stringValue = "\(topic!.id)"
self.createdLabel.stringValue = topic!.createdAt.humanReadableTimeInterval
self.updatedLabel.stringValue = topic!.updatedAt.humanReadableTimeInterval
if let posted = topic!.lastPostedAt {
self.lastPostedLabel.stringValue = posted.humanReadableTimeInterval
}
Observable.combineLatest(viewModel.teamListIndex.asObservable(), viewModel.teamList.asObservable()) { ($0, $1) }
.filter { !$0.1.isEmpty }
.subscribeOn(MainScheduler.instance)
.subscribeNext { (index, teams) -> () in
self.teamListBox.removeAllItems()
self.teamListBox.addItemsWithObjectValues(teams.map { $0.description } )
self.teamListBox.selectItemAtIndex(index)
self.acceptButton.enabled = true
}
.addDisposableTo(disposeBag)
Observable.combineLatest(viewModel.teamList.asObservable(), teamListBox.rx_selectionSignal()) { ($0, $1) }
.filter { teams, idx in teams.count > 0 && (0..<teams.count).contains(idx) }
.map { teams, idx in TeamID(teams[idx].id) }
.bindTo(viewModel.teamId)
.addDisposableTo(disposeBag)
topicNameLabel
.rx_text
.throttle(0.05, scheduler: MainScheduler.instance)
.bindTo(viewModel.topicName)
.addDisposableTo(disposeBag)
viewModel.accounts
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.membersTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
viewModel.invites
.asObservable()
.subscribeOn(MainScheduler.instance)
.subscribeNext { [weak self] _ in
self?.invitesTableView.reloadData()
()
}
.addDisposableTo(disposeBag)
}
@IBAction func deleteTopic(sender: AnyObject) {
let alert = NSAlert()
alert.addButtonWithTitle("Delete")
alert.addButtonWithTitle("Cancel")
let bs = alert.buttons as [NSButton]
bs[0].keyEquivalent = "\033"
bs[1].keyEquivalent = "\r"
alert.messageText = "Remove “\(topic!.name)”"
alert.informativeText = "WARNING: All messages in this topic will be removed permanently."
alert.alertStyle = .WarningAlertStyle
if let key = NSApp.keyWindow {
alert.beginSheetModalForWindow(key) { [weak self] res in
if res == NSAlertFirstButtonReturn {
if let s = self {
s.viewModel.deleteTopic()
s.presentingViewController?.dismissViewController(s)
}
}
}
}
}
@IBAction func exit(sender: NSButton) {
presentingViewController?.dismissViewController(self)
}
@IBAction func accept(sender: AnyObject) {
viewModel.updateTopic()
presentingViewController?.dismissViewController(self)
}
// MARK: - NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if tableView == membersTableView {
return viewModel.accounts.value.count
} else if tableView == invitesTableView {
return viewModel.invites.value.count
}
return 0
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
if let i = tableColumn?.identifier {
if tableView == membersTableView && 0 <= row && row < viewModel.accounts.value.count {
let account = viewModel.accounts.value[row]
if i == "image" { return NSImage(contentsOfURL: account.imageUrl) }
if i == "name" { return account.name }
if i == "date" { return account.createdAt.humanReadableTimeInterval }
}
else if tableView == invitesTableView && 0 <= row && row < viewModel.invites.value.count {
let invite = viewModel.invites.value[row]
if i == "image" {
if let a = invite.account {
return NSImage(contentsOfURL: a.imageUrl)
}
}
if i == "name" { return invite.account?.name ?? "" }
if i == "status" { return invite.status }
if i == "date" { return invite.createdAt?.humanReadableTimeInterval ?? "" }
}
}
return nil
}
// MARK: - NSTableViewDelegate
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 20
}
}
|
7f06457ebbb07cfe779d21fcf276c793
| 35.52071 | 123 | 0.604018 | false | false | false | false |
ushios/SwifTumb
|
refs/heads/master
|
Sources/SwifTumb/OAuthSwiftAdapter.swift
|
mit
|
1
|
//
// OAuthSwiftAdapter.swift
// SwifTumb
//
// Created by Ushio Shugo on 2016/12/11.
//
//
import Foundation
import OAuthSwift
open class OAuthSwiftAdapter: OAuth1Swift, SwifTumbOAuthAdapter {
public init(
consumerKey: String,
consumerSecret: String,
oauthToken: String,
oauthTokenSecret: String
) {
super.init(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
requestTokenUrl: SwifTumb.RequestTokenUrl,
authorizeUrl: SwifTumb.AuthorizeUrl,
accessTokenUrl: SwifTumb.AccessTokenUrl
)
self.client.credential.oauthToken = oauthToken
self.client.credential.oauthTokenSecret = oauthTokenSecret
}
convenience init (consumerKey: String, consumerSecret: String) {
self.init(
consumerKey: consumerKey,
consumerSecret: consumerSecret,
oauthToken: "",
oauthTokenSecret: ""
)
}
public func request(
_ urlString: String,
method: SwifTumbHttpRequest.Method,
parameters: SwifTumb.Parameters = [:],
headers: SwifTumb.Headers? = nil,
body: Data? = nil,
checkTokenExpiration: Bool = true,
success: SwifTumbHttpRequest.SuccessHandler?,
failure: SwifTumbHttpRequest.FailureHandler?
) -> SwifTumbRequestHandle? {
let handle: OAuthSwiftRequestHandle? = self.client.request(
urlString,
method: self.method(method: method),
parameters: parameters,
headers: headers,
body:body,
checkTokenExpiration: checkTokenExpiration,
success: { (response: OAuthSwiftResponse) in
if success != nil {
// print("response data:", String(data: response.data, encoding: .utf8))
let resp = try! SwifTumbResponseMapper.Response(
data: response.data
)
success!(resp)
}
},
failure: { (err: OAuthSwiftError) in
if failure != nil {
failure!(OAuthSwiftAdapterError(err.description))
}
}
)
return OAuthSwiftAdapterRequestHandle(handle: handle)
}
private func method(method: SwifTumbHttpRequest.Method) -> OAuthSwiftHTTPRequest.Method {
switch method {
case SwifTumbHttpRequest.Method.GET:
return OAuthSwiftHTTPRequest.Method.GET
case SwifTumbHttpRequest.Method.POST:
return OAuthSwiftHTTPRequest.Method.POST
case SwifTumbHttpRequest.Method.PUT:
return OAuthSwiftHTTPRequest.Method.PUT
case SwifTumbHttpRequest.Method.DELETE:
return OAuthSwiftHTTPRequest.Method.DELETE
case SwifTumbHttpRequest.Method.PATCH:
return OAuthSwiftHTTPRequest.Method.PATCH
case SwifTumbHttpRequest.Method.HEAD:
return OAuthSwiftHTTPRequest.Method.HEAD
}
}
}
open class OAuthSwiftAdapterError: SwifTumbError {
private var rawMessage: String
init(_ message: String) {
self.rawMessage = message
}
open func message() -> String {
return self.rawMessage
}
}
open class OAuthSwiftAdapterRequestHandle: SwifTumbRequestHandle {
var handle: OAuthSwiftRequestHandle
init? (handle: OAuthSwiftRequestHandle?) {
if handle == nil {
return nil
}
self.handle = handle!
}
open func cancel() {
self.handle.cancel()
}
}
|
4eb2fcff251a89214351e935eb3758c0
| 29.213115 | 93 | 0.595225 | false | false | false | false |
claudetech/cordova-plugin-media-lister
|
refs/heads/master
|
src/ios/MediaLister.swift
|
mit
|
1
|
import Foundation
import AssetsLibrary
import MobileCoreServices
// TODO: Rewrite in ObjC or Photo
@objc(HWPMediaLister) public class MediaLister: CDVPlugin{
let library = ALAssetsLibrary()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
var command: CDVInvokedUrlCommand!
var option: [String: AnyObject] = [:]
var result:[[String: AnyObject]] = []
var success: Bool!
public func readLibrary(command: CDVInvokedUrlCommand){
dispatch_async(dispatch_get_global_queue(priority, 0)){
self.result = []
self.command = command
let temp = command.arguments[0] as! [String: AnyObject]
self.option = self.initailizeOption(temp)
self.loadMedia(self.option)
}
}
public func startLoad(thumbnail: Bool = true, limit: Int = 20, mediaTypes: [String] = ["image"], offset:Int = 0) -> [[String: AnyObject]]{
option = ["thumbnail": thumbnail, "limit":limit , "mediaTypes": mediaTypes, "offset": offset]
loadMedia(option)
return result
}
private func initailizeOption(option:[String: AnyObject]) -> [String: AnyObject]{
var tempOption = option
if tempOption["offset"] == nil{
tempOption["offset"] = 0
}
if tempOption["limit"] == nil{
tempOption["limit"] = 20
}
if tempOption["thumbnail"] == nil{
tempOption["thumbnail"] = true
}
if tempOption["mediaTypes"] == nil{
tempOption["mdeiaTypes"] = ["image"]
}
return tempOption
}
private func sendResult(){
dispatch_async(dispatch_get_main_queue()){
var pluginResult: CDVPluginResult! = nil
if self.success == true {
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsArray: self.result)
} else {
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR)
}
self.commandDelegate?.sendPluginResult(pluginResult, callbackId: self.command.callbackId)
}
}
private func loadMedia(option: [String: AnyObject]){
success = false
library.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos,usingBlock: {
(group: ALAssetsGroup!, stop: UnsafeMutablePointer) in
if group == nil{
return
}
self.success = true
if let filter = self.getFilter(option["mediaTypes"] as! [String]){
group.setAssetsFilter(filter)
} else {
return
}
let num = group.numberOfAssets()
let indexSet = self.getIndexSet(num, limit: option["limit"] as! Int, offset: option["offset"] as! Int)
if indexSet == nil{
return
}
group.enumerateAssetsAtIndexes(indexSet!, options: NSEnumerationOptions.Reverse){
(asset:ALAsset!, id:Int , stop: UnsafeMutablePointer) in
if asset != nil{
self.result.append(self.setDictionary(asset, id: id, option:option))
}
}
self.sendResult()
}, failureBlock:{
(myerror: NSError!) -> Void in
print("error occurred: \(myerror.localizedDescription)")
}
)
}
// TODO: Add data of Location etc.
private func setDictionary(asset: ALAsset, id: Int, option: [String: AnyObject]) -> [String: AnyObject]{
var data: [String: AnyObject] = [:]
data["id"] = id
data["mediaType"] = setType(asset)
let date: NSDate = asset.valueForProperty(ALAssetPropertyDate) as! NSDate
data["dateAdded"] = date.timeIntervalSince1970
data["path"] = asset.valueForProperty(ALAssetPropertyAssetURL).absoluteString
let rep = asset.defaultRepresentation()
data["size"] = Int(rep.size())
data["orientation"] = rep.metadata()["Orientation"]
data["title"] = rep.filename()
data["height"] = rep.dimensions().height
data["wigth"] = rep.dimensions().width
data["mimeType"] = UTTypeCopyPreferredTagWithClass(rep.UTI(), kUTTagClassMIMEType)!.takeUnretainedValue()
if (option["thumbnail"] as! Bool) {
data["thumbnailPath"] = saveThumbnail(asset, id: id)
}
return data
}
private func saveThumbnail(asset: ALAsset, id: Int) -> NSString{
let thumbnail = asset.thumbnail().takeUnretainedValue()
let image = UIImage(CGImage: thumbnail)
let imageData = UIImageJPEGRepresentation(image, 0.8)
let cacheDirPath: NSString = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] as NSString
let filePath = cacheDirPath.stringByAppendingPathComponent("\(id).jpeg")
if imageData!.writeToFile(filePath, atomically: true){
return filePath
} else {
print("error occured: Cannot save thumbnail image")
return ""
}
}
private func setType(asset:ALAsset) -> String{
let type = asset.valueForProperty(ALAssetPropertyType) as! String
if type == ALAssetTypePhoto{
return "image"
} else if type == ALAssetTypeVideo {
return "video"
}
return ""
}
// TODO: Add music and playlist and audio
private func getFilter(mediaTypes: [String]) -> ALAssetsFilter?{
if mediaTypes.contains("image"){
if mediaTypes.contains("video"){
return ALAssetsFilter.allAssets()
} else {
return ALAssetsFilter.allPhotos()
}
} else if mediaTypes.contains("video"){
return ALAssetsFilter.allVideos()
}
return nil
}
private func getIndexSet(max: Int, limit:Int, offset: Int) -> NSIndexSet?{
if offset >= max{
return nil
} else if offset + limit > max{
return NSIndexSet(indexesInRange: NSMakeRange(0, max - offset))
} else {
return NSIndexSet(indexesInRange: NSMakeRange(max - offset - limit, limit))
}
}
}
|
6ea9ac8842d7ff444e6117b9f7b2a270
| 36.710059 | 142 | 0.574074 | false | false | false | false |
peferron/algo
|
refs/heads/master
|
EPI/Strings/Convert from Roman to decimal/swift/main.swift
|
mit
|
1
|
let romanValues: [Character: Int] = [
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1,
]
public func toInt(roman: String) -> Int {
var max = 0
var sum = 0
for character in roman.reversed() {
let value = romanValues[character]!
if value < max {
sum -= value
} else {
sum += value
max = value
}
}
return sum
// Alternative below, that takes 25s to compile with Swift 3.1. Can be made faster by splitting
// the chain into pieces, but hopefully it'll be fixed in a future version of the compiler.
// return roman
// .reversed()
// .map { romanValues[$0]! }
// .reduce((sum: 0, max: 0)) { (acc, value) in
// value < acc.max ? (acc.sum - value, acc.max) : (acc.sum + value, value)
// }
// .sum
}
|
0b93ac4b1ba27050bba9763152ee467b
| 23.75 | 99 | 0.497194 | false | false | false | false |
Johnykutty/SwiftLint
|
refs/heads/master
|
Source/SwiftLintFramework/Rules/LegacyConstantRuleExamples.swift
|
mit
|
2
|
//
// LegacyConstantRuleExamples.swift
// SwiftLint
//
// Created by Aaron McTavish on 01/16/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
internal struct LegacyConstantRuleExamples {
static let swift2NonTriggeringExamples = commonNonTriggeringExamples
static let swift3NonTriggeringExamples = commonNonTriggeringExamples + ["CGFloat.pi", "Float.pi"]
static let swift2TriggeringExamples = commonTriggeringExamples
static let swift3TriggeringExamples = commonTriggeringExamples + ["↓CGFloat(M_PI)", "↓Float(M_PI)"]
static let swift2Corrections = commonCorrections
static let swift3Corrections: [String: String] = {
var corrections = commonCorrections
["↓CGFloat(M_PI)": "CGFloat.pi",
"↓Float(M_PI)": "Float.pi",
"↓CGFloat(M_PI)\n↓Float(M_PI)\n": "CGFloat.pi\nFloat.pi\n"].forEach { key, value in
corrections[key] = value
}
return corrections
}()
static let swift2Patterns = commonPatterns
static let swift3Patterns: [String: String] = {
var patterns = commonPatterns
["CGFloat\\(M_PI\\)": "CGFloat.pi",
"Float\\(M_PI\\)": "Float.pi"].forEach { key, value in
patterns[key] = value
}
return patterns
}()
private static let commonNonTriggeringExamples = [
"CGRect.infinite",
"CGPoint.zero",
"CGRect.zero",
"CGSize.zero",
"NSPoint.zero",
"NSRect.zero",
"NSSize.zero",
"CGRect.null"
]
private static let commonTriggeringExamples = [
"↓CGRectInfinite",
"↓CGPointZero",
"↓CGRectZero",
"↓CGSizeZero",
"↓NSZeroPoint",
"↓NSZeroRect",
"↓NSZeroSize",
"↓CGRectNull"
]
private static let commonCorrections = [
"↓CGRectInfinite": "CGRect.infinite",
"↓CGPointZero": "CGPoint.zero",
"↓CGRectZero": "CGRect.zero",
"↓CGSizeZero": "CGSize.zero",
"↓NSZeroPoint": "NSPoint.zero",
"↓NSZeroRect": "NSRect.zero",
"↓NSZeroSize": "NSSize.zero",
"↓CGRectNull": "CGRect.null",
"↓CGRectInfinite\n↓CGRectNull\n": "CGRect.infinite\nCGRect.null\n"
]
private static let commonPatterns = [
"CGRectInfinite": "CGRect.infinite",
"CGPointZero": "CGPoint.zero",
"CGRectZero": "CGRect.zero",
"CGSizeZero": "CGSize.zero",
"NSZeroPoint": "NSPoint.zero",
"NSZeroRect": "NSRect.zero",
"NSZeroSize": "NSSize.zero",
"CGRectNull": "CGRect.null"
]
}
|
a1561f5c368430acffdd27a70aa3c44c
| 28.191011 | 103 | 0.602002 | false | false | false | false |
nevyn/SPAsync
|
refs/heads/master
|
Swift/Task.swift
|
mit
|
1
|
//
// Task.swift
// SPAsync
//
// Created by Joachim Bengtsson on 2014-08-14.
// Copyright (c) 2014 ThirdCog. All rights reserved.
//
import Foundation
public class Task<T> : Cancellable, Equatable
{
// MARK: Public interface: Callbacks
public func addCallback(callback: (T -> Void)) -> Self
{
return addCallback(on:dispatch_get_main_queue(), callback: callback)
}
public func addCallback(on queue: dispatch_queue_t, callback: (T -> Void)) -> Self
{
synchronized(self.callbackLock) {
if self.isCompleted {
if self.completedError == nil {
dispatch_async(queue) {
callback(self.completedValue!)
}
}
} else {
self.callbacks.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
public func addErrorCallback(callback: (NSError! -> Void)) -> Self
{
return addErrorCallback(on:dispatch_get_main_queue(), callback:callback)
}
public func addErrorCallback(on queue: dispatch_queue_t, callback: (NSError! -> Void)) -> Self
{
synchronized(self.callbackLock) {
if self.isCompleted {
if self.completedError != nil {
dispatch_async(queue) {
callback(self.completedError!)
}
}
} else {
self.errbacks.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
public func addFinallyCallback(callback: (Bool -> Void)) -> Self
{
return addFinallyCallback(on:dispatch_get_main_queue(), callback:callback)
}
public func addFinallyCallback(on queue: dispatch_queue_t, callback: (Bool -> Void)) -> Self
{
synchronized(self.callbackLock) {
if(self.isCompleted) {
dispatch_async(queue, { () -> Void in
callback(self.isCancelled)
})
} else {
self.finallys.append(TaskCallbackHolder(on: queue, callback: callback))
}
}
return self
}
// MARK: Public interface: Advanced callbacks
public func then<T2>(worker: (T -> T2)) -> Task<T2>
{
return then(on:dispatch_get_main_queue(), worker: worker)
}
public func then<T2>(on queue:dispatch_queue_t, worker: (T -> T2)) -> Task<T2>
{
let source = TaskCompletionSource<T2>();
let then = source.task;
self.childTasks.append(then)
self.addCallback(on: queue, callback: { (value: T) -> Void in
let result = worker(value)
source.completeWithValue(result)
})
self.addErrorCallback(on: queue, callback: { (error: NSError!) -> Void in
source.failWithError(error)
})
return then
}
public func then<T2>(chainer: (T -> Task<T2>)) -> Task<T2>
{
return then(on:dispatch_get_main_queue(), chainer: chainer)
}
public func then<T2>(on queue:dispatch_queue_t, chainer: (T -> Task<T2>)) -> Task<T2>
{
let source = TaskCompletionSource<T2>();
let chain = source.task;
self.childTasks.append(chain)
self.addCallback(on: queue, callback: { (value: T) -> Void in
let workToBeProvided : Task<T2> = chainer(value)
chain.childTasks.append(workToBeProvided)
source.completeWithTask(workToBeProvided)
})
self.addErrorCallback(on: queue, callback: { (error: NSError!) -> Void in
source.failWithError(error)
})
return chain;
}
/// Transforms Task<Task<T2>> into a Task<T2> asynchronously
// dunno how to do this with static typing...
/*public func chain<T2>() -> Task<T2>
{
return self.then<T.T>({(value: Task<T2>) -> T2 in
return value
})
}*/
// MARK: Public interface: Cancellation
public func cancel()
{
var shouldCancel = false
synchronized(callbackLock) { () -> Void in
shouldCancel = !self.isCancelled
self.isCancelled = true
}
if shouldCancel {
self.source!.cancel()
// break any circular references between source<> task by removing
// callbacks and errbacks which might reference the source
synchronized(callbackLock) {
self.callbacks.removeAll()
self.errbacks.removeAll()
for holder in self.finallys {
dispatch_async(holder.callbackQueue, { () -> Void in
holder.callback(true)
})
}
self.finallys.removeAll()
}
}
for child in childTasks {
child.cancel()
}
}
public private(set) var isCancelled = false
// MARK: Public interface: construction
class func performWork(on queue:dispatch_queue_t, work: Void -> T) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_async(queue) {
let value = work()
source.completeWithValue(value)
}
return source.task
}
class func fetchWork(on queue:dispatch_queue_t, work: Void -> Task<T>) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_async(queue) {
let value = work()
source.completeWithTask(value)
}
return source.task
}
class func delay(interval: NSTimeInterval, value : T) -> Task<T>
{
let source = TaskCompletionSource<T>()
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
source.completeWithValue(value)
}
return source.task
}
class func completedTask(value: T) -> Task<T>
{
let source = TaskCompletionSource<T>()
source.completeWithValue(value)
return source.task
}
class func failedTask(error: NSError!) -> Task<T>
{
let source = TaskCompletionSource<T>()
source.failWithError(error)
return source.task
}
// MARK: Public interface: other convenience
class func awaitAll(tasks: [Task]) -> Task<[Any]>
{
let source = TaskCompletionSource<[Any]>()
if tasks.count == 0 {
source.completeWithValue([])
return source.task;
}
var values : [Any] = []
var remainingTasks : [Task] = tasks
var i : Int = 0
for task in tasks {
source.task.childTasks.append(task)
weak var weakTask = task
values.append(NSNull())
task.addCallback(on: dispatch_get_main_queue(), callback: { (value: Any) -> Void in
values[i] = value
remainingTasks.removeAtIndex(find(remainingTasks, weakTask!)!)
if remainingTasks.count == 0 {
source.completeWithValue(values)
}
}).addErrorCallback(on: dispatch_get_main_queue(), callback: { (error: NSError!) -> Void in
if remainingTasks.count == 0 {
// ?? how could this happen?
return
}
remainingTasks.removeAtIndex(find(remainingTasks, weakTask!)!)
source.failWithError(error)
for task in remainingTasks {
task.cancel()
}
remainingTasks.removeAll()
values.removeAll()
}).addFinallyCallback(on: dispatch_get_main_queue(), callback: { (canceled: Bool) -> Void in
if canceled {
source.task.cancel()
}
})
i++;
}
return source.task;
}
// MARK: Private implementation
var callbacks : [TaskCallbackHolder<T -> Void>] = []
var errbacks : [TaskCallbackHolder<NSError! -> Void>] = []
var finallys : [TaskCallbackHolder<Bool -> Void>] = []
var callbackLock : NSLock = NSLock()
var isCompleted = false
var completedValue : T? = nil
var completedError : NSError? = nil
weak var source : TaskCompletionSource<T>?
var childTasks : [Cancellable] = []
internal init()
{
// temp
}
internal init(source: TaskCompletionSource<T>)
{
self.source = source
}
func completeWithValue(value: T)
{
assert(self.isCompleted == false, "Can't complete a task twice")
if self.isCompleted {
return
}
if self.isCancelled {
return
}
synchronized(callbackLock) {
self.isCompleted = true
self.completedValue = value
let copiedCallbacks = self.callbacks
let copiedFinallys = self.finallys
for holder in copiedCallbacks {
dispatch_async(holder.callbackQueue) {
if !self.isCancelled {
holder.callback(value)
}
}
}
for holder in copiedFinallys {
dispatch_async(holder.callbackQueue) {
holder.callback(self.isCancelled)
}
}
self.callbacks.removeAll()
self.errbacks.removeAll()
self.finallys.removeAll()
}
}
func failWithError(error: NSError!)
{
assert(self.isCompleted == false, "Can't complete a task twice")
if self.isCompleted {
return
}
if self.isCancelled {
return
}
synchronized(callbackLock) {
self.isCompleted = true
self.completedError = error
let copiedErrbacks = self.errbacks
let copiedFinallys = self.finallys
for holder in copiedErrbacks {
dispatch_async(holder.callbackQueue) {
if !self.isCancelled {
holder.callback(error)
}
}
}
for holder in copiedFinallys {
dispatch_async(holder.callbackQueue) {
holder.callback(self.isCancelled)
}
}
self.callbacks.removeAll()
self.errbacks.removeAll()
self.finallys.removeAll()
}
}
}
public func ==<T>(lhs: Task<T>, rhs: Task<T>) -> Bool
{
return lhs === rhs
}
// MARK:
public class TaskCompletionSource<T> : NSObject {
public override init()
{
}
public let task = Task<T>()
private var cancellationHandlers : [(() -> Void)] = []
/** Signal successful completion of the task to all callbacks */
public func completeWithValue(value: T)
{
self.task.completeWithValue(value)
}
/** Signal failed completion of the task to all errbacks */
public func failWithError(error: NSError!)
{
self.task.failWithError(error)
}
/** Signal completion for this source's task based on another task. */
public func completeWithTask(task: Task<T>)
{
task.addCallback(on:dispatch_get_global_queue(0, 0), callback: {
(v: T) -> Void in
self.task.completeWithValue(v)
}).addErrorCallback(on:dispatch_get_global_queue(0, 0), callback: {
(e: NSError!) -> Void in
self.task.failWithError(e)
})
}
/** If the task is cancelled, your registered handlers will be called. If you'd rather
poll, you can ask task.cancelled. */
public func onCancellation(callback: () -> Void)
{
synchronized(self) {
self.cancellationHandlers.append(callback)
}
}
func cancel() {
var handlers: [()->()] = []
synchronized(self) { () -> Void in
handlers = self.cancellationHandlers
}
for callback in handlers {
callback()
}
}
}
protocol Cancellable {
func cancel() -> Void
}
class TaskCallbackHolder<T>
{
init(on queue:dispatch_queue_t, callback: T) {
callbackQueue = queue
self.callback = callback
}
var callbackQueue : dispatch_queue_t
var callback : T
}
func synchronized(on: AnyObject, closure: () -> Void) {
objc_sync_enter(on)
closure()
objc_sync_exit(on)
}
func synchronized(on: NSLock, closure: () -> Void) {
on.lock()
closure()
on.unlock()
}
func synchronized<T>(on: NSLock, closure: () -> T) -> T {
on.lock()
let r = closure()
on.unlock()
return r
}
|
1f24475013928f12040ac855ac14da7c
| 22.068282 | 133 | 0.664343 | false | false | false | false |
tellowkrinkle/Sword
|
refs/heads/master
|
Sources/Sword/Gateway/GatewayHandler.swift
|
mit
|
1
|
//
// GatewayHandler.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2017 Alejandro Alonso. All rights reserved.
//
import Foundation
/// Gateway Handler
extension Shard {
/**
Handles all gateway events (except op: 0)
- parameter payload: Payload sent with event
*/
func handleGateway(_ payload: Payload) {
guard let op = OP(rawValue: payload.op) else {
self.sword.log("Received unknown gateway\nOP: \(payload.op)\nData: \(payload.d)")
return
}
switch op {
/// OP: 1
case .heartbeat:
let heartbeat = Payload(
op: .heartbeat,
data: self.lastSeq ?? NSNull()
).encode()
self.send(heartbeat)
/// OP: 11
case .heartbeatACK:
self.heartbeat?.received = true
/// OP: 10
case .hello:
self.heartbeat = Heartbeat(self.session!, "heartbeat.shard.\(self.id)", interval: (payload.d as! [String: Any])["heartbeat_interval"] as! Int)
self.heartbeat?.received = true
self.heartbeat?.send()
guard !self.isReconnecting else {
self.isReconnecting = false
var data: [String: Any] = ["token": self.sword.token, "session_id": self.sessionId!, "seq": NSNull()]
if let lastSeq = self.lastSeq {
data["seq"] = lastSeq
}
let payload = Payload(
op: .resume,
data: data
).encode()
self.send(payload)
return
}
self.identify()
/// OP: 9
case .invalidSession:
self.isReconnecting = false
self.reconnect()
/// OP: 7
case .reconnect:
self.isReconnecting = true
self.reconnect()
/// Others~~~
default:
break
}
}
}
|
9a9d3f862fc866cd1ddad12017ea8834
| 20.170732 | 148 | 0.567396 | false | false | false | false |
JamieScanlon/AugmentKit
|
refs/heads/master
|
AugmentKit/AKCore/Anchors/AugmentedSurfaceAnchor.swift
|
mit
|
1
|
//
// AugmentedSurfaceAnchor.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 ARKit
import Foundation
import MetalKit
import simd
/**
A generic implementation of `AKAugmentedSurfaceAnchor` that renders a `MDLTexture` on a simple plane with a given extent
*/
open class AugmentedSurfaceAnchor: AKAugmentedSurfaceAnchor {
/**
A type string. Always returns "AugmentedSurface"
*/
public static var type: String {
return "AugmentedSurface"
}
/**
The location in the ARWorld
*/
public var worldLocation: AKWorldLocation
/**
The heading in the ARWorld. Defaults to `NorthHeading()`
*/
public var heading: AKHeading = NorthHeading()
/**
The `MDLAsset` associated with the entity.
*/
public var asset: MDLAsset
/**
A unique, per-instance identifier
*/
public var identifier: UUID?
/**
An array of `AKEffect` objects that are applied by the renderer
*/
public var effects: [AnyEffect<Any>]?
/**
Specified a perfered renderer to use when rendering this enitity. Most will use the standard PBR renderer but some entities may prefer a simpiler renderer when they are not trying to achieve the look of real-world objects. Defaults to `ShaderPreference.pbr`
*/
public var shaderPreference: ShaderPreference = .pbr
/**
Indicates whether this geometry participates in the generation of augmented shadows. Since this is an augmented geometry, it does generate shadows.
*/
public var generatesShadows: Bool = true
/**
If `true`, the current base color texture of the entity has changed since the last time it was rendered and the pixel data needs to be updated. This flag can be used to achieve dynamically updated textures for rendered objects.
*/
public var needsColorTextureUpdate: Bool = false
/// If `true` the underlying mesh for this geometry has changed and the renderer needs to update. This can be used to achieve dynamically generated geometries that change over time.
public var needsMeshUpdate: Bool = false
/**
An `ARAnchor` that will be tracked in the AR world by `ARKit`
*/
public var arAnchor: ARAnchor?
/**
Initialize a new object with a `MDLTexture` and an extent representing the size at a `AKWorldLocation` and AKHeading using a `MTKMeshBufferAllocator` for allocating the geometry
- Parameters:.
- withTexture: The `MDLTexture` containing the image texture
- extent: The size of the geometry in meters
- at: The location of the anchor
- heading: The heading for the anchor
- withAllocator: A `MTKMeshBufferAllocator` with wich to create the plane geometry
*/
public init(withTexture texture: MDLTexture, extent: SIMD3<Float>, at location: AKWorldLocation, heading: AKHeading? = nil, withAllocator metalAllocator: MTKMeshBufferAllocator? = nil) {
self.texture = texture
self.extent = extent
self.metalAllocator = metalAllocator
self.asset = MDLAsset(bufferAllocator: metalAllocator)
self.worldLocation = location
if let heading = heading {
self.heading = heading
}
}
/**
Sets a new `arAnchor`
- Parameters:
- _: An `ARAnchor`
*/
public func setARAnchor(_ arAnchor: ARAnchor) {
self.arAnchor = arAnchor
if identifier == nil {
identifier = arAnchor.identifier
}
worldLocation.transform = arAnchor.transform
let mesh = MDLMesh(planeWithExtent: extent, segments: SIMD2<UInt32>(1, 1), geometryType: .triangles, allocator: metalAllocator)
let scatteringFunction = MDLScatteringFunction()
let material = MDLMaterial(name: "Default AugmentedSurfaceAnchor baseMaterial", scatteringFunction: scatteringFunction)
let textureSampler = MDLTextureSampler()
textureSampler.texture = texture
let property = MDLMaterialProperty(name: "baseColor", semantic: MDLMaterialSemantic.baseColor, textureSampler: textureSampler)
material.setProperty(property)
for submesh in mesh.submeshes! {
if let submesh = submesh as? MDLSubmesh {
submesh.material = material
}
}
asset.add(mesh)
}
// MARK: Private
private var texture: MDLTexture
private var extent: SIMD3<Float>
private var metalAllocator: MTKMeshBufferAllocator?
}
/// :nodoc:
extension AugmentedSurfaceAnchor: CustomDebugStringConvertible, CustomStringConvertible {
/// :nodoc:
public var description: String {
return debugDescription
}
/// :nodoc:
public var debugDescription: String {
let myDescription = "<AugmentedSurfaceAnchor: \(Unmanaged.passUnretained(self).toOpaque())> worldLocation: \(worldLocation), identifier:\(identifier?.uuidString ?? "None"), effects: \(effects?.debugDescription ?? "None"), arAnchor: \(arAnchor?.debugDescription ?? "None"), asset: \(asset)"
return myDescription
}
}
|
2f95df1d1aa6f3c0ccca29c58ef3feca
| 39.584416 | 297 | 0.6904 | false | false | false | false |
cdtschange/SwiftMKit
|
refs/heads/master
|
SwiftMKit/Data/Local/Cache/CachePool.swift
|
mit
|
1
|
//
// CachePool.swift
// SwiftMKitDemo
//
// Created by Mao on 4/26/16.
// Copyright © 2016 cdts. All rights reserved.
//
import Foundation
import PINCache
import CocoaLumberjack
public struct CachePoolConstant {
// 取手机剩余空间 DefaultCapacity = MIN(剩余空间, 100M)
static let DefaultCapacity: Int64 = 100*1024*1024 // 默认缓存池空间 100M
static let DefaultCachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! + "/"
static let MimeType4Image = "image"
}
@objc(CacheModel)private class CacheModel : NSObject, NSCoding, CacheModelProtocol {
var key: String = ""
var name: String = ""
var filePath: URL?
var size: Int64 = 0
var mimeType: String = ""
var createTime: TimeInterval = 0
var lastVisitTime: TimeInterval = 0
var expireTime: TimeInterval = 0
@objc func encode(with aCoder: NSCoder){
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.key, forKey: "key")
aCoder.encode(self.filePath, forKey: "filePath")
aCoder.encode(self.createTime, forKey: "createTime")
aCoder.encode(self.size, forKey: "size")
aCoder.encode(self.mimeType, forKey: "mimeType")
}
@objc required init(coder aDecoder: NSCoder) {
super.init()
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.key = aDecoder.decodeObject(forKey: "key") as! String
self.filePath = aDecoder.decodeObject(forKey: "filePath") as? URL
self.createTime = aDecoder.decodeObject(forKey: "createTime") as! TimeInterval
self.size = aDecoder.decodeInt64(forKey: "size")
self.mimeType = aDecoder.decodeObject(forKey: "mimeType") as! String
}
override init() {
super.init()
}
override var description: String {
return "\(key) \(name) \(createTime) \(size)"
}
}
/// 缓存池:用于存储文件
open class CachePool: CachePoolProtocol {
let fileManager = FileManager.default
var cache: PINCache?
open var namespace: String = "CachePool"
open var capacity: Int64 = CachePoolConstant.DefaultCapacity
open var size: Int64 {
// 遍历配置文件
// 取出缓存字典
let cachedDict = (cache?.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
var cachedSize: Int64 = 0
for value in cachedDict.values {
cachedSize += value.size
}
return cachedSize
}
open var basePath: URL?
init() {
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: namespace, baseUrl: baseCacheUrl())
}
init(namespace: String?) {
self.namespace = namespace ?? self.namespace
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: self.namespace, baseUrl: baseCacheUrl())
}
open func addCache(_ data: Data, name: String?) -> String {
return addCache(data, name: name, mimeType: nil)
}
open func addCache(_ image: UIImage, name: String?) -> String {
let data = UIImagePNGRepresentation(image)
return self.addCache(data!, name: name, mimeType: CachePoolConstant.MimeType4Image)
}
open func addCache(_ filePath: URL, name: String?) -> String {
// 拷贝文件
// 生成目标路径
let timestamp = Date().timeIntervalSince1970
let nameTime = ( name ?? "" ) + "\(timestamp)"
let encryptName = nameTime.md5
let dir = self.cachePath()
let destFilePath:String = dir + encryptName
try! fileManager.copyItem(atPath: filePath.path, toPath: destFilePath)
DDLogInfo("filePath: \(filePath.path)")
DDLogInfo("destFilePath: \(destFilePath)")
// 获取文件信息
if let attrs = self.getFileAttributes(withFilePath: destFilePath) {
DDLogInfo("file info:\(attrs)")
// 更新配置文件
let num = attrs[FileAttributeKey.size] as? NSNumber ?? 0
let size = num.int64Value
return self.updateConfig(forName: name, timestamp:timestamp, size: size)
}
// TODO: 返回值需要思考一下
return encryptName
}
open func getCache(forKey key: String) -> AnyObject? {
let dir = self.cachePath()
let filePath:String = dir + key
DDLogInfo("objectForName filePath:" + filePath)
let cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
if let obj = cachedDict[key] {
if obj.mimeType == CachePoolConstant.MimeType4Image {
if let data = fileManager.contents(atPath: filePath) {
return UIImage(data: data)
} else {
return nil
}
}
return fileManager.contents(atPath: filePath) as AnyObject?
}
return fileManager.contents(atPath: filePath) as AnyObject?
}
open func all() -> [CacheModelProtocol]? {
let cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
var cacheModelList:[CacheModelProtocol] = []
for obj in cachedDict.values {
cacheModelList.append(obj)
}
return cacheModelList
}
open func removeCache(forKey key: String) -> Bool {
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
if let obj = cachedDict[key] {
print(obj)
// 从沙河中删除
let filePathStr = cachePath() + obj.key
if fileManager.fileExists(atPath: filePathStr) {
try! fileManager.removeItem(atPath: filePathStr)
}
// 从配置文件中删除
cachedDict.removeValue(forKey: key)
cacheDict = cachedDict
return true
}
return false
}
@discardableResult
open func clear() -> Bool {
let cachepath = cachePath()
if fileManager.fileExists(atPath: cachepath) {
let fileArray:[AnyObject]? = fileManager.subpaths(atPath: cachepath) as [AnyObject]?
for fn in fileArray!{
let subpath = cachepath + "/\(fn)";
var flag: ObjCBool = false
if fileManager.fileExists(atPath: subpath, isDirectory: &flag) {
if flag.boolValue {
// 是文件夹
continue
} else {
try! fileManager.removeItem(atPath: subpath)
}
}
// if fileManager.fileExistsAtPath(subpath) {
// try! fileManager.removeItemAtPath(subpath)
// }
}
// try! fileManager.removeItemAtPath(cachepath)
// try! fileManager.createDirectoryAtPath(cachepath, withIntermediateDirectories: true, attributes: nil)
// 清空缓存配置文件
cacheDict?.removeAll()
// 重新生成配置文件
cache = PINCache(name: "Config", rootPath: cachePath())
createFolder(forName: namespace, baseUrl: baseCacheUrl())
return true
}
return size == 0
}
// 缓存相关
let cacheDictKey = "CacheModels"
fileprivate var cacheDict: Dictionary<String, CacheModel>? {
get {
return cache!.object(forKey: cacheDictKey) as? Dictionary<String, CacheModel>
}
set {
if let value = newValue {
cache!.setObject(value as NSCoding, forKey: cacheDictKey)
} else {
cache!.removeObject(forKey: cacheDictKey)
}
}
}
}
extension CachePool {
fileprivate func addCache(_ data: Data, name: String?, mimeType: String?) -> String {
// 更新配置文件
let timestamp = Date().timeIntervalSince1970
let encryptName = self.updateConfig(forName: name, timestamp:timestamp, size: Int64(data.count), mimeType: mimeType)
// 保存对象到沙盒
let dir = self.cachePath()
let filePath:String = dir + encryptName
let _ = Async.background {
if (try? data.write(to: URL(fileURLWithPath: filePath), options: [.atomic])) != nil {
DDLogDebug("文件写入成功:\(filePath)")
} else {
DDLogDebug("文件写入失败!")
}
}
return encryptName
}
/// 存储文件之前,判断是否有足够的空间存储
///
/// :param: size 即将存储的文件大小
fileprivate func preparePool(forSize size: Int64) -> Bool {
// 比较 设备剩余可用空间 & 文件大小
var leftCapacity = capacity - self.size
leftCapacity = min(UIDevice.freeDiskSpaceInBytes, leftCapacity) // 取出最小可用空间
DDLogVerbose("可用空间:\(leftCapacity), 文件大小:\(size), 正常保存")
if leftCapacity < size {
// 读取配置文件,删除已过期、即将过期、最近未访问的文件,直至可以保存为止
DDLogInfo("需要删除文件后保存")
leftCapacity = self.cleanDisk(leftCapacity: leftCapacity, size: size)
}
return size <= leftCapacity
}
/// 更新配置文件
///
/// :param: name 文件名
/// :param: size 文件大小
///
/// :returns: 加密后的文件名
fileprivate func updateConfig(forName name: String?, timestamp: TimeInterval, size: Int64) -> String {
return updateConfig(forName: name, timestamp: timestamp, size: size, mimeType: nil)
}
fileprivate func updateConfig(forName name: String?, timestamp: TimeInterval, size: Int64, mimeType: String?) -> String {
// 核心方法:判断是否有足够的空间存储
if !(self.preparePool(forSize: size)) {
return ""
}
let cacheObj = CacheModel()
// 已缓存的字典
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
let nameTime = (name ?? "") + "\(timestamp)"
let encryptName = nameTime.md5
cacheObj.name = name ?? ""
cacheObj.key = encryptName
cacheObj.createTime = timestamp
cacheObj.mimeType = (mimeType ?? "")
cacheObj.size = size
cacheObj.filePath = URL(fileURLWithPath: (cachePath() + encryptName))
cachedDict[encryptName] = cacheObj
// 同步到PINCache
cacheDict = cachedDict
return encryptName
}
/// 创建文件夹
fileprivate func createFolder(forName name: String, baseUrl: URL) {
let folder = baseUrl.appendingPathComponent(name, isDirectory: true)
let exist = fileManager.fileExists(atPath: folder.path)
if !exist {
try! fileManager.createDirectory(at: folder, withIntermediateDirectories: true, attributes: nil)
DDLogVerbose("缓存文件夹:" + folder.path)
}
}
/// 获取文件属性
///
/// :param: filePath 文件路径
fileprivate func getFileAttributes(withFilePath filePath: String) -> [FileAttributeKey: Any]? {
let attributes = try? fileManager.attributesOfItem(atPath: filePath)
return attributes
}
fileprivate func cachePath() -> String {
let baseStr = ((basePath) != nil) ? basePath!.path : CachePoolConstant.DefaultCachePath
return baseStr + "/" + namespace + "/"
}
fileprivate func baseCacheUrl() -> URL {
let baseUrl = ((basePath) != nil) ? basePath! : URL(fileURLWithPath: CachePoolConstant.DefaultCachePath)
self.basePath = baseUrl
return baseUrl
}
/// 设备剩余空间不足时,删除本地缓存文件
///
/// :param: leftCapacity 剩余空间
/// :param: size 至少需要的空间
fileprivate func cleanDisk(leftCapacity lastSize: Int64, size: Int64) -> Int64 {
var leftCapacity = lastSize
// 遍历配置文件
// 取出缓存字典
var cachedDict = (cache!.object(forKey: cacheDictKey) as? [String: CacheModel]) ?? [:]
DDLogVerbose("排序前:\(cachedDict)")
// 升序,最新的数据在最下面(目的:删除日期最小的旧数据)
let sortedList = cachedDict.sorted { $0.1.createTime < $1.1.createTime }
DDLogVerbose("=========================================================")
DDLogVerbose("排序后:\(sortedList)")
// obj 是一个元组类型
for (key, model) in sortedList {
// 从沙河中删除
let filePathStr = cachePath() + key
if fileManager.fileExists(atPath: filePathStr) {
try! fileManager.removeItem(atPath: filePathStr)
}
// 从配置文件中删除
cachedDict.removeValue(forKey: key)
cacheDict = cachedDict
// 更新剩余空间大小
leftCapacity += model.size
DDLogVerbose("remove=\(key), save=\(model.size) byte lastSize=\(leftCapacity) size=\(size)")
if leftCapacity > size {
break
}
}
return leftCapacity
}
}
|
37fb058fc99892d1a792f82f49660496
| 36.002941 | 125 | 0.585883 | false | false | false | false |
rohan-panchal/Scaffold
|
refs/heads/master
|
Scaffold/Classes/Foundation/SCAFFoundation.swift
|
mit
|
1
|
//
// SCAFFoundation.swift
// Pods
//
// Created by Rohan Panchal on 9/26/16.
//
//
import Foundation
public struct Platform {
public static var iPhone: Bool {
return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone
}
public static var iPad: Bool {
return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad
}
public static var iOS: Bool {
return TARGET_OS_IOS != 0
}
public static var TVOS: Bool {
return TARGET_OS_TV != 0
}
public static var WatchOS: Bool {
return TARGET_OS_WATCH != 0
}
public static var Simulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
}
|
5e11afb1a5fb762cbaac873c7593bc60
| 17.631579 | 70 | 0.583333 | false | false | false | false |
marcelvoss/WWDC15-Scholarship
|
refs/heads/master
|
Marcel Voss/Marcel Voss/MapViewer.swift
|
unlicense
|
1
|
//
// MapViewer.swift
// Marcel Voss
//
// Created by Marcel Voß on 18.04.15.
// Copyright (c) 2015 Marcel Voß. All rights reserved.
//
import UIKit
import MapKit
class MapViewer: UIView {
var mapView : MKMapView?
var effectView = UIVisualEffectView()
var aWindow : UIWindow?
var closeButton = UIButton()
var constraintY : NSLayoutConstraint?
init() {
super.init(frame: UIScreen.mainScreen().bounds)
aWindow = UIApplication.sharedApplication().keyWindow!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func show() {
self.setupViews()
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.effectView.alpha = 1
self.closeButton.alpha = 1
})
UIView.animateWithDuration(0.4, delay: 0.4, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in
self.constraintY!.constant = 0
self.layoutIfNeeded()
}) { (finished) -> Void in
}
}
func hide() {
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.effectView.alpha = 0
self.closeButton.alpha = 0
}) { (finished) -> Void in
self.mapView!.delegate = nil;
self.mapView!.removeFromSuperview();
self.mapView = nil;
self.effectView.removeFromSuperview()
self.removeFromSuperview()
}
UIView.animateWithDuration(0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in
self.constraintY!.constant = self.frame.size.height
self.layoutIfNeeded()
}) { (finished) -> Void in
self.mapView?.removeFromSuperview()
}
}
func setupViews () {
aWindow?.addSubview(self)
let blur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
effectView = UIVisualEffectView(effect: blur)
effectView.frame = self.frame
effectView.alpha = 0
self.addSubview(effectView)
closeButton.alpha = 0
closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
closeButton.addTarget(self, action: "hide", forControlEvents: UIControlEvents.TouchUpInside)
closeButton.setImage(UIImage(named: "CloseIcon"), forState: UIControlState.Normal)
self.addSubview(closeButton)
self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -20))
self.addConstraint(NSLayoutConstraint(item: closeButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 20))
// Map
mapView?.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(mapView!)
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
constraintY = NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: self.frame.size.height)
self.addConstraint(constraintY!)
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
self.addConstraint(NSLayoutConstraint(item: mapView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
var tap = UITapGestureRecognizer(target: self, action: "hide")
effectView.addGestureRecognizer(tap)
self.layoutIfNeeded()
}
}
|
96c463a1ff2818953cbc099f818cb438
| 39.67619 | 232 | 0.65137 | false | false | false | false |
codeservis/UICollectionviewsample
|
refs/heads/master
|
MultiDirectionCollectionView/CustomCollectionViewLayout.swift
|
gpl-3.0
|
1
|
//
// CustomCollectionViewLayout.swift
// MultiDirectionCollectionView
//
// Created by Kyle Andrews on 4/20/15.
// Copyright (c) 2015 Credera. All rights reserved.
//
import UIKit
class CustomCollectionViewLayout: UICollectionViewLayout {
// Used for calculating each cells CGRect on screen.
// CGRect will define the Origin and Size of the cell.
let CELL_HEIGHT = 40.0
let CELL_WIDTH = 120.0
let STATUS_BAR = UIApplication.sharedApplication().statusBarFrame.height
// Dictionary to hold the UICollectionViewLayoutAttributes for
// each cell. The layout attribtues will define the cell's size
// and position (x, y, and z index). I have found this process
// to be one of the heavier parts of the layout. I recommend
// holding onto this data after it has been calculated in either
// a dictionary or data store of some kind for a smooth performance.
var cellAttrsDictionary = Dictionary<NSIndexPath, UICollectionViewLayoutAttributes>()
// Defines the size of the area the user can move around in
// within the collection view.
var contentSize = CGSize.zero
// Used to determine if a data source update has occured.
// Note: The data source would be responsible for updating
// this value if an update was performed.
var dataSourceDidUpdate = true
override func collectionViewContentSize() -> CGSize {
return self.contentSize
}
override func prepareLayout() {
// Only update header cells.
if !dataSourceDidUpdate {
// Determine current content offsets.
let xOffset = collectionView!.contentOffset.x
let yOffset = collectionView!.contentOffset.y
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Confirm the section has items.
if collectionView?.numberOfItemsInSection(section) > 0 {
// Update all items in the first row.
if section == 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: item, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
// Also update x-position for corner cell.
if item == 0 {
frame.origin.x = xOffset
}
frame.origin.y = yOffset
attrs.frame = frame
}
}
// For all other sections, we only need to update
// the x-position for the fist item.
} else {
// Build indexPath to get attributes from dictionary.
let indexPath = NSIndexPath(forItem: 0, inSection: section)
// Update y-position to follow user.
if let attrs = cellAttrsDictionary[indexPath] {
var frame = attrs.frame
frame.origin.x = xOffset
attrs.frame = frame
}
}
}
}
}
// Do not run attribute generation code
// unless data source has been updated.
return
}
// Acknowledge data source change, and disable for next time.
dataSourceDidUpdate = false
// Cycle through each section of the data source.
if collectionView?.numberOfSections() > 0 {
for section in 0...collectionView!.numberOfSections()-1 {
// Cycle through each item in the section.
if collectionView?.numberOfItemsInSection(section) > 0 {
for item in 0...collectionView!.numberOfItemsInSection(section)-1 {
// Build the UICollectionVieLayoutAttributes for the cell.
let cellIndex = NSIndexPath(forItem: item, inSection: section)
let xPos = Double(item) * CELL_WIDTH
let yPos = Double(section) * CELL_HEIGHT
let cellAttributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: cellIndex)
cellAttributes.frame = CGRect(x: xPos, y: yPos, width: CELL_WIDTH, height: CELL_HEIGHT)
// Determine zIndex based on cell type.
if section == 0 && item == 0 {
cellAttributes.zIndex = 4
} else if section == 0 {
cellAttributes.zIndex = 3
} else if item == 0 {
cellAttributes.zIndex = 2
} else {
cellAttributes.zIndex = 1
}
// Save the attributes.
cellAttrsDictionary[cellIndex] = cellAttributes
}
}
}
}
// Update content size.
let contentWidth = Double(collectionView!.numberOfItemsInSection(0)) * CELL_WIDTH
let contentHeight = Double(collectionView!.numberOfSections()) * CELL_HEIGHT
self.contentSize = CGSize(width: contentWidth, height: contentHeight)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// Create an array to hold all elements found in our current view.
var attributesInRect = [UICollectionViewLayoutAttributes]()
// Check each element to see if it should be returned.
for cellAttributes in cellAttrsDictionary.values.elements {
if CGRectIntersectsRect(rect, cellAttributes.frame) {
attributesInRect.append(cellAttributes)
}
}
// Return list of elements.
return attributesInRect
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return cellAttrsDictionary[indexPath]!
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
|
6297023d18ca18988cfbf5db562d51eb
| 41.386364 | 115 | 0.497319 | false | false | false | false |
DrabWeb/Akedo
|
refs/heads/master
|
Akedo/Akedo/Objects/AKPomf.swift
|
gpl-3.0
|
1
|
//
// AKPomf.swift
// Akedo
//
// Created by Seth on 2016-09-04.
//
import Cocoa
import Alamofire
import SwiftyJSON
/// Represents a pomf clone the user can upload to
class AKPomf: NSObject {
// MARK: - Properties
/// The name of this pomf clone
var name : String = "";
/// The URL to this pomf clone(E.g. https://mixtape.moe/)
var url : String = "";
/// The max file size for uploading(in MB)
var maxFileSize : Int = 0;
/// For some pomf hosts they use a subdomain for uploaded files(E.g. pomf.cat, uses a.pomf.cat for uploads), this variable is the "a." in that example, optional
var uploadUrlPrefix : String = "";
// MARK: - Functions
/// Uploads the file(s) at the given path(s) to this pomf clone and calls the completion handler with the URL(s), and if the upload was successful
/// Uploads the given files to this pomf host
///
/// - Parameters:
/// - filePaths: The paths of the files to upload
/// - completionHandler: The completion handler for when the operation finishes, passed the URLs of the uploaded files and if it the upload was successful
func upload(files : [String], completionHandler : @escaping ((([String], Bool)) -> ())) {
/// The URLs to the uploaded files
var urls : [String] = [];
/// Was the upload successful?
var successful : Bool = false;
print("AKPomf: Uploading \"\(files)\" to \(self.name)(\(self.url + "upload.php"))");
// Make the upload request
Alamofire.upload(
multipartFormData: { multipartFormData in
// For every file to upload...
for(_, currentFilePath) in files.enumerated() {
// Append the current file path to the `files[]` multipart data
multipartFormData.append(URL(fileURLWithPath: currentFilePath), withName: "files[]");
}
},
to: self.url + "upload.php",
encodingCompletion: { encodingResult in
switch encodingResult {
// If the encode was a success...
case .success(let upload, _, _):
upload.responseJSON { (responseData) -> Void in
/// The string of JSON that will be returned when the POST request finishes
let responseJsonString : NSString = NSString(data: responseData.data!, encoding: String.Encoding.utf8.rawValue)!;
// If the the response data isnt nil...
if let dataFromResponseJsonString = responseJsonString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) {
/// The JSON from the response string
let responseJson = JSON(data: dataFromResponseJsonString);
// For every uploaded file...
for(_, currentFileData) in responseJson["files"] {
/// The current file URL
var currentUrl : String = currentFileData["url"].stringValue.replacingOccurrences(of: "\\", with: "");
// If the URL doesnt have a ://...
if(!currentUrl.contains("://")) {
// Fix up the URL
/// The prefix of this pomf clones URL(Either http:// or https://)
let urlPrefix : String = (self.url.substring(to: self.url.range(of: "://")!.lowerBound)) + "://";
// Set currentUrl to `urlPrefix + uploadUrlPrefix + self.url` without `prefix + currentUrl`
currentUrl = urlPrefix + (self.uploadUrlPrefix + self.url.replacingOccurrences(of: urlPrefix, with: "")) + currentUrl;
}
// Add the current file's URL to `urls`
urls.append(currentUrl);
}
// Set `successful`
successful = responseJson["success"].boolValue;
// Call the completion handler
completionHandler((urls, successful));
}
}
// If the encode was a failure...
case .failure(let encodingError):
print("AKPomf(\(self.name)): Error encoding \"\(files)\", \(encodingError)");
// Post the notification saying the file failed to encode
/// The notification to say the file encoding failed
let fileEncodingFailedNotification : NSUserNotification = NSUserNotification();
// Setup the notification
fileEncodingFailedNotification.title = "Akedo";
fileEncodingFailedNotification.informativeText = "Failed to encode \(files.count) file\((files.count == 1) ? "" : "s") for \(self.name)";
// Deliver the notification
NSUserNotificationCenter.default.deliver(fileEncodingFailedNotification);
}
}
)
}
// Init with a name, URL and max file size
init(name: String, url : String, maxFileSize : Int) {
self.name = name;
self.url = url;
self.maxFileSize = maxFileSize;
}
// Init with a name, URL, max file size and URL prefix
init(name: String, url : String, maxFileSize : Int, uploadUrlPrefix : String) {
self.name = name;
self.url = url;
self.maxFileSize = maxFileSize;
self.uploadUrlPrefix = uploadUrlPrefix;
}
}
|
55e66d5fbd7cbd8db268048156d5dfda
| 47.906977 | 164 | 0.492788 | false | false | false | false |
ludagoo/Perfect
|
refs/heads/master
|
PerfectLib/WebSocketHandler.swift
|
agpl-3.0
|
2
|
//
// WebSocketHandler.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-01-06.
// Copyright © 2016 PerfectlySoft. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version, as supplemented by the
// Perfect Additional Terms.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License, as supplemented by the
// Perfect Additional Terms, for more details.
//
// You should have received a copy of the GNU Affero General Public License
// and the Perfect Additional Terms that immediately follow the terms and
// conditions of the GNU Affero General Public License along with this
// program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>.
//
#if os(Linux)
import SwiftGlibc
import LinuxBridge
private let UINT16_MAX = UInt(0xFFFF)
#endif
private let smallPayloadSize = 126
/// This class represents the communications channel for a WebSocket session.
public class WebSocket {
/// The various types of WebSocket messages.
public enum OpcodeType: UInt8 {
case Continuation = 0x0, Text = 0x1, Binary = 0x2, Close = 0x8, Ping = 0x9, Pong = 0xA, Invalid
}
private struct Frame {
let fin: Bool
let rsv1: Bool
let rsv2: Bool
let rsv3: Bool
let opCode: OpcodeType
let bytesPayload: [UInt8]
var stringPayload: String? {
return UTF8Encoding.encode(self.bytesPayload)
}
}
private let connection: WebConnection
/// The read timeout, in seconds. By default this is -1, which means no timeout.
public var readTimeoutSeconds: Double = -1.0
private var socket: NetTCP { return self.connection.connection }
/// Indicates if the socket is still likely connected or if it has been closed.
public var isConnected: Bool { return self.socket.fd.isValid }
private var nextIsContinuation = false
private let readBuffer = Bytes()
init(connection: WebConnection) {
self.connection = connection
}
/// Close the connection.
public func close() {
if self.socket.fd.isValid {
self.sendMessage(.Close, bytes: [UInt8](), final: true) {
self.socket.close()
}
}
}
private func clearFrame() {
let position = self.readBuffer.position
self.readBuffer.data.removeFirst(position)
self.readBuffer.position = 0
}
private func fillFrame() -> Frame? {
guard self.readBuffer.availableExportBytes >= 2 else {
return nil
}
// we know we potentially have a valid frame here
// for to be resetting the position if we don't have a valid frame yet
let oldPosition = self.readBuffer.position
let byte1 = self.readBuffer.export8Bits()
let byte2 = self.readBuffer.export8Bits()
let fin = (byte1 & 0x80) != 0
let rsv1 = (byte1 & 0x40) != 0
let rsv2 = (byte1 & 0x20) != 0
let rsv3 = (byte1 & 0x10) != 0
let opcode = OpcodeType(rawValue: byte1 & 0xF) ?? .Invalid
let maskBit = (byte2 & 0x80) != 0
guard maskBit else {
self.close()
return nil
}
var unmaskedLength = Int(byte2 ^ 0x80)
if unmaskedLength == smallPayloadSize {
if self.readBuffer.availableExportBytes >= 2 {
unmaskedLength = Int(ntohs(self.readBuffer.export16Bits()))
}
} else if unmaskedLength > smallPayloadSize {
if self.readBuffer.availableExportBytes >= 8 {
unmaskedLength = Int(ntohll(self.readBuffer.export64Bits()))
}
} // else small payload
if self.readBuffer.availableExportBytes >= 4 {
let maskingKey = self.readBuffer.exportBytes(4)
if self.readBuffer.availableExportBytes >= unmaskedLength {
var exported = self.readBuffer.exportBytes(unmaskedLength)
for i in 0..<exported.count {
exported[i] = exported[i] ^ maskingKey[i % 4]
}
self.clearFrame()
return Frame(fin: fin, rsv1: rsv1, rsv2: rsv2, rsv3: rsv3, opCode: opcode, bytesPayload: exported)
}
}
self.readBuffer.position = oldPosition
return nil
}
func fillBuffer(demand: Int, completion: (Bool) -> ()) {
self.socket.readBytesFully(demand, timeoutSeconds: self.readTimeoutSeconds) {
[weak self] (b:[UInt8]?) -> () in
if let b = b {
self?.readBuffer.data.appendContentsOf(b)
}
completion(b != nil)
}
}
func fillBufferSome(suggestion: Int, completion: () -> ()) {
self.socket.readSomeBytes(suggestion) {
[weak self] (b:[UInt8]?) -> () in
if let b = b {
self?.readBuffer.data.appendContentsOf(b)
}
completion()
}
}
private func readFrame(completion: (Frame?) -> ()) {
if let frame = self.fillFrame() {
switch frame.opCode {
// check for and handle ping/pong
case .Ping:
self.sendMessage(.Pong, bytes: frame.bytesPayload, final: true) {
self.readFrame(completion)
}
return
// check for and handle close
case .Close:
self.close()
return completion(nil)
default:
return completion(frame)
}
}
self.fillBuffer(1) {
b in
guard b != false else {
return completion(nil)
}
self.fillBufferSome(1024 * 32) { // some arbitrary read-ahead amount
self.readFrame(completion)
}
}
}
/// Read string data from the client.
public func readStringMessage(continuation: (String?, opcode: OpcodeType, final: Bool) -> ()) {
self.readFrame {
frame in
continuation(frame?.stringPayload, opcode: frame?.opCode ?? .Invalid, final: frame?.fin ?? true)
}
}
/// Read binary data from the client.
public func readBytesMessage(continuation: ([UInt8]?, opcode: OpcodeType, final: Bool) -> ()) {
self.readFrame {
frame in
continuation(frame?.bytesPayload, opcode: frame?.opCode ?? .Invalid, final: frame?.fin ?? true)
}
}
/// Send binary data to thew client.
public func sendBinaryMessage(bytes: [UInt8], final: Bool, completion: () -> ()) {
self.sendMessage(.Binary, bytes: bytes, final: final, completion: completion)
}
/// Send string data to the client.
public func sendStringMessage(string: String, final: Bool, completion: () -> ()) {
self.sendMessage(.Text, bytes: UTF8Encoding.decode(string), final: final, completion: completion)
}
/// Send a "pong" message to the client.
public func sendPong(completion: () -> ()) {
self.sendMessage(.Pong, bytes: [UInt8](), final: true, completion: completion)
}
/// Send a "ping" message to the client.
/// Expect a "pong" message to follow.
public func sendPing(completion: () -> ()) {
self.sendMessage(.Ping, bytes: [UInt8](), final: true, completion: completion)
}
private func sendMessage(opcode: OpcodeType, bytes: [UInt8], final: Bool, completion: () -> ()) {
let sendBuffer = Bytes()
let byte1 = UInt8(final ? 0x80 : 0x0) | (self.nextIsContinuation ? 0 : opcode.rawValue)
self.nextIsContinuation = !final
sendBuffer.import8Bits(byte1)
let payloadSize = bytes.count
if payloadSize < smallPayloadSize {
let byte2 = UInt8(payloadSize)
sendBuffer.import8Bits(byte2)
} else if payloadSize <= Int(UINT16_MAX) {
sendBuffer.import8Bits(UInt8(smallPayloadSize))
.import16Bits(htons(UInt16(payloadSize)))
} else {
sendBuffer.import8Bits(UInt8(1+smallPayloadSize))
.import64Bits(htonll(UInt64(payloadSize)))
}
sendBuffer.importBytes(bytes)
self.socket.writeBytes(sendBuffer.data) {
_ in
completion()
}
}
}
/// The protocol that all WebSocket handlers must implement.
public protocol WebSocketSessionHandler {
/// Optionally indicate the name of the protocol the handler implements.
/// If this has a valid, the protocol name will be validated against what the client is requesting.
var socketProtocol: String? { get }
/// This function is called once the WebSocket session has been initiated.
func handleSession(request: WebRequest, socket: WebSocket)
}
private let acceptableProtocolVersions = [13]
private let webSocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
/// This request handler accepts WebSocket requests from client.
/// It will initialize the session and then deliver it to the `WebSocketSessionHandler`.
public class WebSocketHandler : RequestHandler {
public typealias HandlerProducer = (request: WebRequest, protocols: [String]) -> WebSocketSessionHandler?
private let handlerProducer: HandlerProducer
public init(handlerProducer: HandlerProducer) {
self.handlerProducer = handlerProducer
}
public func handleRequest(request: WebRequest, response: WebResponse) {
guard let upgrade = request.header("Upgrade"),
connection = request.header("Connection"),
secWebSocketKey = request.header("Sec-WebSocket-Key"),
secWebSocketVersion = request.header("Sec-WebSocket-Version")
where upgrade.lowercaseString == "websocket" && connection.lowercaseString == "upgrade" else {
response.setStatus(400, message: "Bad Request")
response.requestCompletedCallback()
return
}
guard acceptableProtocolVersions.contains(Int(secWebSocketVersion) ?? 0) else {
response.setStatus(400, message: "Bad Request")
response.addHeader("Sec-WebSocket-Version", value: "\(acceptableProtocolVersions[0])")
response.appendBodyString("WebSocket protocol version \(secWebSocketVersion) not supported. Supported protocol versions are: \(acceptableProtocolVersions.map { String($0) }.joinWithSeparator(","))")
response.requestCompletedCallback()
return
}
let secWebSocketProtocol = request.header("Sec-WebSocket-Protocol") ?? ""
let protocolList = secWebSocketProtocol.characters.split(",").flatMap {
i -> String? in
var s = String(i)
while s.characters.count > 0 && s.characters[s.characters.startIndex] == " " {
s.removeAtIndex(s.startIndex)
}
return s.characters.count > 0 ? s : nil
}
guard let handler = self.handlerProducer(request: request, protocols: protocolList) else {
response.setStatus(400, message: "Bad Request")
response.appendBodyString("WebSocket protocols not supported.")
response.requestCompletedCallback()
return
}
response.requestCompletedCallback = {} // this is no longer a normal request, eligible for keep-alive
response.setStatus(101, message: "Switching Protocols")
response.addHeader("Upgrade", value: "websocket")
response.addHeader("Connection", value: "Upgrade")
response.addHeader("Sec-WebSocket-Accept", value: self.base64((secWebSocketKey + webSocketGUID).utf8.sha1))
if let chosenProtocol = handler.socketProtocol {
response.addHeader("Sec-WebSocket-Protocol", value: chosenProtocol)
}
for (key, value) in response.headersArray {
response.connection.writeHeaderLine(key + ": " + value)
}
response.connection.writeBodyBytes([UInt8]())
handler.handleSession(request, socket: WebSocket(connection: response.connection))
}
private func base64(a: [UInt8]) -> String {
let bio = BIO_push(BIO_new(BIO_f_base64()), BIO_new(BIO_s_mem()))
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL)
BIO_write(bio, a, Int32(a.count))
BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nil)
var mem = UnsafeMutablePointer<BUF_MEM>()
BIO_ctrl(bio, BIO_C_GET_BUF_MEM_PTR, 0, &mem)
BIO_ctrl(bio, BIO_CTRL_SET_CLOSE, Int(BIO_NOCLOSE), nil)
BIO_free_all(bio)
let txt = UnsafeMutablePointer<UInt8>(mem.memory.data)
let ret = UTF8Encoding.encode(GenerateFromPointer(from: txt, count: mem.memory.length))
free(mem.memory.data)
return ret
}
}
import OpenSSL
extension String.UTF8View {
var sha1: [UInt8] {
let bytes = UnsafeMutablePointer<UInt8>.alloc(Int(SHA_DIGEST_LENGTH))
defer { bytes.destroy() ; bytes.dealloc(Int(SHA_DIGEST_LENGTH)) }
SHA1(Array<UInt8>(self), (self.count), bytes)
var r = [UInt8]()
for idx in 0..<Int(SHA_DIGEST_LENGTH) {
r.append(bytes[idx])
}
return r
}
}
|
29e1325113e224b88d834440210b97b3
| 29.861619 | 201 | 0.710575 | false | false | false | false |
nathan-hekman/Chill
|
refs/heads/master
|
Chill/Chill/Utilities/ColorUtil.swift
|
mit
|
1
|
//
// Utils.swift
// Chill
//
// Created by Nathan Hekman on 12/20/15.
// Copyright © 2015 NTH. All rights reserved.
//
import UIKit
import ChameleonFramework
class ColorUtil: NSObject {
static let sharedInstance: ColorUtil = {
var instance = ColorUtil()
return instance
}()
private override init() {
super.init()
}
var colorArray: NSArray!
var color1: UIColor!
var color2: UIColor!
var color3: UIColor! //base color of palette
var color4: UIColor!
var color5: UIColor!
func setupFlatColorPaletteWithFlatBaseColor(color: UIColor!, colorscheme: ColorScheme!) {
//get color scheme
colorArray = NSArray(ofColorsWithColorScheme: colorscheme, usingColor: color, withFlatScheme: true)
color1 = colorArray[0] as? UIColor
color2 = colorArray[1] as? UIColor
color3 = colorArray[2] as? UIColor
color4 = colorArray[3] as? UIColor
color5 = colorArray[4] as? UIColor
}
}
|
cb141f4b1162676eb2711a54cab566bb
| 21.020833 | 107 | 0.614948 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS
|
refs/heads/master
|
ResearchUXFactory/SBAProfileInfoForm.swift
|
bsd-3-clause
|
1
|
//
// SBARegistrationForm.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
/**
Protocol for extending all the profile info steps (used by the factory to create the
appropriate default form items).
*/
public protocol SBAProfileInfoForm: SBAFormStepProtocol {
/**
Use the `ORKFormItem` model object when getting/setting
*/
var formItems:[ORKFormItem]? { get set }
/**
Used in common initialization to get the default options if the included options are nil.
*/
func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption]
}
/**
Shared factory methods for creating profile form steps.
*/
extension SBAProfileInfoForm {
public var options: [SBAProfileInfoOption]? {
return self.formItems?.mapAndFilter({ SBAProfileInfoOption(rawValue: $0.identifier) })
}
public func formItemForProfileInfoOption(_ profileInfoOption: SBAProfileInfoOption) -> ORKFormItem? {
return self.formItems?.find({ $0.identifier == profileInfoOption.rawValue })
}
public func commonInit(inputItem: SBASurveyItem?, factory: SBABaseSurveyFactory?) {
self.title = inputItem?.stepTitle
self.text = inputItem?.stepText
if let formStep = self as? ORKFormStep {
formStep.footnote = inputItem?.stepFootnote
}
let options = SBAProfileInfoOptions(inputItem: inputItem, defaultIncludes: defaultOptions(inputItem))
self.formItems = options.makeFormItems(factory: factory)
}
}
|
4633c1c4a66c7e71bdbc40f224aa56f4
| 40.597403 | 109 | 0.739931 | false | false | false | false |
HongliYu/DPColorfulTags-Swift
|
refs/heads/master
|
DPColorfulTagsDemo/DPAppLanguage.swift
|
mit
|
1
|
//
// DPAppLanguage.swift
// DPColorfulTagsDemo
//
// Created by Hongli Yu on 12/11/2017.
// Copyright © 2017 Hongli Yu. All rights reserved.
//
import Foundation
class DPAppLanguage: Equatable {
let code: String
let englishName: String
let localizedName: String
init(code: String) {
self.code = code
let localeEnglish = Locale(identifier: "en")
self.englishName = localeEnglish.localizedString(forIdentifier: code) ?? ""
let locale = Locale(identifier: code)
self.localizedName = locale.localizedString(forIdentifier: code) ?? ""
}
}
extension DPAppLanguage: CustomStringConvertible {
var description: String {
return "\(code), \(englishName), \(localizedName)"
}
}
func == (lhs: DPAppLanguage, rhs: DPAppLanguage) -> Bool {
return lhs.code == rhs.code
}
|
58014e54d9e3866e5e507908a461e446
| 21.135135 | 79 | 0.686203 | false | false | false | false |
nessBautista/iOSBackup
|
refs/heads/master
|
SwiftSlang/plotTest1/plotTest1/PlotView.swift
|
cc0-1.0
|
1
|
//
// PlotView.swift
// plotTest1
//
// Created by Ness on 1/8/16.
// Copyright © 2016 Ness. All rights reserved.
//
import UIKit
class PlotView: UIView {
// MARK: Geometric Constants
var kGraphHeight = 300
var kDefaultGraphWidth = 600
var kOffsetX = 10
var kStepX = 50
var kGraphBottom = 300
var kGraphTop = 0
// MARK: Init routines
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextSetLineWidth(context, 10.0)
CGContextSetStrokeColorWithColor(context, UIColor.greenColor().CGColor)
CGContextMoveToPoint(context, 0.0, 0.0)
CGContextAddLineToPoint(context, self.frame.width/2, self.frame.height/2)
// let howMany = (kDefaultGraphWidth - kOffsetX) / kStepX
//
// for i in 0...howMany
// {
// CGContextMoveToPoint(context, CGFloat(kOffsetX) + CGFloat(i*kStepX), CGFloat(kGraphTop))
// CGContextAddLineToPoint(context, CGFloat(kOffsetX) + CGFloat(i * kStepX), CGFloat(kGraphBottom))
// }
CGContextStrokePath(context)
CGContextRestoreGState(context)
}
}
|
bf77396769cc71375dcf0a2ab1349d3d
| 23.967213 | 110 | 0.625739 | false | false | false | false |
sora0077/iTunesKit
|
refs/heads/master
|
iTunesKit/src/Endpoint/Search.swift
|
mit
|
1
|
//
// Search.swift
// iTunesKit
//
// Created by 林達也 on 2015/10/04.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
public struct Search {
/// The URL-encoded text string you want to search for. For example: jack+johnson.
/// Any URL-encoded text string.
///
/// Note: URL encoding replaces spaces with the plus (+) character and all characters except the following are encoded: letters, numbers, periods (.), dashes (-), underscores (_), and asterisks (*).
public var term: String
/// The two-letter country code for the store you want to search. The search uses the default store front for the specified country. For example: US.
///
/// The default is US.
public var country: String
/// The media type you want to search for. For example: movie.
///
/// The default is all.
public var media: String = "all"
/// The type of results you want returned, relative to the specified media type. For example: movieArtist for a movie media type search.
///
/// The default is the track entity associated with the specified media type.
public var entity: String = "allTrack"
/// The attribute you want to search for in the stores, relative to the specified media type. For example, if you want to search for an artist by name specify entity=allArtist&attribute=allArtistTerm.
///
/// In this example, if you search for term=maroon, iTunes returns "Maroon 5" in the search results, instead of all artists who have ever recorded a song with the word "maroon" in the title.
///
/// The default is all attributes associated with the specified media type.
public var attribute: String?
/// The number of search results you want the iTunes Store to return. For example: 25.
///
/// The default is 50.
public var limit: Int = 50
/// The language, English or Japanese, you want to use when returning search results. Specify the language using the five-letter codename. For example: en_us.
///
/// The default is en_us (English).
public var lang: String = "en_us"
/// A flag indicating whether or not you want to include explicit content in your search results.
///
/// The default is Yes.
public var explicit: Bool = true
/**
<#Description#>
- parameter term: Y
- parameter country: Y
- returns: <#return value description#>
*/
public init(term: String, country: String = "US") {
self.term = term
self.country = country
}
}
extension Search: iTunesRequestToken {
public typealias Response = [SearchResult]
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .GET
}
public var path: String {
return "https://itunes.apple.com/search"
}
public var parameters: [String: AnyObject]? {
var dict: [String: AnyObject] = [
"term": term,
"country": country,
"media": media,
"entity": entity,
"limit": limit,
"lang": lang,
"explicit": explicit ? "Yes" : "No"
]
if let attribute = attribute {
dict["attribute"] = attribute
}
return dict
}
public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
print(request, object)
return (object["results"] as! [[String: AnyObject]]).map { v in
guard let wrapperType = SearchResultWrapperType(rawValue: v["wrapperType"] as! String) else {
return .Unsupported(v)
}
switch wrapperType {
case .Track:
guard let kind = SearchResultKind(rawValue: v["kind"] as! String) else {
return .Unsupported(v)
}
return .Track(SearchResultTrack(
kind: kind,
artistId: v["artistId"] as! Int,
collectionId: v["collectionId"] as! Int,
trackId: v["trackId"] as! Int,
artistName: v["artistName"] as! String,
collectionName: v["collectionName"] as! String,
trackName: v["trackName"] as! String,
collectionCensoredName: v["collectionCensoredName"] as! String,
trackCensoredName: v["trackCensoredName"] as! String,
artistViewUrl: v["artistViewUrl"] as! String,
collectionViewUrl: v["collectionViewUrl"] as! String,
trackViewUrl: v["trackViewUrl"] as! String,
previewUrl: v["previewUrl"] as! String,
artworkUrl30: v["artworkUrl30"] as! String,
artworkUrl60: v["artworkUrl60"] as! String,
artworkUrl100: v["artworkUrl100"] as! String,
collectionPrice: v["collectionPrice"] as! Float,
trackPrice: v["trackPrice"] as! Float,
releaseDate: v["releaseDate"] as! String,
collectionExplicitness: v["collectionExplicitness"] as! String,
trackExplicitness: v["trackExplicitness"] as! String,
discCount: v["discCount"] as! Int,
discNumber: v["discNumber"] as! Int,
trackCount: v["trackCount"] as! Int,
trackNumber: v["trackNumber"] as! Int,
trackTimeMillis: v["trackTimeMillis"] as! Int,
country: v["country"] as! String,
currency: v["currency"] as! String,
primaryGenreName: v["primaryGenreName"] as! String,
radioStationUrl: v["radioStationUrl"] as? String,
isStreamable: v["isStreamable"] as! Bool
))
case .Artist:
return .Artist(SearchResultArtist(
artistType: v["artistType"] as! String,
artistName: v["artistName"] as! String,
artistLinkUrl: v["artistLinkUrl"] as! String,
artistId: v["artistId"] as! Int,
amgArtistId: v["amgArtistId"] as? Int,
primaryGenreName: v["primaryGenreName"] as! String,
primaryGenreId: v["primaryGenreId"] as! Int,
radioStationUrl: v["radioStationUrl"] as? String
))
case .Collection:
return .Collection(SearchResultCollection(
collectionType: v["collectionType"] as! String,
artistId: v["artistId"] as! Int,
collectionId: v["collectionId"] as! Int,
amgArtistId: v["amgArtistId"] as! Int,
artistName: v["artistName"] as! String,
collectionName: v["collectionName"] as! String,
collectionCensoredName: v["collectionCensoredName"] as! String,
artistViewUrl: v["artistViewUrl"] as! String,
collectionViewUrl: v["collectionViewUrl"] as! String,
artworkUrl30: v["artworkUrl30"] as! String,
artworkUrl60: v["artworkUrl60"] as! String,
artworkUrl100: v["artworkUrl100"] as! String,
collectionPrice: v["collectionPrice"] as! Float,
collectionExplicitness: v["collectionExplicitness"] as! String,
trackCount: v["trackCount"] as! Int,
copyright: v["copyright"] as! String,
country: v["country"] as! String,
currency: v["currency"] as! String,
releaseDate: v["releaseDate"] as! String,
primaryGenreName: v["primaryGenreName"] as! String,
radioStationUrl: v["radioStationUrl"] as? String
))
}
}
}
}
|
0e980f65015ca173620ae8f4004bba82
| 40.623188 | 204 | 0.528668 | false | false | false | false |
HongxiangShe/STV
|
refs/heads/master
|
STV/STV/Classes/Main/Protocol/Nibloadable.swift
|
apache-2.0
|
1
|
//
// Nibloadable.swift
// SHXPageView
//
// Created by 佘红响 on 2017/6/5.
// Copyright © 2017年 she. All rights reserved.
//
import UIKit
protocol Nibloadable {
}
// 表明该协议只能被UIView实现
extension Nibloadable where Self: UIView {
// 协议,结构体都用static
static func loadFromNib(_ nibname: String? = nil) -> Self {
// let nib = nibname == nil ? "\(self)" : nibname!
let nib = nibname ?? "\(self)";
return Bundle.main.loadNibNamed(nib, owner: nil, options: nil)?.first as! Self
}
}
|
b95cda00c498ea7f1379a093071136e3
| 18.962963 | 86 | 0.593692 | false | false | false | false |
treasure-data/td-ios-sdk
|
refs/heads/master
|
TreasureDataExample/TreasureDataExample/IAPViewController.swift
|
apache-2.0
|
1
|
//
// IAPViewController.swift
// TreasureDataExample
//
// Created by huylenq on 3/7/19.
// Copyright © 2019 Arm Treasure Data. All rights reserved.
//
import UIKit
import StoreKit
class IAPViewController : UITableViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver
{
var products: [SKProduct] = []
let indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
override func viewDidLoad() {
indicator.center = CGPoint(x: self.view.center.x, y: self.view.center.y * 0.3)
indicator.color = .gray
indicator.hidesWhenStopped = true
indicator.startAnimating()
self.view.addSubview(indicator)
requestProducts()
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction])
{
for transaction in transactions {
if (transaction.transactionState != .purchasing) {
queue.finishTransaction(transaction)
}
}
}
@IBAction func purchase(_ sender: UIButton) {
(self.parent as! iOSViewController).updateClientIfFormChanged()
let product = products[sender.tag]
SKPaymentQueue.default().add(SKPayment(product: product))
}
public func requestProducts()
{
let request = SKProductsRequest(productIdentifiers: TreasureDataExample.productIds())
request.delegate = self
request.start()
SKPaymentQueue.default().add(self)
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse)
{
self.products = response.products
(self.view as? UITableView)?.separatorStyle = .singleLine
indicator.stopAnimating()
self.tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return products.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "IAPItemCell") as! IAPItemCell
cell.itemName.text = products[indexPath.row].localizedTitle
cell.purchaseButton.tag = indexPath.row
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let product = products[indexPath.row]
let payment = SKMutablePayment(product: product)
payment.quantity = 1
SKPaymentQueue.default().add(payment)
}
}
class IAPItemCell : UITableViewCell
{
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var purchaseButton: UIButton!
}
|
52d38264613f5a847f5a007c903dab41
| 29.731183 | 107 | 0.6655 | false | false | false | false |
bromas/ActivityViewController
|
refs/heads/master
|
ActivityViewController/ActivityTransitionManager.swift
|
mit
|
1
|
//
// ApplicationTransitionManager.swift
// ApplicationVCSample
//
// Created by Brian Thomas on 3/1/15.
// Copyright (c) 2015 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
internal class ActivityTransitionManager {
fileprivate weak var managedContainer : ActivityViewController?
internal var activeVC : UIViewController?
lazy internal var typeAnimator: AnimateByTypeManager = {
return AnimateByTypeManager(containerController: self.managedContainer)
}()
lazy internal var noninteractiveTransitionManager: AnimateNonInteractiveTransitionManager = {
return AnimateNonInteractiveTransitionManager(containerController: self.managedContainer)
}()
init (containerController: ActivityViewController) {
managedContainer = containerController
}
var containerView: UIView? = .none
/**
An 'active controller's view should be contained in a UIView subview of the container controller to operate correctly with all transition types.
*/
internal func transitionToVC(_ controller: UIViewController, withOperation operation: ActivityOperation) {
guard let managedContainer = managedContainer else {
return
}
if let activeVCUnwrapped = activeVC {
switch operation.type {
case .animationOption:
managedContainer.animating = true
typeAnimator.animate(operation.animationOption, fromVC: activeVCUnwrapped, toVC: controller, withDuration: operation.animationDuration, completion: completionGen(operation))
case .nonInteractiveTransition:
managedContainer.animating = true
noninteractiveTransitionManager.animate(operation.nonInteractiveTranstionanimator, fromVC: activeVCUnwrapped, toVC: controller, completion: completionGen(operation))
case .none:
_ = swapToControllerUnanimated(controller, fromController: activeVCUnwrapped)
default:
assert(false, "You called for a transition with an invalid operation... How did you even do that!?")
}
activeVC = controller
} else {
_ = initializeDisplayWithController(controller)
}
}
fileprivate func completionGen(_ operation: ActivityOperation) -> (() -> Void) {
return { [weak self] _ in
operation.completionBlock()
self?.managedContainer?.animating = false
}
}
fileprivate func swapToControllerUnanimated(_ controller: UIViewController, fromController: UIViewController) -> Bool {
guard let container = containerView else {
return false
}
removeController(fromController)
self.activeVC = .none
prepareContainmentFor(controller, inController: managedContainer)
container.addSubview(controller.view)
constrainEdgesOf(controller.view, toEdgesOf: container)
controller.didMove(toParentViewController: managedContainer);
self.activeVC = controller
return true
}
func initializeDisplayWithController(_ controller: UIViewController) -> Bool {
guard let managedContainer = managedContainer else {
return false
}
let container = UIView(frame: CGRect.zero)
container.translatesAutoresizingMaskIntoConstraints = false
managedContainer.view.addSubview(container)
constrainEdgesOf(container, toEdgesOf: managedContainer.view)
containerView = container
managedContainer.configureContainerView(container)
prepareContainmentFor(controller, inController: managedContainer)
container.addSubview(controller.view)
constrainEdgesOf(controller.view, toEdgesOf: container)
controller.didMove(toParentViewController: managedContainer);
self.activeVC = controller
return true
}
fileprivate func removeController(_ controller: UIViewController) {
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.didMove(toParentViewController: nil)
}
}
|
66a976623e6135026a158a1cb3ec5702
| 34.225225 | 181 | 0.74578 | false | false | false | false |
hhsolar/MemoryMaster-iOS
|
refs/heads/master
|
MemoryMaster/View/EditNoteCollectionViewCell.swift
|
mit
|
1
|
//
// EditNoteCollectionViewCell.swift
// MemoryMaster
//
// Created by apple on 23/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
protocol EditNoteCollectionViewCellDelegate: class {
func noteTitleEdit(for cell: EditNoteCollectionViewCell)
func noteTextContentChange(cardIndex: Int, textViewType: String, textContent: NSAttributedString)
func noteAddPhoto()
}
class EditNoteCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var titleEditButton: UIButton!
@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var bodyTextView: UITextView!
let titleTextView = UITextView()
let titleKeyboardAddPhotoButton = UIButton()
let bodyKeyboardAddPhotoButton = UIButton()
var cardIndex: Int?
var currentStatus: CardStatus?
var editingTextView: UITextView?
weak var delegate: EditNoteCollectionViewCellDelegate?
var titleText: NSAttributedString? {
get {
return titleTextView.attributedText
}
}
var bodyText: NSAttributedString? {
get {
return bodyTextView.attributedText
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
private func setupUI()
{
contentView.backgroundColor = CustomColor.paperColor
titleEditButton.setTitleColor(CustomColor.medianBlue, for: .normal)
// titleTextView
titleTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge)
titleTextView.backgroundColor = CustomColor.paperColor
titleTextView.tag = OutletTag.titleTextView.rawValue
titleTextView.showsVerticalScrollIndicator = false
titleTextView.delegate = self
contentView.addSubview(titleTextView)
let titleAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
titleKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight)
titleKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal)
titleKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside)
titleAccessoryView.addSubview(titleKeyboardAddPhotoButton)
titleTextView.inputAccessoryView = titleAccessoryView
// bodyTextView
bodyTextView.textContainerInset = UIEdgeInsets(top: 0, left: CustomDistance.wideEdge, bottom: 0, right: CustomDistance.wideEdge)
bodyTextView.backgroundColor = CustomColor.paperColor
bodyTextView.tag = OutletTag.bodyTextView.rawValue
bodyTextView.showsVerticalScrollIndicator = false
bodyTextView.delegate = self
let bodyAccessoryView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
bodyKeyboardAddPhotoButton.frame = CGRect(x: UIScreen.main.bounds.width - CustomDistance.midEdge - CustomSize.smallBtnHeight, y: 0, width: CustomSize.smallBtnHeight, height: CustomSize.smallBtnHeight)
bodyKeyboardAddPhotoButton.setImage(UIImage.init(named: "photo_icon"), for: .normal)
bodyKeyboardAddPhotoButton.addTarget(self, action: #selector(addPhotoAction), for: .touchUpInside)
bodyAccessoryView.addSubview(bodyKeyboardAddPhotoButton)
bodyTextView.inputAccessoryView = bodyAccessoryView
}
override func layoutSubviews() {
super.layoutSubviews()
titleTextView.frame = bodyTextView.frame
}
func updateCell(with cardContent: CardContent, at index: Int, total: Int, cellStatus: CardStatus, noteType: NoteType) {
cardIndex = index
currentStatus = cellStatus
indexLabel.text = String.init(format: "%d / %d", index + 1, total)
bodyTextView.attributedText = cardContent.body.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.body.length))
if noteType == NoteType.single {
titleEditButton.isHidden = false
} else {
titleEditButton.isHidden = true
}
switch cellStatus {
case .titleFront:
titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length))
showTitle(noteType: noteType)
case .bodyFrontWithTitle:
titleTextView.attributedText = cardContent.title.addAttributesForText(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: cardContent.title.length))
showBody(noteType: noteType)
default:
showBody(noteType: noteType)
titleTextView.attributedText = NSAttributedString()
}
}
func showTitle(noteType: NoteType)
{
UIView.animateKeyframes(withDuration: 0.5, delay: 0.3, options: [], animations: {
if noteType == NoteType.single {
self.titleEditButton.setTitle("Remove Title", for: .normal)
self.titleLable.text = "Title"
} else {
self.titleLable.text = "Question"
}
self.titleTextView.alpha = 1.0
self.bodyTextView.alpha = 0.0
}, completion: nil)
titleTextView.isHidden = false
bodyTextView.isHidden = true
bodyTextView.resignFirstResponder()
editingTextView = titleTextView
}
func showBody(noteType: NoteType)
{
UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
if noteType == NoteType.single {
self.titleLable.text = ""
if self.currentStatus == CardStatus.bodyFrontWithTitle {
self.titleEditButton.setTitle("Remove Title", for: .normal)
} else {
self.titleEditButton.setTitle("Add Title", for: .normal)
}
} else {
self.titleLable.text = "Answer"
}
self.titleTextView.alpha = 0.0
self.bodyTextView.alpha = 1.0
}, completion: nil)
titleTextView.isHidden = true
bodyTextView.isHidden = false
titleTextView.resignFirstResponder()
editingTextView = bodyTextView
}
@IBAction func titleEditAction(_ sender: UIButton) {
delegate?.noteTitleEdit(for: self)
}
@objc func addPhotoAction() {
delegate?.noteAddPhoto()
}
func cutTextView(KBHeight: CGFloat) {
editingTextView?.frame.size.height = contentView.bounds.height + CustomSize.barHeight - KBHeight - CustomSize.buttonHeight
}
func extendTextView() {
editingTextView?.frame.size.height = contentView.bounds.height - CustomSize.buttonHeight
}
}
extension EditNoteCollectionViewCell: UITextViewDelegate {
func textViewDidChangeSelection(_ textView: UITextView) {
if textView.tag == OutletTag.titleTextView.rawValue {
delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "title", textContent: titleText!)
} else if textView.tag == OutletTag.bodyTextView.rawValue {
delegate?.noteTextContentChange(cardIndex: cardIndex!, textViewType: "body", textContent: bodyText!)
}
}
func textViewDidChange(_ textView: UITextView) {
if textView.markedTextRange == nil {
let range = textView.selectedRange
let attrubuteStr = NSMutableAttributedString(attributedString: textView.attributedText)
attrubuteStr.addAttributes(CustomRichTextAttri.bodyNormal, range: NSRange(location: 0, length: textView.text.count))
textView.attributedText = attrubuteStr
textView.selectedRange = range
}
}
}
|
d9626437e5ecc96716308f0d33c6d733
| 40.8125 | 209 | 0.670279 | false | false | false | false |
tensorflow/swift-models
|
refs/heads/main
|
Examples/ResNet50-ImageNet/main.swift
|
apache-2.0
|
1
|
// Copyright 2019 The TensorFlow Authors. 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 Datasets
import ImageClassificationModels
import TensorBoard
import TensorFlow
import TrainingLoop
// XLA mode can't load Imagenet, need to use eager mode to limit memory use
let device = Device.defaultTFEager
let dataset = ImageNet(batchSize: 32, outputSize: 224, on: device)
var model = ResNet(classCount: 1000, depth: .resNet50)
// https://github.com/mlcommons/training/blob/4f97c909f3aeaa3351da473d12eba461ace0be76/image_classification/tensorflow/official/resnet/imagenet_main.py#L286
let optimizer = SGD(for: model, learningRate: 0.1, momentum: 0.9)
public func scheduleLearningRate<L: TrainingLoopProtocol>(
_ loop: inout L, event: TrainingLoopEvent
) throws where L.Opt.Scalar == Float {
if event == .epochStart {
guard let epoch = loop.epochIndex else { return }
if epoch > 30 { loop.optimizer.learningRate = 0.01 }
if epoch > 60 { loop.optimizer.learningRate = 0.001 }
if epoch > 80 { loop.optimizer.learningRate = 0.0001 }
}
}
var trainingLoop = TrainingLoop(
training: dataset.training,
validation: dataset.validation,
optimizer: optimizer,
lossFunction: softmaxCrossEntropy,
metrics: [.accuracy],
callbacks: [scheduleLearningRate, tensorBoardStatisticsLogger()])
try! trainingLoop.fit(&model, epochs: 90, on: device)
|
1c133d014403c1aea4af1dac032a49cb
| 39.361702 | 156 | 0.756458 | false | false | false | false |
uber/rides-ios-sdk
|
refs/heads/master
|
source/UberCoreTests/LoginManagerTests.swift
|
mit
|
1
|
//
// LoginManagerTests.swift
// UberRides
//
// 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 XCTest
import CoreLocation
import WebKit
@testable import UberCore
class LoginManagerTests: XCTestCase {
private let timeout: Double = 2
override func setUp() {
super.setUp()
Configuration.plistName = "testInfo"
Configuration.restoreDefaults()
Configuration.shared.isSandbox = true
}
override func tearDown() {
Configuration.restoreDefaults()
super.tearDown()
}
func testRidesAppDelegateContainsManager_afterNativeLogin() {
let loginManager = LoginManager(loginType: .native)
loginManager.login(requestedScopes: [.profile], presentingViewController: nil, completion: nil)
XCTAssert(UberAppDelegate.shared.loginManager is LoginManager, "Expected RidesAppDelegate to have loginManager instance")
}
func testAuthentictorIsImplicit_whenLoginWithImplicitType() {
let loginManager = LoginManager(loginType: .implicit)
let presentingViewController = UIViewController()
loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil)
XCTAssert(loginManager.authenticator is ImplicitGrantAuthenticator)
XCTAssertTrue(loginManager.loggingIn)
}
func testAuthentictorIsAuthorizationCode_whenLoginWithAuthorizationCodeType() {
let loginManager = LoginManager(loginType: .authorizationCode)
let presentingViewController = UIViewController()
loginManager.login(requestedScopes: [.profile], presentingViewController: presentingViewController, completion: nil)
XCTAssert(loginManager.authenticator is AuthorizationCodeGrantAuthenticator)
XCTAssertTrue(loginManager.loggingIn)
}
func testLoginFails_whenLoggingIn() {
let expectation = self.expectation(description: "loginCompletion called")
let loginCompletion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void) = { token, error in
guard let error = error else {
XCTFail()
return
}
XCTAssertEqual(error.code, UberAuthenticationErrorType.unavailable.rawValue)
expectation.fulfill()
}
let loginManagerMock = LoginManagerPartialMock()
loginManagerMock.executeLoginClosure = { completionHandler in
completionHandler?(nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
}
loginManagerMock.login(requestedScopes: [.profile], presentingViewController: nil, completion: loginCompletion)
waitForExpectations(timeout: 0.2, handler: nil)
}
func testOpenURLFails_whenInvalidSource() {
let loginManager = LoginManager(loginType: .native)
let testApp = UIApplication.shared
guard let testURL = URL(string: "http://www.google.com") else {
XCTFail()
return
}
let testSourceApplication = "com.not.uber.app"
let testAnnotation = "annotation"
XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation))
}
func testOpenURLFails_whenNotNativeType() {
let loginManager = LoginManager(loginType: .implicit)
let testApp = UIApplication.shared
guard let testURL = URL(string: "http://www.google.com") else {
XCTFail()
return
}
let testSourceApplication = "com.ubercab.foo"
let testAnnotation = "annotation"
XCTAssertFalse(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation))
}
func testOpenURLSuccess_rides() {
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)])
let testApp = UIApplication.shared
guard let testURL = URL(string: "http://www.google.com") else {
XCTFail()
return
}
let testSourceApplication = "com.ubercab.foo"
let testAnnotation = "annotation"
let authenticatorMock = RidesNativeAuthenticatorPartialStub(scopes: [.profile])
authenticatorMock.consumeResponseCompletionValue = (nil, nil)
loginManager.authenticator = authenticatorMock
loginManager.loggingIn = true
XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation))
XCTAssertFalse(loginManager.loggingIn)
XCTAssertNil(loginManager.authenticator)
}
func testOpenURLSuccess_eats() {
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)])
let testApp = UIApplication.shared
guard let testURL = URL(string: "http://www.google.com") else {
XCTFail()
return
}
let testSourceApplication = "com.ubercab.UberEats"
let testAnnotation = "annotation"
let authenticatorMock = EatsNativeAuthenticatorPartialStub(scopes: [.profile])
authenticatorMock.consumeResponseCompletionValue = (nil, nil)
loginManager.authenticator = authenticatorMock
loginManager.loggingIn = true
XCTAssertTrue(loginManager.application(testApp, open: testURL, sourceApplication: testSourceApplication, annotation: testAnnotation))
XCTAssertFalse(loginManager.loggingIn)
XCTAssertNil(loginManager.authenticator)
}
func testCancelLoginNotCalled_whenNotEnteringForeground() {
let loginManager = LoginManager(loginType: .native)
loginManager.loggingIn = true
loginManager.applicationDidBecomeActive()
XCTAssertNil(loginManager.authenticator)
XCTAssertTrue(loginManager.loggingIn)
}
func testCancelLoginCalled_whenDidBecomeActive() {
let loginManager = LoginManager(loginType: .native)
loginManager.loggingIn = true
loginManager.applicationWillEnterForeground()
loginManager.applicationDidBecomeActive()
XCTAssertNil(loginManager.authenticator)
XCTAssertFalse(loginManager.loggingIn)
}
func testNativeLoginCompletionDoesFallback_whenUnavailableError_withConfiguration_alwaysUseAuthCodeFallback() {
Configuration.shared.alwaysUseAuthCodeFallback = true
let scopes = [UberScope.historyLite]
let loginManager = LoginManager(loginType: .native)
let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: [])
nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
loginManager.authenticator = nativeAuthenticatorStub
let viewController = UIViewController()
loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil)
XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode)
}
func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_rides() {
Configuration.shared.useFallback = true
let scopes = [UberScope.request]
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)])
let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: [])
nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
loginManager.authenticator = nativeAuthenticatorStub
let viewController = UIViewController()
loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil)
XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode)
}
func testNativeLoginCompletionDoesFallback_whenUnavailableError_withPrivelegedScopes_eats() {
Configuration.shared.useFallback = true
let scopes = [UberScope.request]
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)])
let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: [])
nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
loginManager.authenticator = nativeAuthenticatorStub
let viewController = UIViewController()
loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil)
XCTAssertEqual(loginManager.loginType, LoginType.authorizationCode)
}
func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_rides() {
let scopes = [UberScope.profile]
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.rides)])
let nativeAuthenticatorStub = RidesNativeAuthenticatorPartialStub(scopes: [])
nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
loginManager.authenticator = nativeAuthenticatorStub
let viewController = UIViewController()
loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil)
XCTAssertEqual(loginManager.loginType, LoginType.implicit)
}
func testNativeLoginCompletionDoesFallback_whenUnavailableError_withGeneralScopes_eats() {
let scopes = [UberScope.profile]
let loginManager = LoginManager(loginType: .native, productFlowPriority: [UberAuthenticationProductFlow(.eats)])
let nativeAuthenticatorStub = EatsNativeAuthenticatorPartialStub(scopes: [])
nativeAuthenticatorStub.consumeResponseCompletionValue = (nil, UberAuthenticationErrorFactory.errorForType(ridesAuthenticationErrorType: .unavailable))
loginManager.authenticator = nativeAuthenticatorStub
let viewController = UIViewController()
loginManager.login(requestedScopes: scopes, presentingViewController: viewController, completion: nil)
XCTAssertEqual(loginManager.loginType, LoginType.implicit)
}
}
|
6f5fdceeb5d4d63f55605470448ef872
| 41.386029 | 159 | 0.737618 | false | true | false | false |
rferrerme/malaga-scala-user-group-meetup
|
refs/heads/master
|
2015-06-18_Scala_y_programacion_funcional_101/Functional_Programming.playground/Contents.swift
|
mit
|
1
|
/*:
# Functional Programming in Swift
### Based on the Malaga Scala User Group meetup on 2015-06-08:
* [Slides](https://docs.google.com/presentation/d/1JYhcSe3JcWdNQkz9oquX3vU5I8gKA-KWuzVPkaQbopk/edit?usp=sharing)
* [Code](https://gist.github.com/jserranohidalgo/31e7ea8efecfb36276cf)
Pure function:
*/
let sumPure1 = { (x: Int, y: Int) in x+y }
sumPure1(4, 5)
//: Function with side effect:
let sumPureWithLogging1 = { (x: Int, y: Int) -> Int in
println("I'm a side effect")
return x+y
}
sumPureWithLogging1(4, 5)
/*:
That is not a pure function:
* It does not declare everything it does
* Pure functions can only do internal things
Impure functions are _evil_:
* Side effects make things difficult to understand
* Testing is also difficult (you need mocks, etc)
* Modularity and reusability are also a problem if there are side effects
* Efficiency and scalability: pure functions can be executed in any order
But we cannot only have pure functions because someone has to do the job: database, web services, log, etc.
How do we purify functions?
* E.g. logging has to be part of the result
* It has to be declared in the signature, as a new data type
New type to take care of the logging information:
*/
enum LoggingInstruction1 {
case Info(msg: String)
case Warn(msg: String)
case Debug(msg: String)
var description: String {
switch self {
case let .Info(msg: msg):
return "Info(\(msg))"
case let .Warn(msg: msg):
return "Warn(\(msg))"
case let .Debug(msg: msg):
return "Debug(\(msg))"
}
}
}
//: New type to combine logging information and value:
struct Logging1<T> {
var log: LoggingInstruction1
var result: T
var description: String {
return "(\(log.description), \(result)"
}
}
//: New implementations without side effects:
let sumPureWithLogging2 = { (x: Int, y: Int) -> Logging1<Int> in
return Logging1<Int>(log: LoggingInstruction1.Info(msg: "\(x) + \(y)"), result: x+y)
}
let operation = sumPureWithLogging2(4, 5)
operation.description
let negPureWithLogging2 = { (x: Int) -> Logging1<Int> in
return Logging1<Int>(log: LoggingInstruction1.Warn(msg: "Neg \(x)"), result: -x)
}
negPureWithLogging2(7).description
//: Simple test (asserts are not nice in Playgrounds):
operation.log.description == "Info(4 + 5)"
operation.result == 9
/*:
That helps to understand it conceptually.
The function returns an integer but decorated with logging instructions.
In practice every side effect should have its own type.
We will have two separare parts: pure and impure.
Programs have the interpreter also to be able to deal with the side effects.
What is the gain?
* Most part of the code can be tested, it is modular, it can be composed
* But the other part has to exist also...
* Our logging instructions can be implemented with println or log4j, etc
* The business logic of my application will remain unaffected by that
* The instructions set that I designed is not going to change
* I have designed a language to define my effects
My interpreter will remove the decoration and return the pure value:
*/
func runIO(logging: Logging1<Int>) -> Int {
switch logging.log {
case let LoggingInstruction1.Info(msg): println("INFO: " + msg)
case let LoggingInstruction1.Warn(msg): println("WARN: " + msg)
case let LoggingInstruction1.Debug(msg): println("DEBUG: " + msg)
}
return logging.result
}
//: See above (Quicklook of each `println`) for the side effects:
runIO(sumPureWithLogging2(4, 5))
runIO(sumPureWithLogging2(2, 3))
runIO(negPureWithLogging2(8))
/*:
But now it is not possible to do composition because types do not match.
This will not compile:
negPureWithLogging2(sumPureWithLogging2(4, 5))
We will have to define a special compose operator to solve the problem (`bind`/`flatMap`).
LoggingInstruction needs to be able to combine multiple logs:
*/
enum LoggingInstruction2 {
case Info(msg: String)
case Warn(msg: String)
case Debug(msg: String)
// Added to be able to do composition
case MultiLog(logs: [LoggingInstruction2])
var description: String {
switch self {
case let .Info(msg: msg):
return "Info(\(msg))"
case let .Warn(msg: msg):
return "Warn(\(msg))"
case let .Debug(msg: msg):
return "Debug(\(msg))"
case let .MultiLog(logs: logs):
return "Multi(\(logs.map({ $0.description })))"
}
}
}
LoggingInstruction2.MultiLog(logs: [LoggingInstruction2.Info(msg: "info1"), LoggingInstruction2.Warn(msg: "warn1")]).description
//: Implementation of the `bind`/`flatMap` operator:
struct Logging2<T> {
var log: LoggingInstruction2
var result: T
func bind<U>(f: T -> Logging2<U>) -> Logging2<U> {
let logging = f(result)
return Logging2<U>(log: LoggingInstruction2.MultiLog(logs: [log, logging.log]), result: logging.result)
}
var description: String {
return "(\(log.description), \(result)"
}
}
let sumPureWithLogging3 = { (x: Int, y: Int) -> Logging2<Int> in
return Logging2<Int>(log: LoggingInstruction2.Info(msg: "\(x) + \(y)"), result: x+y)
}
let negPureWithLogging3 = { (x: Int) -> Logging2<Int> in
return Logging2<Int>(log: LoggingInstruction2.Warn(msg: "Neg \(x)"), result: -x)
}
//: Now we can do composition and it will contain all the information (result of the operation and composition of the logging effects):
sumPureWithLogging3(4, 5).bind(negPureWithLogging3).description
/*:
There are other composition operators:
* E.g. `pure` will encapsulate a value into something with effects, but the effect will be empty:
*/
func pure<T>(t: T) -> Logging2<T> {
return Logging2<T>(log: LoggingInstruction2.MultiLog(logs: []), result: t)
}
pure(10).description
|
de189d6c23a25e1ee0be24ff1f5a98dd
| 28.348259 | 135 | 0.686218 | false | false | false | false |
corchwll/amos-ss15-proj5_ios
|
refs/heads/master
|
MobileTimeAccounting/Model/Profile.swift
|
agpl-3.0
|
1
|
/*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
class Profile
{
var firstname: String
var lastname: String
var employeeId: String
var weeklyWorkingTime: Int
var totalVacationTime: Int
var currentVacationTime: Int
var currentOvertime: Int
var registrationDate: NSDate
/*
Constructor for model class, representing a profile.
@methodtype Constructor
@pre -
@post Initialized profile
*/
init(firstname: String, lastname: String, employeeId: String, weeklyWorkingTime: Int, totalVacationTime: Int, currentVacationTime: Int, currentOvertime: Int)
{
self.firstname = firstname
self.lastname = lastname
self.employeeId = employeeId
self.weeklyWorkingTime = weeklyWorkingTime
self.totalVacationTime = totalVacationTime
self.currentVacationTime = currentVacationTime
self.currentOvertime = currentOvertime
self.registrationDate = NSDate()
}
/*
Constructor for model class, representing a profile.
@methodtype Constructor
@pre -
@post Initialized profile
*/
convenience init(firstname: String, lastname: String, employeeId: String, weeklyWorkingTime: Int, totalVacationTime: Int, currentVacationTime: Int, currentOvertime: Int, registrationDate: NSDate)
{
self.init(firstname: firstname, lastname: lastname, employeeId: employeeId, weeklyWorkingTime: weeklyWorkingTime, totalVacationTime: totalVacationTime, currentVacationTime: currentVacationTime, currentOvertime: currentOvertime)
self.registrationDate = registrationDate
}
/*
Asserts wether id is valid or not(consists only of digits of length 5).
@methodtype Assertion
@pre -
@post -
*/
static func isValidId(id: String)->Bool
{
return id.toInt() != nil && count(id) == 5
}
/*
Asserts wether weekly working time is valid or not(must be a number between 10 and 50).
@methodtype Assertion
@pre -
@post -
*/
static func isValidWeeklyWorkingTime(weeklyWorkingTime: String)->Bool
{
if let time = weeklyWorkingTime.toInt()
{
return time >= 10 && time <= 50
}
return false
}
/*
Asserts wether total vacation time is valid or not(must be a number between 0 and 40).
@methodtype Assertion
@pre -
@post -
*/
static func isValidTotalVacationTime(totalVacationTime: String)->Bool
{
if let time = totalVacationTime.toInt()
{
return time >= 0 && time <= 40
}
return false
}
/*
Asserts wether current vacation time is valid or not(must be a number greater or equals 0).
@methodtype Assertion
@pre -
@post -
*/
static func isValidCurrentVacationTime(currentVacationTime: String)->Bool
{
if let time = currentVacationTime.toInt()
{
return time >= 0
}
return false
}
/*
Asserts wether current over time is valid or not(must be a number).
@methodtype Assertion
@pre -
@post -
*/
static func isValidCurrentOvertime(currentOvertime: String)->Bool
{
if let time = currentOvertime.toInt()
{
return true
}
return false
}
/*
Returns string representation of user profile
@methodtype Convertion
@pre -
@post String representation of user profile
*/
func asString()->String
{
return "\(firstname) \(lastname); \(employeeId); \(weeklyWorkingTime); \(totalVacationTime); \(currentVacationTime); \(currentOvertime)"
}
}
|
945ae2096d3759366c31ab8c8a55df10
| 27.8 | 235 | 0.624484 | false | false | false | false |
RyanTech/cannonball-ios
|
refs/heads/master
|
Cannonball/SignInViewController.swift
|
apache-2.0
|
3
|
//
// Copyright (C) 2014 Twitter, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import TwitterKit
import DigitsKit
import Crashlytics
class SignInViewController: UIViewController, UIAlertViewDelegate {
// MARK: Properties
@IBOutlet weak var logoView: UIImageView!
@IBOutlet weak var signInTwitterButton: UIButton!
@IBOutlet weak var signInPhoneButton: UIButton!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Color the logo.
logoView.image = logoView.image?.imageWithRenderingMode(.AlwaysTemplate)
logoView.tintColor = UIColor(red: 0, green: 167/255, blue: 155/255, alpha: 1)
// Decorate the Sign In with Twitter and Phone buttons.
let defaultColor = signInPhoneButton.titleLabel?.textColor
decorateButton(signInTwitterButton, color: UIColor(red: 0.333, green: 0.675, blue: 0.933, alpha: 1))
decorateButton(signInPhoneButton, color: defaultColor!)
// Add custom image to the Sign In with Phone button.
let image = UIImage(named: "Phone")?.imageWithRenderingMode(.AlwaysTemplate)
signInPhoneButton.setImage(image, forState: .Normal)
}
private func navigateToMainAppScreen() {
performSegueWithIdentifier("ShowThemeChooser", sender: self)
}
// MARK: IBActions
@IBAction func signInWithTwitter(sender: UIButton) {
Twitter.sharedInstance().logInWithCompletion { session, error in
if session != nil {
// Navigate to the main app screen to select a theme.
self.navigateToMainAppScreen()
// Tie crashes to a Twitter user ID and username in Crashlytics.
Crashlytics.sharedInstance().setUserIdentifier(session.userID)
Crashlytics.sharedInstance().setUserName(session.userName)
// Log Answers Custom Event.
Answers.logLoginWithMethod("Twitter", success: true, customAttributes: ["User ID": session.userID])
} else {
// Log Answers Custom Event.
Answers.logLoginWithMethod("Twitter", success: false, customAttributes: ["Error": error.localizedDescription])
}
}
}
@IBAction func signInWithPhone(sender: UIButton) {
// Create a Digits appearance with Cannonball colors.
let appearance = DGTAppearance()
appearance.backgroundColor = UIColor.cannonballBeigeColor()
appearance.accentColor = UIColor.cannonballGreenColor()
// Start the Digits authentication flow with the custom appearance.
Digits.sharedInstance().authenticateWithDigitsAppearance(appearance, viewController: nil, title: nil) { session, error in
if session != nil {
// Navigate to the main app screen to select a theme.
self.navigateToMainAppScreen()
// Tie crashes to a Digits user ID in Crashlytics.
Crashlytics.sharedInstance().setUserIdentifier(session.userID)
// Log Answers Custom Event.
Answers.logLoginWithMethod("Digits", success: true, customAttributes: ["User ID": session.userID])
} else {
// Log Answers Custom Event.
Answers.logLoginWithMethod("Digits", success: false, customAttributes: ["Error": error.localizedDescription])
}
}
}
@IBAction func skipSignIn(sender: AnyObject) {
// Log Answers Custom Event.
Answers.logCustomEventWithName("Skipped Sign In", customAttributes: nil)
}
// MARK: Utilities
private func decorateButton(button: UIButton, color: UIColor) {
// Draw the border around a button.
button.layer.masksToBounds = false
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 2
button.layer.cornerRadius = 6
}
}
|
770dee94ff6d5105e9e21277d7f7295c
| 37.826087 | 129 | 0.665174 | false | false | false | false |
timd/Flashcardr
|
refs/heads/master
|
Flashcards/Card.swift
|
mit
|
1
|
//
// Card.swift
// Flashcards
//
// Created by Tim on 22/07/15.
// Copyright (c) 2015 Tim Duckett. All rights reserved.
//
import RealmSwift
class Card: Object {
dynamic var uid: Int = 0
dynamic var sortOrder: Int = 0
dynamic var deutsch: String = ""
dynamic var englisch: String = ""
dynamic var score: Int = 0
let sections = List<Section>()
}
|
c73281e15289e74d0d00d9bdf2d09ef9
| 17.47619 | 56 | 0.615979 | false | false | false | false |
GrouponChina/groupon-up
|
refs/heads/master
|
Groupon UP/Groupon UP/UPConstants.swift
|
apache-2.0
|
1
|
//
// UPConstants.swift
// Groupon UP
//
// Created by Robert Xue on 11/21/15.
// Copyright © 2015 Chang Liu. All rights reserved.
//
import UIKit
let UPBackgroundColor = UIColor.whiteColor()
let UPTintColor = UIColor(rgba: "#82b548")
let UPSpanSize = 15
let UPPrimaryTextColor = UIColor(rgba: "#333333")
let UPSecondaryTextColor = UIColor(rgba: "#666666")
let UPDangerZoneColor = UIColor(rgba: "#df3e3e")
let UPTextColorOnDardBackground = UIColor(rgba: "#f2f2f2")
let UPContentFont = UIFont(name: "Avenir", size: 17)!
let UPBorderRadius: CGFloat = 5
let UPBorderWidth: CGFloat = 1.0
let UPContainerMargin = 8
//Groupon Color
let UPBackgroundGrayColor = UIColor(rgba: "#f2f2f2")
let UPDarkGray = UIColor(rgba: "#666666")
let UPUrgencyOrange = UIColor(rgba: "#e35205")
//font
let UPFontBold = "HelveticaNeue-Bold"
let UPFont = "HelveticaNeue"
|
e751d088e8484324d16aa4d6a9227639
| 26.451613 | 58 | 0.737955 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
refs/heads/master
|
SmartReceipts/Reports/Generators/ReportGenerator.swift
|
agpl-3.0
|
2
|
//
// ReportGenerator.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 03/12/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
typealias CategoryReceipts = (category: WBCategory, receipts: [WBReceipt])
@objcMembers
class ReportGenerator: NSObject {
private(set) var trip: WBTrip!
private(set) var database: Database!
init(trip: WBTrip, database: Database) {
self.trip = trip
self.database = database
}
func generateTo(path: String) -> Bool {
abstractMethodError()
return false
}
func receiptColumns() -> [ReceiptColumn] {
abstractMethodError()
return []
}
func categoryColumns() -> [CategoryColumn] {
return CategoryColumn.allColumns()
}
func distanceColumns() -> [DistanceColumn] {
return DistanceColumn.allColumns() as! [DistanceColumn]
}
func receipts() -> [WBReceipt] {
var receipts = database.allReceipts(for: trip, ascending: true) as! [WBReceipt]
receipts = receipts.filter { !$0.isMarkedForDeletion }
return ReceiptIndexer.indexReceipts(receipts, filter: { WBReportUtils.filterOutReceipt($0) })
}
func distances() -> [Distance] {
let distances = database.fetchedAdapterForDistances(in: trip, ascending: true)
return distances?.allObjects() as! [Distance]
}
func receiptsByCategories() -> [CategoryReceipts] {
var result = [WBCategory: [WBReceipt]]()
let receipts = self.receipts()
receipts.forEach {
guard let category = $0.category else { return }
if result[category] == nil {
result[category] = []
}
result[category]?.append($0)
}
if WBPreferences.printDailyDistanceValues() {
let dReceipts = DistancesToReceiptsConverter.convertDistances(distances()) as! [WBReceipt]
if let category = dReceipts.first?.category {
result[category] = dReceipts
}
}
return result
.filter { !$0.value.isEmpty }
.sorted { $0.key.customOrderId < $1.key.customOrderId }
.map { ($0.key, $0.value) }
}
}
fileprivate func abstractMethodError() { fatalError("Abstract Method") }
|
c9d4341478e067d06e78f1a363dfc366
| 29.230769 | 102 | 0.603478 | false | false | false | false |
onebytecode/krugozor-iOSVisitors
|
refs/heads/develop
|
krugozor-visitorsApp/OnboardPageVC.swift
|
apache-2.0
|
1
|
//
// OnboardPageVC.swift
// krugozor-visitorsApp
//
// Created by Stanly Shiyanovskiy on 27.09.17.
// Copyright © 2017 oneByteCode. All rights reserved.
//
import UIKit
class OnboardPageVC: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource {
static func storyboardInstance() -> OnboardPageVC? {
let storyboard = UIStoryboard(name: String(describing: self), bundle: nil)
return storyboard.instantiateInitialViewController() as? OnboardPageVC
}
// MARK: - Properties -
let contentImages = [("Onboard_1", "Landing Page #1."), ("Onboard_2", "Landing Page #2.")]
// MARK: - Outlets -
override func viewDidLoad() {
self.delegate = self
self.dataSource = self
if contentImages.count > 0 {
let firstController = getItemController(0)!
let startingViewControllers = [firstController]
self.setViewControllers(startingViewControllers, direction: .forward, animated: false, completion: nil)
}
setupPageControl()
}
func setupPageControl() {
self.view.backgroundColor = UIColor.white
let appearance = UIPageControl.appearance()
appearance.pageIndicatorTintColor = UIColor.CustomColors.second
appearance.currentPageIndicatorTintColor = UIColor.CustomColors.first
appearance.backgroundColor = UIColor.white
}
// MARK: - UIPageViewControllerDataSource methods -
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let itemController = viewController as! OnboardTemplateVC
if itemController.itemIndex > 0 {
return getItemController(itemController.itemIndex - 1)
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let itemController = viewController as? OnboardTemplateVC {
if itemController.itemIndex + 1 < contentImages.count {
return getItemController(itemController.itemIndex + 1)
} else if itemController.itemIndex + 1 == contentImages.count {
let itemController2 = LogInVC.storyboardInstance()!
return getItemController(itemController2.itemIndex + contentImages.count)
}
}
return nil
}
func getItemController(_ itemIndex: Int) -> UIViewController? {
if itemIndex < contentImages.count {
if let pageVC = OnboardTemplateVC.storyboardInstance() {
pageVC.itemIndex = itemIndex
pageVC.contentModel = contentImages[itemIndex]
return pageVC
}
} else if itemIndex == contentImages.count {
if let loginVC = LogInVC.storyboardInstance() {
return loginVC
}
}
return nil
}
// MARK: - Page Indicator -
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return contentImages.count + 1
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
// MARK: - Additions -
func currentControllerIndex() -> Int {
let pageItemController = self.currentController()
if let controller = pageItemController as? OnboardTemplateVC {
return controller.itemIndex
}
return -1
}
func currentController() -> UIViewController? {
if (self.viewControllers?.count)! > 0 {
return self.viewControllers![0]
}
return nil
}
}
|
bdbe542509681fe1e3cecbdaa3d6ee5e
| 35.171429 | 149 | 0.64218 | false | false | false | false |
wftllc/hahastream
|
refs/heads/master
|
Haha Stream/HahaService/Models/ContentItem.swift
|
mit
|
1
|
import Foundation
class ContentItem: NSObject, FromDictable {
public var game: Game?
public var channel: Channel?
static func fromDictionary(_ dict:[String: Any]?) throws -> Self {
guard let dict = dict else { throw FromDictableError.keyError(key: "\(self).<root>") }
let kind: String = try dict.value("kind")
if kind == "channel" {
return self.init(channel: try Channel.fromDictionary(dict))
}
else if kind == "game" {
return self.init(game: try Game.fromDictionary(dict))
}
else {
throw FromDictableError.keyError(key: "kind unrecognized \(kind)")
}
}
required init(game: Game? = nil, channel: Channel? = nil) {
self.game = game
self.channel = channel
}
override var description: String {
if let g = game {
return g.description
}
else {
return channel!.description
}
}
override func isEqual(_ object: Any?) -> Bool {
guard let item = object as? ContentItem else {
return false
}
if self.game != nil {
return item.game?.uuid == self.game?.uuid
}
else if self.channel != nil {
return item.channel?.uuid == self.channel?.uuid
}
else {
return false
}
}
}
|
564918f63b476f7a5225b8d32a393353
| 22.346939 | 88 | 0.656469 | false | false | false | false |
SteveRohrlack/CitySimCore
|
refs/heads/master
|
src/Model/City/City.swift
|
mit
|
1
|
//
// City.swift
// CitySimCore
//
// Created by Steve Rohrlack on 24.05.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import Foundation
/// the simulation's main data container
public class City: EventEmitting, ActorStageable {
typealias EventNameType = CityEvent
/// Container holding event subscribers
var eventSubscribers: [EventNameType: [EventSubscribing]] = [:]
/// CityMap, regards all layers of the map
public var map: CityMap
/// current population count
public var population: Int {
didSet {
emitPopulationThresholdEvents(oldValue: oldValue)
}
}
/// list of population thresholds that trigger events
private var populationThresholds: [Int] = []
/// City budget
public var budget: Budget
/// City Ressources
public var ressources: Ressources
/**
initializer
- parameter map: CityMap
- parameter budget: city budget
- parameter population: city population
- parameter populationThresholds: population thresholds that trigger events
*/
init(map: CityMap, budget: Budget, ressources: Ressources, population: Int, populationThresholds: [Int]) {
self.map = map
self.budget = budget
self.ressources = ressources
self.population = population
self.populationThresholds = populationThresholds
}
/**
convenience initializer
- parameter map: CityMap
- parameter startingBudget: starting budget
- parameter populationThresholds: population thresholds that trigger events
*/
convenience init(map: CityMap, startingBudget: Int) {
let budget = Budget(amount: startingBudget, runningCost: 0)
let ressources = Ressources(electricityDemand: 0, electricitySupply: 0, electricityNeedsRecalculation: false)
self.init(map: map, budget: budget, ressources: ressources, population: 0, populationThresholds: [])
}
/**
convenience initializer
- parameter map: CityMap
- parameter startingBudget: starting budget
*/
convenience init(map: CityMap, startingBudget: Int, populationThresholds: [Int]) {
let budget = Budget(amount: startingBudget, runningCost: 0)
let ressources = Ressources(electricityDemand: 0, electricitySupply: 0, electricityNeedsRecalculation: false)
self.init(map: map, budget: budget, ressources: ressources, population: 0, populationThresholds: populationThresholds)
}
/**
determines if city population threshold event should be triggered
- parameter oldValue: value before population-value was changed
*/
private func emitPopulationThresholdEvents(oldValue oldValue: Int) {
for threshold in populationThresholds {
if oldValue < threshold && population >= threshold {
do {
try emit(event: .PopulationReachedThreshold, payload: threshold)
} catch {}
}
}
}
}
|
bc4b4438103cdd5a9a3330a7222e4ed3
| 31.104167 | 126 | 0.657903 | false | false | false | false |
fanyinan/ImagePickerProject
|
refs/heads/master
|
ImagePicker/Tool/Extension.swift
|
bsd-2-clause
|
1
|
//
// MuColor.swift
// ImagePickerProject
//
// Created by 范祎楠 on 15/4/9.
// Copyright (c) 2015年 范祎楠. All rights reserved.
//
import UIKit
extension UIColor {
class var jx_main: UIColor { return UIColor(hex: 0x333333) }
class var separatorColor: UIColor { return UIColor(hex: 0xe5e5e5) }
convenience init(hex: Int, alpha: CGFloat = 1) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0x00FF00) >> 8) / 255.0
let blue = CGFloat((hex & 0x0000FF)) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
随机颜色
- returns: 颜色
*/
class func randomColor() -> UIColor{
let hue = CGFloat(arc4random() % 256) / 256.0
let saturation = CGFloat(arc4random() % 128) / 256.0 + 0.5
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256.0 + 0.5
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}
}
extension UIImage {
//旋转rect
func transformOrientationRect(_ rect: CGRect) -> CGRect {
var rectTransform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case .left:
rectTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)).translatedBy(x: 0, y: -size.height)
case .right:
rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: 0)
case .down:
rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: -size.height)
default:
break
}
let orientationRect = rect.applying(rectTransform.scaledBy(x: scale, y: scale))
return orientationRect
}
}
|
df54ea0719e9fc2b609a5751e955fd18
| 26.0625 | 125 | 0.646651 | false | false | false | false |
crossroadlabs/ExpressCommandLine
|
refs/heads/master
|
swift-express/Commands/Run/RunSPM.swift
|
gpl-3.0
|
1
|
//===--- RunSPM.swift ----------------------------------------------------------===//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express Command Line
//
//Swift Express Command Line is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express Command Line is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Swift Express Command Line. If not, see <http://www.gnu.org/licenses/>.
//
//===---------------------------------------------------------------------------===//
import Foundation
import Result
infix operator ++ {}
func ++ <K,V> (left: Dictionary<K,V>, right: Dictionary<K,V>?) -> Dictionary<K,V> {
guard let right = right else { return left }
return left.reduce(right) {
var new = $0 as [K:V]
new.updateValue($1.1, forKey: $1.0)
return new
}
}
struct RunSPMStep : RunSubtaskStep {
let dependsOn:[Step] = []
func run(params: [String: Any], combinedOutput: StepResponse) throws -> [String: Any] {
guard let path = params["path"] as? String else {
throw SwiftExpressError.BadOptions(message: "RunSPM: No path option.")
}
guard let buildType = params["buildType"] as? BuildType else {
throw SwiftExpressError.BadOptions(message: "RunSPM: No buildType option.")
}
print ("Running app...")
let binaryPath = path.addPathComponent(".build").addPathComponent(buildType.spmValue).addPathComponent("app")
try executeSubtaskAndWait(SubTask(task: binaryPath, arguments: nil, workingDirectory: path, environment: nil, useAppOutput: true))
return [String:Any]()
}
func cleanup(params: [String : Any], output: StepResponse) throws {
}
// func callParams(ownParams: [String : Any], forStep: Step, previousStepsOutput: StepResponse) throws -> [String : Any] {
// return ownParams ++ ["force": false, "dispatch": DEFAULTS_BUILD_DISPATCH]
// }
}
|
ab58a59e3f08e8a36658380f9e50013a
| 38.435484 | 138 | 0.625205 | false | false | false | false |
vedantb/WatchkitMusic
|
refs/heads/master
|
PlayThatSong/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// PlayThatSong
//
// Created by Vedant Bhatt on 1/29/15.
// Copyright (c) 2015 Vedant. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var currentSongLabel: UILabel!
var audioSession: AVAudioSession!
//var audioPlayer: AVAudioPlayer!
var audioQueuePlayer: AVQueuePlayer!
var currentSongIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureAudioSession()
//self.configureAudioPlayer()
self.configureAudioQueuePlayer()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleRequest:"), name: "WatchKitDidMakeRequest", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Mark - IBActions
@IBAction func playButtonPressed(sender: UIButton) {
self.playMusic()
self.updateUI()
}
@IBAction func playPreviousButtonPressed(sender: UIButton) {
if currentSongIndex > 0 {
self.audioQueuePlayer.pause()
self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
let temporaryNowPlayingIndex = currentSongIndex
let temporaryPlaylist = self.createSongs()
self.audioQueuePlayer.removeAllItems()
for var index = temporaryNowPlayingIndex - 1; index < temporaryPlaylist.count; index++ {
self.audioQueuePlayer.insertItem(temporaryPlaylist[index] as AVPlayerItem, afterItem: nil)
}
self.currentSongIndex = temporaryNowPlayingIndex - 1;
self.audioQueuePlayer.seekToTime(kCMTimeZero, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)
self.audioQueuePlayer.play()
}
self.updateUI()
}
@IBAction func playNextButtonPressed(sender: UIButton) {
self.audioQueuePlayer.advanceToNextItem()
self.currentSongIndex = self.currentSongIndex + 1
self.updateUI()
}
//Mark - Audio
func configureAudioSession() {
self.audioSession = AVAudioSession.sharedInstance()
var categoryError:NSError?
var activeError:NSError?
self.audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &categoryError)
println("error \(categoryError)")
var success = self.audioSession.setActive(true, error: &activeError)
if !success {
println("Error making audio session active \(activeError)")
}
}
// func configureAudioPlayer() {
// var songPath = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3")
// var songURL = NSURL.fileURLWithPath(songPath!)
// println("songURL: \(songURL)")
// var songError: NSError?
// self.audioPlayer = AVAudioPlayer(contentsOfURL: songURL, error: &songError)
// println("song error: \(songError)")
// self.audioPlayer.numberOfLoops = 0
// }
func configureAudioQueuePlayer() {
let songs = createSongs()
self.audioQueuePlayer = AVQueuePlayer(items: songs)
for var songIndex = 0; songIndex < songs.count; songIndex++ {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "songEnded:", name: AVPlayerItemDidPlayToEndTimeNotification, object: songs[songIndex])
}
}
func playMusic() {
//was used to implement audio player. Later replaced with AudioQueuePlayer
// self.audioPlayer.prepareToPlay()
// self.audioPlayer.play()
if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil {
self.audioQueuePlayer.pause()
} else if currentSongIndex == nil {
self.audioQueuePlayer.play()
self.currentSongIndex = 0
} else {
self.audioQueuePlayer.play()
}
}
func createSongs () -> [AnyObject] {
let firstSongPath = NSBundle.mainBundle().pathForResource("CLASSICAL SOLITUDE", ofType: "wav")
let secondSongPath = NSBundle.mainBundle().pathForResource("Timothy Pinkham - The Knolls of Doldesh", ofType: "mp3")
let thirdSongPath = NSBundle.mainBundle().pathForResource("Open Source - Sending My Signal", ofType: "mp3")
let firstSongURL = NSURL.fileURLWithPath(firstSongPath!)
let secondSongURL = NSURL.fileURLWithPath(secondSongPath!)
let thirdSongURL = NSURL.fileURLWithPath(thirdSongPath!)
let firstPlayItem = AVPlayerItem(URL: firstSongURL)
let secondPlayItem = AVPlayerItem(URL: secondSongURL)
let thirdPlayItem = AVPlayerItem(URL: thirdSongURL)
let songs: [AnyObject] = [firstPlayItem, secondPlayItem, thirdPlayItem]
return songs
}
//Mark: Audio Notification
func songEnded (notification: NSNotification){
self.currentSongIndex = self.currentSongIndex + 1
self.updateUI()
}
//Mark: UI Update Helpers
func updateUI () {
self.currentSongLabel.text = currentSongName()
if audioQueuePlayer.rate > 0 && audioQueuePlayer.error == nil {
self.playButton.setTitle("Pause", forState: UIControlState.Normal)
}
else {
self.playButton.setTitle("Play", forState: UIControlState.Normal)
}
}
func currentSongName () -> String {
var currentSong: String
if currentSongIndex == 0{
currentSong = "Classical Solitude"
}
else if currentSongIndex == 1 {
currentSong = "The Knolls of Doldesh"
}
else if currentSongIndex == 2 {
currentSong = "Sending my Signal"
}
else {
currentSong = "No Song Playing"
println("Someting went wrong!")
}
return currentSong
}
//Mark - WatchKit Notification
func handleRequest(notification: NSNotification) {
let watchKitInfo = notification.object! as? WatchKitInfo
if watchKitInfo.playerRequest != nil {
let requestedAction: String = watchKitInfo.playerRequest!
self.playMusic()
}
}
}
|
5f4385c047732fd1d767873cb4ca540e
| 33.533679 | 164 | 0.626707 | false | false | false | false |
ZwxWhite/V2EX
|
refs/heads/master
|
V2EX/V2EX/Class/Model/V2Reply.swift
|
mit
|
1
|
//
// V2Replies.swift
// V2EX
//
// Created by wenxuan.zhang on 16/2/24.
// Copyright © 2016年 张文轩. All rights reserved.
//
import Foundation
import SwiftyJSON
class V2Reply {
var id: Int?
var thanks: Int?
var content: String?
var content_rendered: String?
var member: V2Member?
var created: Int?
var last_modified: Int?
init(json: JSON) {
self.id = json["id"].int
self.thanks = json["thanks"].int
self.content = json["content"].string
self.content_rendered = json["content_rendered"].string
self.created = json["created"].int
self.last_modified = json["last_modified"].int
self.member = V2Member(json: json["member"])
}
}
|
65419c86eee9abac4dd550a350b8ef2f
| 22.09375 | 63 | 0.603518 | false | false | false | false |
msn0w/bgsights
|
refs/heads/master
|
bgSights/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// bgSights
//
// Created by Deyan Marinov on 1/8/16.
// Copyright © 2016 Deyan Marinov. All rights reserved.
//
import UIKit
class ViewController: UITableViewController, MenuTransitionManagerDelegate {
let menuTransitionManager = MenuTransitionManager()
var introModalDidDisplay = NSUserDefaults.standardUserDefaults().boolForKey("introModalDidDisplay")
override func viewDidLoad() {
super.viewDidLoad()
if NSUserDefaults.standardUserDefaults().isFirstLaunch() {
let walkVC = self.storyboard?.instantiateViewControllerWithIdentifier("walk0") as! WalkthroughVC
walkVC.modalPresentationStyle = UIModalPresentationStyle.FormSheet
self.presentViewController(walkVC, animated: true, completion: nil)
}
self.title = "Начало"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dismiss() {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Navigation
@IBAction func unwindToHome(segue: UIStoryboardSegue) {
let sourceController = segue.sourceViewController as! MenuTableViewController
self.title = sourceController.currentItem
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let menuTableViewController = segue.destinationViewController as! MenuTableViewController
menuTableViewController.currentItem = self.title!
menuTableViewController.transitioningDelegate = menuTransitionManager
menuTransitionManager.delegate = self
}
}
extension NSUserDefaults {
func isFirstLaunch() -> Bool {
if !NSUserDefaults.standardUserDefaults().boolForKey("LaunchedOnce") {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "LaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
return true
}
return false
}
}
|
4ade880d968f7a543a92b070d2819afc
| 33.081967 | 108 | 0.698268 | false | false | false | false |
Vazzi/VJAutocomplete
|
refs/heads/master
|
VJAutocompleteSwiftDemo/VJAutocompleteSwiftDemo/VJAutocomplete.swift
|
mit
|
2
|
//
// VJAutocomplete.m
//
// Created by Jakub Vlasák on 14/09/14.
// Copyright (c) 2014 Jakub Vlasak ( http://vlasakjakub.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
/*! Protocol for manipulation with data
*/
protocol VJAutocompleteDataSource {
/*! Set the text of cell with given data. Data can be any object not only string.
Always return the parameter cell. Only set text. ([cell.textLabel setText:])
/param cell
/param item Source data. Data can be any object not only string that is why you have to define the cell text.
/return cell that has been given and modified
*/
func setCell(cell:UITableViewCell, withItem item:AnyObject) -> UITableViewCell
/*! Define data that should by shown by autocomplete on substring. Can be any object. Not only NSString.
/param substring
/return array of objects for substring
*/
func getItemsArrayWithSubstring(substring:String) -> [AnyObject]
}
/*! Protocol for manipulation with VJAutocomplete
*/
protocol VJAutocompleteDelegate {
/*! This is called when row was selected and autocomplete add text to text field.
/param rowIndex Selected row number
*/
func autocompleteWasSelectedRow(rowIndex: Int)
}
/*! VJAutocomplete table for text field is pinned to the text field that must be given. User starts
writing to the text field and VJAutocomplete show if has any suggestion. If there is no
suggestion then hide. User can choose suggestion by clicking on it. If user choose any suggestion
then it diseppeared and add text to text field. If user continues adding text then
VJAutocomplete start showing another suggestions or diseppead if has no.
*/
class VJAutocomplete: UITableView, UITableViewDelegate, UITableViewDataSource {
// -------------------------------------------------------------------------------
// MARK: - Public properties
// -------------------------------------------------------------------------------
// Set by init
var textField: UITextField! //!< Given text field. To this text field is autocomplete pinned to.
var parentView: UIView? //!< Parent view of text field (Change only if the current view is not what you want)
// Actions properties
var doNotShow = false //!< Do not show autocomplete
// Other properties
var maxVisibleRowsCount:UInt = 2 //!< Maximum height of autocomplete based on max visible rows
var cellHeight:CGFloat = 44.0 //!< Cell height
var minCountOfCharsToShow:UInt = 3 //!< Minimum count of characters needed to show autocomplete
var autocompleteDataSource:VJAutocompleteDataSource? //!< Manipulation with data
var autocompleteDelegate:VJAutocompleteDelegate? //!< Manipulation with autocomplete
// -------------------------------------------------------------------------------
// MARK: - Private properties
// -------------------------------------------------------------------------------
private let cellIdentifier = "VJAutocompleteCellIdentifier"
private var lastSubstring:String = "" //!< Last given substring
private var autocompleteItemsArray = [AnyObject]() //!< Current suggestions
private var autocompleteSearchQueue = dispatch_queue_create("VJAutocompleteQueue",
DISPATCH_QUEUE_SERIAL); //!< Queue for searching suggestions
private var isVisible = false //<! Is autocomplete visible
// -------------------------------------------------------------------------------
// MARK: - Init methods
// -------------------------------------------------------------------------------
init(textField: UITextField) {
super.init(frame: textField.frame, style: UITableViewStyle.Plain);
// Text field
self.textField = textField;
// Set parent view as text field super view
self.parentView = textField.superview;
// Setup table view
setupTableView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
// -------------------------------------------------------------------------------
// MARK: - Setups
// -------------------------------------------------------------------------------
private func setupTableView() {
// Protocols
dataSource = self;
delegate = self;
// Properties
scrollEnabled = true;
// Visual properties
backgroundColor = UIColor.whiteColor();
rowHeight = cellHeight;
// Empty footer
tableFooterView = UIView(frame: CGRectZero);
}
// -------------------------------------------------------------------------------
// MARK: - Public methods
// -------------------------------------------------------------------------------
func setBorder(width: CGFloat, cornerRadius: CGFloat, color: UIColor) {
self.layer.borderWidth = width;
self.layer.cornerRadius = cornerRadius;
self.layer.borderColor = color.CGColor;
}
func searchAutocompleteEntries(WithSubstring substring: NSString) {
let lastCount = autocompleteItemsArray.count;
autocompleteItemsArray.removeAll(keepCapacity: false);
// If substring has less than min. characters then hide and return
if (UInt(substring.length) < minCountOfCharsToShow) {
hideAutocomplete();
return;
}
let substringBefore = lastSubstring;
lastSubstring = substring as String;
// If substring is the same as before and before it has no suggestions then
// do not search for suggestions
if (substringBefore == substring.substringToIndex(substring.length - 1) &&
lastCount == 0 &&
!substringBefore.isEmpty) {
return;
}
dispatch_async(autocompleteSearchQueue) { ()
// Save new suggestions
if let dataArray = self.autocompleteDataSource?.getItemsArrayWithSubstring(substring as String) {
self.autocompleteItemsArray = dataArray;
}
// Call show or hide autocomplete and reload data on main thread
dispatch_async(dispatch_get_main_queue()) { ()
if (self.autocompleteItemsArray.count != 0) {
self.showAutocomplete();
} else {
self.hideAutocomplete();
}
self.reloadData();
}
}
}
func hideAutocomplete() {
if (!isVisible) {
return;
}
removeFromSuperview();
isVisible = false;
}
func showAutocomplete() {
if (doNotShow) {
return;
}
if (isVisible) {
removeFromSuperview();
}
self.isVisible = true;
var origin = getTextViewOrigin();
setFrame(origin, height: computeHeight());
layer.zPosition = CGFloat(FLT_MAX);
parentView?.addSubview(self);
}
func shouldChangeCharacters(InRange range: NSRange, replacementString string: String) {
var substring = NSString(string: textField.text);
substring = substring.stringByReplacingCharactersInRange(range, withString: string);
searchAutocompleteEntries(WithSubstring: substring);
}
func isAutocompleteVisible() -> Bool {
return isVisible;
}
// -------------------------------------------------------------------------------
// MARK: - UITableView data source
// -------------------------------------------------------------------------------
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocompleteItemsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell!;
if let oldCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell {
cell = oldCell;
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier);
}
var newCell = autocompleteDataSource?.setCell(cell, withItem: autocompleteItemsArray[indexPath.row])
return cell
}
// -------------------------------------------------------------------------------
// MARK: - UITableView delegate
// -------------------------------------------------------------------------------
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the cell
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
// Set text to
textField.text = selectedCell?.textLabel!.text
// Call delegate method
autocompleteDelegate?.autocompleteWasSelectedRow(indexPath.row)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight
}
// -------------------------------------------------------------------------------
// MARK: - Private
// -------------------------------------------------------------------------------
private func computeHeight() -> CGFloat {
// Set number of cells (do not show more than maxSuggestions)
var visibleRowsCount = autocompleteItemsArray.count as NSInteger;
if (visibleRowsCount > NSInteger(maxVisibleRowsCount)) {
visibleRowsCount = NSInteger(maxVisibleRowsCount);
}
// Calculate autocomplete height
let height = cellHeight * CGFloat(visibleRowsCount);
return height;
}
private func getTextViewOrigin() -> CGPoint {
var textViewOrigin: CGPoint;
if (parentView?.isEqual(textField.superview) != nil) {
textViewOrigin = textField.frame.origin;
} else {
textViewOrigin = textField.convertPoint(textField.frame.origin,
toView: parentView);
}
return textViewOrigin;
}
private func setFrame(textViewOrigin: CGPoint, height: CGFloat) {
var newFrame = CGRectMake(textViewOrigin.x, textViewOrigin.y + CGRectGetHeight(textField.bounds),
CGRectGetWidth(textField.bounds), height);
frame = newFrame;
}
}
|
2482806afa067449cfe79a8105c746c6
| 37.220395 | 123 | 0.577933 | false | false | false | false |
wenghengcong/Coderpursue
|
refs/heads/master
|
BeeFun/BeeFun/View/BaseViewController/BFBaseViewController.swift
|
mit
|
1
|
//
// BFBaseViewController.swift
// BeeFun
//
// Created by wenghengcong on 15/12/30.
// Copyright © 2015年 JungleSong. All rights reserved.
//
import UIKit
import MJRefresh
protocol BFViewControllerNetworkProtocol: class {
func networkSuccssful()
func networkFailure()
}
class BFBaseViewController: UIViewController, UIGestureRecognizerDelegate {
typealias PlaceHolderAction = ((Bool) -> Void)
// MARK: - 视图
var topOffset: CGFloat = uiTopBarHeight
/// 是否需要登录态
var needLogin = true
// MARK: - 各种占位图:网络 > 未登录 > 无数据
//Reload View
var needShowReloadView = true
var placeReloadView: BFPlaceHolderView?
var reloadTip = "Wake up your connection!".localized {
didSet {
}
}
var reloadImage = "network_error_1" {
didSet {
}
}
var reloadActionTitle = "Try Again".localized {
didSet {
}
}
var reloadViewClosure: PlaceHolderAction?
//Empty View
var needShowEmptyView = true
var placeEmptyView: BFPlaceHolderView?
var emptyTip = "Empty now".localized {
didSet {
}
}
var emptyImage = "empty_data" {
didSet {
}
}
var emptyActionTitle = "Go".localized {
didSet {
}
}
var emptyViewClosure: PlaceHolderAction?
//Login View
var needShowLoginView = true
var placeLoginView: BFPlaceHolderView?
var loginTip = "Please login first".localized {
didSet {
}
}
var loginImage = "github_signin_logo" {
didSet {
}
}
var loginActionTitle = "Sign in".localized {
didSet {
}
}
var loginViewClosure: PlaceHolderAction?
// MARK: - 刷新控件
var refreshHidden: RefreshHidderType = .all {
didSet {
setRefreshHiddenOrShow()
}
}
var refreshManager = MJRefreshManager()
var header: MJRefreshNormalHeader!
var footer: MJRefreshAutoNormalFooter!
lazy var tableView: UITableView = {
return self.getBaseTableView()
}()
// MARK: - 导航栏左右按钮
var leftItem: UIButton? {
didSet {
if let left = leftItem {
setLeftBarItem(left)
}
}
}
var rightItem: UIButton? {
didSet {
if let right = rightItem {
setRightBarItem(right)
}
}
}
var leftItemImage: UIImage? {
didSet {
leftItem!.setImage(leftItemImage, for: .normal)
layoutLeftItem()
}
}
var leftItemSelImage: UIImage? {
didSet {
leftItem!.setImage(leftItemSelImage, for: .selected)
layoutLeftItem()
}
}
var rightItemImage: UIImage? {
didSet {
rightItem!.setImage(rightItemImage, for: .normal)
layoutRightItem()
}
}
var rightItemSelImage: UIImage? {
didSet {
rightItem!.setImage(rightItemSelImage, for: .selected)
layoutRightItem()
}
}
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
customView()
gatherUserActivityInViewDidload()
registerNoti()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
gatherUserActivityInViewWillAppear()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
gatherUserActivityInViewWillDisAppear()
}
}
|
4f85879a414a14d686b81167698266ce
| 20.755952 | 75 | 0.563338 | false | false | false | false |
cocoaheadsru/server
|
refs/heads/develop
|
Sources/App/Models/Speaker/Speaker.swift
|
mit
|
1
|
import Vapor
import FluentProvider
// sourcery: AutoModelGeneratable
// sourcery: Preparation
final class Speaker: Model {
let storage = Storage()
var userId: Identifier
var speechId: Identifier
init(userId: Identifier, speechId: Identifier) {
self.userId = userId
self.speechId = speechId
}
// sourcery:inline:auto:Speaker.AutoModelGeneratable
init(row: Row) throws {
userId = try row.get(Keys.userId)
speechId = try row.get(Keys.speechId)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Keys.userId, userId)
try row.set(Keys.speechId, speechId)
return row
}
// sourcery:end
}
extension Speaker {
func user() throws -> User? {
return try parent(id: userId).get()
}
func speech() throws -> Speech? {
return try parent(id: speechId).get()
}
}
/// Custom implementation because of this exceptional case
extension Speaker: JSONRepresentable {
func makeJSON() throws -> JSON {
guard
let userJSON = try user()?.makeJSON(),
let userId = userJSON[Keys.id]?.int
else {
throw Abort(.internalServerError, reason: "Speaker doesn't have associated User")
}
var json = JSON(json: userJSON)
json.removeKey(Session.Keys.token)
json.removeKey(Keys.id)
try json.set(Keys.userId, userId)
return json
}
}
|
f2ccbef313b4c74495b7785cedabb30e
| 21.466667 | 87 | 0.664688 | false | false | false | false |
gewill/Feeyue
|
refs/heads/develop
|
Feeyue/Main/Lists/Lists/ListModel.swift
|
mit
|
1
|
//
// ListModel.swift
// Feeyue
//
// Created by Will on 2018/7/15.
// Copyright © 2018 Will. All rights reserved.
//
import Foundation
import RealmSwift
import IGListKit
import SwiftyJSON
import Moya_SwiftyJSONMapper
@objcMembers class TwitterList: BaseModel, ALSwiftyJSONAble {
enum Property: String {
case idStr, name, uri, memberCount, subscriberCount, mode, des, slug, fullName, createdAt, following, user
}
dynamic var idStr: String = "-1"
dynamic var name: String = ""
dynamic var uri: String = ""
dynamic var subscriberCount: Int = 0
dynamic var memberCount: Int = 0
dynamic var _mode: String = "priavate"
dynamic var des: String = ""
dynamic var slug: String = ""
dynamic var fullName: String = ""
dynamic var createdAt: Date = Date.distantPast
dynamic var following: Bool = false
dynamic var user: TwitterUser?
enum Mode: String {
case `private`, `public`
}
var mode: Mode {
get { return Mode(rawValue: _mode) ?? Mode.private }
set { _mode = mode.rawValue }
}
override class func primaryKey() -> String? {
return Property.idStr.rawValue
}
// MARK: - Object Mapper
convenience required init(jsonData json: JSON) {
self.init()
self.idStr = json["id_str"].string ?? UUID().uuidString
self.name = json["name"].stringValue
self.uri = json["uri"].stringValue
self.subscriberCount = json["subscriber_count"].intValue
self.memberCount = json["member_count"].intValue
self._mode = json["mode"].stringValue
self.des = json["description"].stringValue
self.slug = json["slug"].stringValue
self.fullName = json["full_name"].stringValue
self.createdAt = DateHelper.convert(json["created_at"])
self.following = json["following"].boolValue
if json["user"] != JSON.null { self.user = TwitterUser(jsonData: json["user"]) }
}
}
|
09b252470a8341248a85d22d46515c48
| 30.222222 | 114 | 0.641586 | false | false | false | false |
mercadopago/px-ios
|
refs/heads/develop
|
MercadoPagoSDK/MercadoPagoSDK/UI/PXCard/DefaultCards/TemplateCard.swift
|
mit
|
1
|
import Foundation
import MLCardDrawer
// TemplateCard
class TemplateCard: NSObject, CardUI {
var placeholderName = ""
var placeholderExpiration = ""
var bankImage: UIImage?
var cardPattern = [4, 4, 4, 4]
var cardFontColor: UIColor = .white
var cardLogoImage: UIImage?
var cardBackgroundColor: UIColor = UIColor(red: 0.23, green: 0.31, blue: 0.39, alpha: 1.0)
var securityCodeLocation: MLCardSecurityCodeLocation = .back
var defaultUI = true
var securityCodePattern = 3
var fontType: String = "light"
var cardLogoImageUrl: String?
var bankImageUrl: String?
}
class TemplatePIX: NSObject, GenericCardUI {
var titleName = ""
var titleWeight = ""
var titleTextColor = ""
var subtitleName = ""
var subtitleWeight = ""
var subtitleTextColor = ""
var labelName = ""
var labelTextColor = ""
var labelBackgroundColor = ""
var labelWeight = ""
var cardBackgroundColor = UIColor.white
var logoImageURL = ""
var securityCodeLocation = MLCardSecurityCodeLocation.none
var placeholderName = ""
var placeholderExpiration = ""
var cardPattern = [4, 4, 4, 4]
var cardFontColor: UIColor = .white
var defaultUI = true
var securityCodePattern = 3
var gradientColors = [""]
}
class TemplateDebin: NSObject, GenericCardUI {
var gradientColors: [String] = [""]
var descriptionName = ""
var descriptionTextColor = ""
var descriptionWeight = ""
var bla: String = ""
var labelName: String = ""
var labelTextColor: String = ""
var labelBackgroundColor: String = ""
var labelWeight: String = ""
var titleName: String = ""
var titleTextColor: String = ""
var titleWeight: String = ""
var subtitleName: String = ""
var subtitleTextColor: String = ""
var subtitleWeight: String = ""
var logoImageURL: String = ""
var cardPattern: [Int] = []
var cardBackgroundColor: UIColor = .red
var securityCodeLocation: MLCardSecurityCodeLocation = .none
var placeholderName: String = ""
var placeholderExpiration: String = ""
var cardFontColor: UIColor = .white
var defaultUI: Bool = true
var securityCodePattern: Int = 0 // averiguar
}
|
7d2357bca105faf6efa4fadeb603ca02
| 31.405797 | 94 | 0.666816 | false | false | false | false |
fakerabbit/LucasBot
|
refs/heads/master
|
AutoBot/PopOver.swift
|
gpl-3.0
|
2
|
//
// PopOverView.swift
// LucasBot
//
// Created by Mirko Justiniano on 2/20/17.
// Copyright © 2017 LB. All rights reserved.
//
import Foundation
import UIKit
class PopOver: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
typealias PopOverOnCell = (MenuButton?) -> Void
var onCell: PopOverOnCell = { button in }
var parentRect: CGRect = CGRect.zero
lazy var loading: UIActivityIndicatorView! = {
let load = UIActivityIndicatorView(activityIndicatorStyle: .gray)
load.hidesWhenStopped = true
load.startAnimating()
return load
}()
private let backgroundImg: UIImageView! = {
let view = UIImageView(image: UIImage(named: Utils.kPopBg))
view.contentMode = .scaleToFill
return view
}()
lazy var collectionView: UICollectionView! = {
let frame = self.frame
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 1
let cv: UICollectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
cv.backgroundColor = UIColor.clear
cv.alwaysBounceVertical = true
cv.showsVerticalScrollIndicator = false
cv.dataSource = self
cv.delegate = self
cv.register(PopCell.classForCoder(), forCellWithReuseIdentifier: "PopCell")
return cv
}()
var menuItems: [MenuButton?] = []
// MARK:- Init
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
///self.layer.cornerRadius = 6.0;
//self.layer.masksToBounds = false;
//self.clipsToBounds = true
self.addSubview(backgroundImg)
self.addSubview(collectionView)
self.addSubview(loading)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
let w = self.frame.size.width
let h = self.frame.size.height
backgroundImg.frame = CGRect(x: 0, y: 0, width: w, height: h)
collectionView.frame = CGRect(x: 0, y: 10, width: w - 10, height: h - 30)
loading.frame = CGRect(x: w/2 - loading.frame.size.width/2, y: h/2 - loading.frame.size.height/2, width: loading.frame.size.width, height: loading.frame.size.height)
}
// MARK:- Data Provider
func fetchMenu() {
NetworkMgr.sharedInstance.fetchMenu() { [weak self] buttons in
self?.menuItems = buttons
DispatchQueue.main.async {
self?.growAnimation()
}
}
}
/*
* MARK:- CollectionView Datasource & Delegate
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return menuItems.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let button = self.menuItems[indexPath.row]
let cell:PopCell = collectionView.dequeueReusableCell(withReuseIdentifier: "PopCell", for: indexPath) as! PopCell
cell.title = button?.title
cell.imgUrl = button?.imgUrl
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: collectionView.frame.size.width - 20, height: CGFloat((Utils.menuItemHeight as NSString).floatValue))
return size
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let button = self.menuItems[indexPath.row]
self.onCell(button)
}
// MARK:- Animations
func growAnimation() {
self.isHidden = true
let h:CGFloat = UIScreen.main.bounds.size.height/3 + 10
self.frame = CGRect(x: self.frame.origin.x, y: self.parentRect.minY - (h - 10), width: UIScreen.main.bounds.size.width - 20, height: h)
UIView.animate(withDuration: 2, animations: {
self.isHidden = false
}, completion: { [weak self] finished in
self?.loading.stopAnimating()
self?.layoutIfNeeded()
self?.collectionView.reloadData()
})
}
}
|
9747a15a0aaf9c06a15cdafde20e771a
| 32.846715 | 173 | 0.633815 | false | false | false | false |
Kushki/kushki-ios
|
refs/heads/master
|
Example/kushki-ios/CardTokenView.swift
|
mit
|
1
|
import SwiftUI
import Kushki
struct CardTokenView: View {
@State var name: String = ""
@State var cardNumber: String = ""
@State var cvv: String = ""
@State var expiryMonth: String = ""
@State var expiryYear: String = ""
@State var totalAmount: String = ""
@State var currency: String = "USD"
@State var showResponse: Bool = false
@State var responseMsg: String = ""
@State var isSubscription: Bool = false
@State var merchantId: String = ""
@State var loading: Bool = false
let currencies = ["CRC", "USD", "GTQ", "HNL", "NIO"]
func getCard() -> Card {
return Card(name: self.name,number: self.cardNumber, cvv: self.cvv,expiryMonth: self.expiryMonth,expiryYear: self.expiryYear)
}
func requestToken() {
self.loading.toggle()
let card = getCard();
let totalAmount = Double(self.totalAmount) ?? 0.0
let kushki = Kushki(publicMerchantId: self.merchantId, currency: self.currency, environment: KushkiEnvironment.testing_qa)
if(self.isSubscription){
kushki.requestSubscriptionToken(card: card, isTest: true){
transaction in
self.responseMsg = transaction.isSuccessful() ?
transaction.token : transaction.code + ": " + transaction.message
self.showResponse = true
self.loading.toggle()
}
}
else{
kushki.requestToken(card: card, totalAmount: totalAmount, isTest: true){
transaction in
self.responseMsg = transaction.isSuccessful() ?
transaction.token : transaction.code + ": " + transaction.message
self.showResponse = true
self.loading.toggle()
}
}
}
var body: some View {
NavigationView {
Form {
Section(header: Text("MerchantId")){
TextField("merchantId", text: $merchantId)
}
Section(header: Text("data")){
TextField("Name", text: $name)
TextField("Card Number", text: $cardNumber)
TextField("CVV", text: $cvv)
HStack{
TextField("Expiry Month", text: $expiryMonth)
TextField("Expiry Year", text: $expiryYear)
}
TextField("Total amount", text: $totalAmount)
Picker("Currency", selection: $currency){
ForEach(currencies, id: \.self){
Text($0)
}
}
}
Section(header:Text("Subscrition")){
Toggle(isOn: $isSubscription ){
Text("Subscription")
}
}
Section {
Button(action: {self.requestToken()}, label: {
Text("Request token")
}).alert(isPresented: $showResponse) {
Alert(title: Text("Token Response"), message: Text(self.responseMsg), dismissButton: .default(Text("Got it!")))
}
}
}.navigationBarTitle("Card Token").disabled(self.loading)
}
}
}
struct CardTokenView_Previews: PreviewProvider {
static var previews: some View {
CardTokenView()
}
}
|
951244ebb335e7722ebe5916c390f532
| 34.88 | 135 | 0.498606 | false | false | false | false |
xdkoooo/LiveDemo
|
refs/heads/master
|
LiveDemo/LiveDemo/Classes/Home/Controller/RecommendViewController.swift
|
mit
|
1
|
//
// RecommendViewController.swift
// LiveDemo
//
// Created by BillBear on 2017/1/25.
// Copyright © 2017年 xdkoo. All rights reserved.
//
import UIKit
fileprivate let kItemMargin : CGFloat = 10
fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2
fileprivate let kNormalItemH = kItemW * 3 / 4
fileprivate let kPrettyItemH = kItemW * 4 / 3
fileprivate let kHeaderViewH : CGFloat = 50
fileprivate let kCycleViewH = kScreenW * 3 / 8
fileprivate let kNormalCellID = "kNormalCellID"
fileprivate let kPrettyCellID = "kPrettyCellID"
fileprivate let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: UIViewController {
// MARK:- 懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
// MARK:- 配合minimumLineSpacing使用
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
// MARK:- 控制collectionView 随父控件伸缩
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionViewNormalCell",bundle:nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell",bundle:nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView",bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -kCycleViewH, width: kScreenW, height: kCycleViewH)
return cycleView
}()
override func viewDidLoad() {
super.viewDidLoad()
// 1.设置UI界面
setupUI()
// 发送网络请求
loadData()
}
}
// MARK:- 设置UI界面内容
extension RecommendViewController {
fileprivate func setupUI() {
// 1.添加collection
view.addSubview(collectionView)
// 2.将cycleView添加到UICollectionView中
collectionView.addSubview(cycleView)
// 3.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH, 0, 0, 0)
}
}
// MARK:- 请求数据
extension RecommendViewController {
fileprivate func loadData() {
// 1.请求推荐数据
recommendVM.requestData {
self.collectionView.reloadData()
}
// 2.请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
// MARK:- UICollectionViewDataSource
extension RecommendViewController : UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.定义cell
// var cell : UICollectionViewCell!
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
// 2.定义cell
var cell : CollectionViewBaseCell!
// 3.取出cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell
}
// 4.将模型赋值给Cell
cell.anchor = anchor
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出section的headerView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.取出模型
headerView.group = recommendVM.anchorGroups[indexPath.section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
|
d82b97db372c282b2ec4c5779fb116d9
| 35.148387 | 195 | 0.686596 | false | false | false | false |
lanit-tercom-school/grouplock
|
refs/heads/master
|
GroupLockiOS/GroupLockTests/UIViewControllerTests.swift
|
apache-2.0
|
1
|
//
// UIViewControllerTests.swift
// GroupLock
//
// Created by Sergej Jaskiewicz on 27.05.16.
// Copyright © 2016 Lanit-Tercom School. All rights reserved.
//
import XCTest
@testable import GroupLock
class UIViewControllerTests: XCTestCase {
var window: UIWindow!
var sut: UIViewController!
override func setUp() {
super.setUp()
window = UIWindow()
sut = UIViewController()
// Load the view
_ = sut.view
// Add the main view to the view hierarchy
window.addSubview(sut.view)
RunLoop.current.run(until: Date())
}
override func tearDown() {
sut = nil
window = nil
super.tearDown()
}
func testHideKeyboardWhenTappedAround() {
sut.hideKeyboardWhenTappedAround()
XCTAssertEqual(sut.view.gestureRecognizers?.count, 1, "View should be able to recognize gestures")
let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 10))
sut.view.addSubview(textField)
textField.becomeFirstResponder()
sut.dismissKeyboard()
XCTAssertFalse(textField.isFirstResponder, "Text field should lose keyboard focus")
}
}
|
cc503a9603d6516e5a4f0a0b9b4d95dd
| 23.08 | 106 | 0.645349 | false | true | false | false |
GJJDD/gjjinSwift
|
refs/heads/master
|
gjjinswift/gjjinswift/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// gjjinswift
//
// Created by apple on 16/6/28.
// Copyright © 2016年 QiaTu HangZhou. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UITabBarControllerDelegate {
var window: UIWindow?
lazy var takePhotoViewController:GJJTakePhotoViewController = {
GJJTakePhotoViewController()
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow.init(frame: UIScreen.main().bounds)
if false { // 直接进入主页
let inTabBarController: UITabBarController = GJJTabBarConfig().setuptabBarController()
inTabBarController.delegate = self;
self.window?.rootViewController = inTabBarController
} else {
// 开启广告页面
self.window?.rootViewController = GJJLaunchAdViewController()
}
self.window?.makeKeyAndVisible()
return true
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController.classForCoder.isSubclass(of: GJJTakePhotoTabbarViewController.classForCoder()) {
debugPrint("点我了")
viewController.present(takePhotoViewController, animated: true, completion: {
})
return false
}
return true
}
}
|
f2dfa7a461daf25c0992413c38cba153
| 24.967213 | 129 | 0.624369 | false | false | false | false |
mono0926/MonoGenerator
|
refs/heads/master
|
Sources/Generator.swift
|
mit
|
1
|
//
// Generator.swift
// MonoGenerator
//
// Created by mono on 2016/11/16.
//
//
import Foundation
class Generator {
let value: String
init(value: String) {
self.value = value
}
func generate(suffix: String = "( ´・‿・`)", maxLength: Int? = nil) -> String {
let r = value + suffix
guard let maxLength = maxLength else {
return r
}
// こうも書けるけどprefixの方がベター
// return r[r.startIndex..<r.index(r.startIndex, offsetBy: min(maxLength, r.characters.count))]
return String(r.characters.prefix(maxLength))
}
}
|
1ca2cbbe7700e2ddfc7c1420f7b6244e
| 21.807692 | 102 | 0.588533 | false | false | false | false |
appfoundry/DRYLogging
|
refs/heads/master
|
Pod/Classes/BackupRoller.swift
|
mit
|
1
|
//
// BackupRoller.swift
// Pods
//
// Created by Michael Seghers on 29/10/2016.
//
//
import Foundation
/// File roller which moves log files, augmenting their index and limiting them to the maximumNumberOfFiles.
/// The naming of the file follows the format [fileName][index].[extension] bassed on the file being rolled.
///
/// The following list shows an example of how rolling happens for a file named "default.log" and a maximum of 4 files
///
/// * 1st roll
/// - default.log becomes default1.log
/// * 2nd roll
/// - default1.log becomes default2.log
/// - default.log becomes default1.log
/// * 3rd roll
/// - default2.log becomes default3.log
/// - default1.log becomes default2.log
/// - default.log becomes default1.log
/// * 4th roll
/// - default3.log is deleted
/// - default2.log becomes default3.log
/// - default1.log becomes default2.log
/// - default.log becomes default1.log
///
/// - since: 3.0
public struct BackupRoller : LoggingRoller {
/// The number of files that should be kept before starting to delete te oldest ones.
public let maximumNumberOfFiles: UInt
/// Designated initializer, initializing a backup roller with the given maximumNumberOfFiles. The default is a maximum of 5 files.
///
/// - parameter maximumNumberOfFiles: the maximum number of files that will be used to roll over
public init(maximumNumberOfFiles: UInt = 5) {
self.maximumNumberOfFiles = maximumNumberOfFiles
}
public func rollFile(atPath path: String) {
objc_sync_enter(self)
let fileName = path.lastPathComponent.stringByDeletingPathExtension
let ext = path.pathExtension
let directory = path.stringByDeletingLastPathComponent
let operation = BackupRollerOperation(fileName: fileName, ext: ext, directory: directory, lastIndex: self.maximumNumberOfFiles - 1)
operation.performRolling()
objc_sync_exit(self)
}
}
/// Private helper class to perform the actual rolling
private struct BackupRollerOperation {
let fileName: String
let ext: String
let directory: String
let lastIndex: UInt
let fileManager: FileManager = FileManager.default
func performRolling() {
self.deleteLastFileIfNeeded()
for index in stride(from: Int(lastIndex), to: -1, by: -1) {
self.moveFileToNextIndex(from: index)
}
}
private func deleteLastFileIfNeeded() {
let lastFile = self.file(at: Int(self.lastIndex))
if self.fileManager.fileExists(atPath: lastFile) {
do {
try self.fileManager.removeItem(atPath: lastFile)
} catch {
print("Unable to delete last file: \(error)")
}
}
}
private func moveFileToNextIndex(from index: Int) {
let potentialExistingRolledFile = self.file(at: index)
if self.fileManager.fileExists(atPath: potentialExistingRolledFile) {
let newPath = self.file(at: index + 1)
self.moveFile(fromPath: potentialExistingRolledFile, toPath: newPath)
}
}
private func moveFile(fromPath: String, toPath: String) {
do {
try self.fileManager.moveItem(atPath: fromPath, toPath: toPath)
} catch {
print("Couldn't move file from \(fromPath) to \(toPath): \(error)")
}
}
private func file(at index: Int) -> String {
return self.directory.stringByAppendingPathComponent(path: "\(self.fileName)\(index <= 0 ? "" : String(index)).\(self.ext)")
}
}
|
661a1f58c6841f9c362b6afbfa358f99
| 33.695238 | 139 | 0.648092 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
refs/heads/master
|
UIKit/UIProgressView/UIProgressView/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// UIProgressView
//
// Created by jianghongbing on 2017/6/1.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var barProgressView: UIProgressView!
@IBOutlet weak var defaultProgressView: UIProgressView!
@IBOutlet weak var progressView: UIProgressView!
let progress = Progress(totalUnitCount: 10)
override func viewDidLoad() {
super.viewDidLoad()
setupProgressView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
print(barProgressView.frame, defaultProgressView.frame)
// barProgressView.subviews.forEach {
// print($0.frame)
// }
// defaultProgressView.subviews.forEach {
// print($0.frame)
// }
}
private func setupProgressView() {
//1.设置已经加载的进度的颜色
barProgressView.progressTintColor = UIColor.red
//2.设置没有被进度填充部分的颜色
barProgressView.trackTintColor = UIColor.blue
//3.设置progress view的进度,默认为0.5
// barProgressView.setProgress(0.0, animated: false)
barProgressView.progress = 0.0
//设置进度条的图片和非填充区域的图片
defaultProgressView.progressImage = createImage(UIColor.orange)
defaultProgressView.trackImage = createImage(UIColor.black)
// defaultProgressView.progressTintColor = UIColor.yellow
// defaultProgressView.trackTintColor = UIColor.brown
if #available(iOS 9.0, *) {
//iOS 9.0之后,可以通过UIProgress来改变UIProgressView的进度
progressView.observedProgress = progress
}
}
private func createImage(_ color: UIColor) -> UIImage? {
UIGraphicsBeginImageContext(CGSize(width: 1.0, height: 1.0))
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0)))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
@IBAction func start(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
barProgressView.setProgress(1.0, animated: true)
defaultProgressView.setProgress(0.0, animated: true)
progress.completedUnitCount = 10
}else {
barProgressView.setProgress(0.0, animated: true)
defaultProgressView.setProgress(1.0, animated: true)
progress.completedUnitCount = 0
}
}
}
|
0aeec084bf8daeb2d7813acb6ac39e54
| 31.074074 | 83 | 0.658968 | false | false | false | false |
incetro/NIO
|
refs/heads/master
|
Tests/DAOTests/Realm/Translators/MessagesTranslator.swift
|
mit
|
1
|
//
// MessagesTranslator.swift
// SDAO
//
// Created by incetro on 07/10/2019.
//
import SDAO
import Monreau
// MARK: - MessagesTranslator
final class MessagesTranslator {
// MARK: - Aliases
typealias PlainModel = MessagePlainObject
typealias DatabaseModel = MessageModelObject
private lazy var messageStorage = RealmStorage<MessageModelObject>(
configuration: RealmConfiguration(inMemoryIdentifier: "DAO")
)
}
// MARK: - Translator
extension MessagesTranslator: Translator {
func translate(model: DatabaseModel) throws -> PlainModel {
MessagePlainObject(
id: Int(model.uniqueId) ?? 0,
date: model.date,
text: model.text,
senderId: model.senderId,
receiverId: model.receiverId,
type: model.type,
isIncoming: model.isIncoming,
isRead: model.isRead
)
}
func translate(plain: PlainModel) throws -> DatabaseModel {
let model = try messageStorage.read(byPrimaryKey: plain.uniqueId.rawValue) ?? MessageModelObject()
try translate(from: plain, to: model)
return model
}
func translate(from plain: PlainModel, to databaseModel: DatabaseModel) throws {
if databaseModel.uniqueId.isEmpty {
databaseModel.uniqueId = plain.uniqueId.rawValue
}
databaseModel.date = plain.date
databaseModel.isIncoming = plain.isIncoming
databaseModel.isRead = plain.isRead
databaseModel.senderId = plain.senderId
databaseModel.text = plain.text
databaseModel.type = plain.type
databaseModel.receiverId = plain.receiverId
}
}
|
7f9f40cead60a3020f71de9694f0f8b0
| 27.083333 | 106 | 0.657567 | false | false | false | false |
pawrsccouk/Stereogram
|
refs/heads/master
|
Stereogram-iPad/Stereogram.swift
|
mit
|
1
|
//
// Stereogram.swift
// Stereogram-iPad
//
// Created by Patrick Wallace on 19/04/2015.
// Copyright (c) 2015 Patrick Wallace. All rights reserved.
//
import UIKit
/// How the stereogram should be viewed.
///
/// - Crosseyed: Adjacent pictures, view crosseyed.
/// - Walleyed: Adjacent pictures, view wall-eyed
/// - RedGreen: Superimposed pictures, use red green glasses.
/// - RandomDot: "Magic Eye" format.
/// - AnimatedGIF: As a cycling animation.
///
public enum ViewMode: Int {
case Crosseyed,
Walleyed,
RedGreen,
RandomDot,
AnimatedGIF
}
private let kViewingMethod = "ViewingMethod"
private let leftPhotoFileName = "LeftPhoto.jpg"
, rightPhotoFileName = "RightPhoto.jpg"
, propertyListFileName = "Properties.plist"
/// Save the property list into it's appointed place.
///
/// :returns: .Success or .Error(NSError) on failure.
private func savePropertyList(propertyList: Stereogram.PropertyDict, toURL url: NSURL) -> Result {
var error: NSError?
if let data = NSPropertyListSerialization.dataWithPropertyList(propertyList
, format: .XMLFormat_v1_0
, options: 0
, error: &error) {
if data.writeToURL(url, options: .allZeros, error: &error) {
return .Success()
}
}
return returnError("Stereogram.savePropertyList()"
, "NSData.writeToURL(_, options:, error:)")
}
/// A Stereogram contains URLs to a left and a right image
/// and composites these according to a viewing method.
///
/// The stereogram assumes you have created a new directory with three files in it:
/// LeftPhoto.jpg, RightPhoto.jpg and Properties.plist.
/// There are class methods to create this directory structure
/// and to search a directory for stereogram objects.
///
/// The stereogram normally contains just three URLs to find these resources.
/// When needed, it will load and cache the images.
/// It will also respond to memory-full notifications and clear the images,
/// which can be re-calculated or reloaded later.
///
/// Calculating the main stereogram image can take time, so you can use
/// the reset method, which will clear all the loaded images and then explicitly reload them all.
/// This can be done in a background thread.
public class Stereogram: NSObject {
// MARK: Properties
/// The type of the property dictionary.
typealias PropertyDict = [String : AnyObject]
/// How to view this stereogram.
/// This affects how the image returned by stereogramImage is computed.
var viewingMethod: ViewMode {
get {
var viewMode: ViewMode? = nil
if let viewingMethodNumber = propertyList[kViewingMethod] as? NSNumber {
viewMode = ViewMode(rawValue: viewingMethodNumber.integerValue)
assert(viewMode != nil, "Invalid value \(viewingMethodNumber)")
}
return viewMode ?? .Crosseyed
}
set {
if self.viewingMethod != newValue {
propertyList[kViewingMethod] = newValue.rawValue
savePropertyList(propertyList, toURL: propertiesURL)
// Delete any cached images so they are recreated with the new viewing method.
stereogramImg = nil
thumbnailImg = nil
}
}
}
override public var description: String {
return "\(super.description) <BaseURL: \(baseURL), Properties: \(propertyList)>"
}
/// URLs to the base directory containing the images. Used to load the images when needed.
let baseURL: NSURL
//MARK: Private Data
/// Properties file for each stereogram.
/// Probably not cached, just load them when we open the object.
private var propertyList: PropertyDict
/// Cached images in memory. Free these if needed.
private var stereogramImg: UIImage?
private var thumbnailImg: UIImage?
//MARK: Initializers
/// Initilizes the stereogram from two already-existing images.
///
/// Save the images provided to the disk under a specified directory.
///
/// :param: leftImage - The left image in the stereogram.
/// :param: rightImage - The right image in the stereogram.
/// :param: baseURL - The URL to save the stereogram under.
/// :returns: A Stereogram object on success, nil on failure.
public convenience init?(leftImage: UIImage
, rightImage: UIImage
, baseURL: NSURL
, inout error: NSError?) {
let newStereogramURL = Stereogram.getUniqueStereogramURL(baseURL)
let propertyList = [String : AnyObject]()
self.init( baseURL: newStereogramURL
, propertyList: propertyList)
switch writeToURL(newStereogramURL, propertyList, leftImage, rightImage) {
case .Success:
break
case .Error(let e):
error = e
return nil
}
}
/// Designated Initializer.
/// Creates a new stereogram object from a URL and a property list.
///
/// :param: baseImageURL File URL pointing to the directory under which the images are stored.
/// :param: propertyList A dictionary of default properties for this stereogram
private init(baseURL url: NSURL, propertyList propList: PropertyDict) {
baseURL = url
propertyList = propList
super.init()
thumbnailImg = nil
stereogramImg = nil
// Notify when memory is low, so I can delete this cache.
let centre = NSNotificationCenter.defaultCenter()
centre.addObserver(self
, selector: "lowMemoryNotification:"
, name: UIApplicationDidReceiveMemoryWarningNotification
, object :nil)
}
deinit {
let centre = NSNotificationCenter.defaultCenter()
centre.removeObserver(self)
}
}
//MARK: - Public class functions.
/// Checks if a file exists given a base directory URL and filename.
///
/// :param: baseURL The Base URL to look in.
/// :param: fileName The name of the file to check for.
/// :returns: .Success if the file was present, .Error(NSError) if it was not.
private func fileExists(baseURL: NSURL, fileName: String) -> Result {
let fullURLPath = baseURL.URLByAppendingPathComponent(fileName).path
if let fullPath = fullURLPath {
if NSFileManager.defaultManager().fileExistsAtPath(fullPath) {
return .Success()
}
}
let userInfo = [NSFilePathErrorKey : NSString(string: fullURLPath ?? "<no path>")]
return .Error(NSError(errorCode:.FileNotFound, userInfo: userInfo))
}
/// Initialize this object by loading image data from the specified URL.
///
/// :param: url - A File URL pointing to the root directory of a stereogram object
/// :returns: A Stereogram object on success or an NSError object on failure.
private func stereogramFromURL(url: NSURL) -> ResultOf<Stereogram> {
// URL should be pointing to a directory.
// Inside this there should be 3 files: LeftImage.jpg, RightImage.jpg, Properties.plist.
// Return an error if any of these are missing. Also load the properties file.
let defaultPropertyDict: Stereogram.PropertyDict = [
kViewingMethod : ViewMode.Crosseyed.rawValue]
// if any of the files don't exist, then return an error.
let result = and([
fileExists(url, leftPhotoFileName),
fileExists(url, rightPhotoFileName),
fileExists(url, propertyListFileName)])
if let err = result.error {
return .Error(err)
}
// Load the property list at the given URL.
var propertyList = defaultPropertyDict
switch loadPropertyList(url.URLByAppendingPathComponent(propertyListFileName)) {
case .Success(let propList):
propertyList = propList.value
case .Error(let error):
return .Error(error)
}
return ResultOf(Stereogram(baseURL: url, propertyList: propertyList))
}
/// Load a property list stored at URL and return it.
///
/// :param: url - File URL describing a path to a .plist file.
/// :returns: A PropertyDict on success, an NSError on failure.
private func loadPropertyList(url: NSURL) -> ResultOf<Stereogram.PropertyDict> {
var error: NSError?
var formatPtr: UnsafeMutablePointer<NSPropertyListFormat> = nil
let options = Int(NSPropertyListMutabilityOptions.MutableContainersAndLeaves.rawValue)
if let propertyData = NSData(contentsOfURL:url, options:.allZeros, error:&error)
, propObject: AnyObject = NSPropertyListSerialization.propertyListWithData(propertyData
, options: options
, format: formatPtr
, error: &error)
, propDict = propObject as? Stereogram.PropertyDict {
return ResultOf(propDict)
}
else {
assert(false, "Property list object cannot be converted to a dictionary")
}
return .Error(error!)
}
extension Stereogram {
/// Find all the stereograms found in the given directory
///
/// :param: url - A File URL pointing to the directory to search.
/// :returns: An array of Stereogram objects on success or an NSError on failure.
class func allStereogramsUnderURL(url: NSURL) -> ResultOf<[Stereogram]> {
let fileManager = NSFileManager.defaultManager()
var stereogramArray = [Stereogram]()
var error: NSError?
if let
fileArray = fileManager.contentsOfDirectoryAtURL(url
, includingPropertiesForKeys: nil
, options: .SkipsHiddenFiles
, error: &error),
fileNames = fileArray as? [NSURL] {
for stereogramURL in fileNames {
switch stereogramFromURL(stereogramURL) {
case .Success(let result):
stereogramArray.append(result.value)
case .Error(let err):
return .Error(err)
}
}
}
return ResultOf(stereogramArray)
}
}
// MARK: - Methods
extension Stereogram {
/// Combine leftImage and rightImage according to viewingMethod,
/// loading the images if they are not already available.
///
/// :returns: The new image on success or an NSError object on failure.
func stereogramImage() -> ResultOf<UIImage> {
// The image is cached. Just return the cached image.
if stereogramImg != nil {
return ResultOf(stereogramImg!)
}
// Get the left and right images, loading them if they are not in cache.
let leftImage: UIImage, rightImage: UIImage
switch and(loadImage(.Left), loadImage(.Right)) {
case .Error(let error): return .Error(error)
case .Success(let result):
(leftImage, rightImage) = result.value
}
// Create the stereogram image, cache it and return it.
switch (self.viewingMethod) {
case .Crosseyed:
switch ImageManager.makeStereogramWithLeftPhoto(leftImage, rightPhoto:rightImage) {
case .Error(let error): return .Error(error)
case .Success(let result): stereogramImg = result.value
}
case .Walleyed:
switch ImageManager.makeStereogramWithLeftPhoto(rightImage, rightPhoto:leftImage) {
case .Error(let error): return .Error(error)
case .Success(let result): stereogramImg = result.value
}
case .AnimatedGIF:
stereogramImg = UIImage.animatedImageWithImages([leftImage, rightImage], duration: 0.25)
default:
let reason = "Viewing method \(self.viewingMethod) is not implemented yet."
let e = NSException(name: "Not implemented"
, reason: reason
, userInfo: nil)
e.raise()
break
}
return ResultOf(stereogramImg!)
}
/// Return a thumbnail image, caching it if necessary.
///
/// :returns: The thumbnail image on success or an NSError object on failure.
func thumbnailImage() -> ResultOf<UIImage> {
let options = NSDataReadingOptions.allZeros
var error: NSError?
if thumbnailImg == nil {
// Get either the left or the right image file URL to use as the thumbnail.
var data: NSData? = NSData(contentsOfURL:leftImageURL, options:options, error:&error)
if data == nil {
data = NSData(contentsOfURL:rightImageURL, options:options, error:&error)
}
if data == nil {
return .Error(error!)
}
if let
d = data,
image = UIImage(data: d) {
// Create the image, and then return a thumbnail-sized copy.
thumbnailImg = image.thumbnailImage(thumbnailSize: Int(thumbnailSize.width)
, transparentBorderSize: 0
, cornerRadius: 0
, interpolationQuality: kCGInterpolationLow)
} else {
let userInfo: [String : AnyObject] = [
NSLocalizedDescriptionKey : "Invalid image format in file",
NSFilePathErrorKey : leftImageURL.path!]
let err = NSError(errorCode:.InvalidFileFormat, userInfo:userInfo)
return .Error(err)
}
}
return ResultOf(thumbnailImg!)
}
}
// MARK: Exporting
extension Stereogram {
/// Alias for a string representing a MIME Type (e.g. "image/jpeg")
typealias MIMEType = String
/// The MIME type for the image that stereogramImage will generate.
///
/// This is based on the viewing method. Use to represent the image when saving.
var mimeType: MIMEType {
return viewingMethod == ViewMode.AnimatedGIF ? "image/gif" : "image/jpeg"
}
/// Data format when returning data for exporting a stereogram
typealias ExportData = (NSData, MIMEType)
/// Returns the stereogram image in a format for sending outside this application.
///
/// :returns: .Success(ExportData) or .Error(NSError)
///
/// ExportData is a tuple: The data representing the image,
/// and a MIME type indicating the format of the data.
func exportData() -> ResultOf<ExportData> {
return stereogramImage().map { (image) -> ResultOf<ExportData> in
let data: NSData
let mimeType: MIMEType
if self.viewingMethod == .AnimatedGIF {
mimeType = "image/gif"
data = image.asGIFData
} else {
mimeType = "image/jpeg"
data = image.asJPEGData
}
return ResultOf((data, mimeType))
}
}
}
// MARK: - Convenience Properties
extension Stereogram {
/// Update the stereogram and thumbnail, replacing the cached images.
/// Usually called from a background thread just after some property has been changed.
///
/// :returns: Success or an NSError object on failure.
func refresh() -> Result {
thumbnailImg = nil
stereogramImg = nil
return and(thumbnailImage().result, stereogramImage().result)
}
/// Delete the folder representing this stereogram from the disk.
/// After this, the stereogram will be invalid.
///
/// :returns: Success or an NSError object on failure.
func deleteFromDisk() -> Result {
var error: NSError?
let fileManager = NSFileManager.defaultManager()
let success = fileManager.removeItemAtURL(baseURL, error:&error)
if success {
thumbnailImg = nil
stereogramImg = nil
return .Success()
}
return .Error(error!)
}
}
//MARK: Private data
/// Saves the specified image into a file provided by the given URL
///
/// :param: image - The image to save.
/// :param: url - File URL of the location to save the image.
/// :returns: Success on success, or an NSError on failure.
///
/// Currently this saves as a JPEG file, but it doesn't check the extension in the URL
/// so it is possible it could save JPEG data into a file ending in .png for example.
private func saveImageIntoURL(image: UIImage, url: NSURL) -> Result {
let fileData = UIImageJPEGRepresentation(image, 1.0)
var error: NSError?
if fileData.writeToURL(url, options:.AtomicWrite, error:&error) {
return .Success()
}
return .Error(error!)
}
/// Save the left and right images and the property list into the directory specified by url.
///
/// :param: url - A File URL to the directory to store the images in.
/// :param: propertyList - The property list to output
/// :param: leftImage - The left image to save.
/// :param: rightImage - The right image to save.
/// :returns: Success or .Error(NSError) on failure.
private func writeToURL(url: NSURL
, propertyList: [String : AnyObject]
, leftImage: UIImage
, rightImage: UIImage) -> Result {
assert(url.path != nil, "URL \(url) has an invalid path")
let fileManager = NSFileManager.defaultManager()
let leftImageURL = url.URLByAppendingPathComponent(leftPhotoFileName)
let rightImageURL = url.URLByAppendingPathComponent(rightPhotoFileName)
// Create the directory (ignoring any errors about it already existing)
// and then write the left and right images and properties data into it.
return and(
[ fileManager.createDirectoryAtURL(url)
, saveImageIntoURL(leftImage , leftImageURL )
, saveImageIntoURL(rightImage, rightImageURL)
, savePropertyList(propertyList, toURL: url)
])
}
/// Serialize the property dict given and write it out to the given URL.
///
/// :param: propertyList
/// :param: toURL
/// :param: format
/// :returns: .Success() on success, .Error() on error.
private func savePropertyList(propertyList: Stereogram.PropertyDict
, toURL url: NSURL
, format: NSPropertyListFormat = .XMLFormat_v1_0) -> Result {
var error: NSError?
if let propertyListData = NSPropertyListSerialization.dataWithPropertyList(
propertyList
, format: format
, options: .allZeros
, error: &error) {
let propertyListURL = url.URLByAppendingPathComponent(propertyListFileName)
if !propertyListData.writeToURL(propertyListURL
, options: .AtomicWrite
, error: &error) {
return .Error(error!)
}
return .Success()
}
return returnError("writeToURL(_propertyList:toURL:format:)"
, "calling NSPropertyListSerialization.dataWithPropertyList")
}
extension Stereogram {
/// URL of the left image file (computed from the base URL)
private var leftImageURL: NSURL {
return baseURL.URLByAppendingPathComponent(leftPhotoFileName)
}
/// URL of the right image file (computed from the base URL)
private var rightImageURL: NSURL {
return baseURL.URLByAppendingPathComponent(rightPhotoFileName)
}
/// URL of the property list file (computed from the base URL)
private var propertiesURL: NSURL {
return baseURL.URLByAppendingPathComponent(propertyListFileName)
}
/// Create a new unique URL which will not already reference a stereogram.
/// This URL is relative to photoDir.
///
/// :param: photoDir - The base directory with all the stereograms in it.
/// :returns: A file URL pointing to a new directory under photoDir.
private class func getUniqueStereogramURL(photoDir: NSURL) -> NSURL {
// Create a CF GUID, then turn it into a string, which we will return.
// Add the object into the backing store using this key.
let newUID = CFUUIDCreate(kCFAllocatorDefault);
let newUIDString = CFUUIDCreateString(kCFAllocatorDefault, newUID)
let uid = newUIDString as String
let newURL = photoDir.URLByAppendingPathComponent(uid, isDirectory:true)
// Name should be unique so no photo should exist yet.
assert(newURL.path != nil, "URL \(newURL) has no path.")
assert(!NSFileManager.defaultManager().fileExistsAtPath(newURL.path!)
, "'Unique' file URL \(newURL) already exists")
return newURL;
}
private enum WhichImage {
case Left, Right
}
/// Loads one of the two images, caching it if necessary.
///
/// :param: whichImage - Left or Right specifying which image to load.
/// :returns: The UIImage object on success or NSError on failure.
private func loadImage(whichImage: WhichImage) -> ResultOf<UIImage> {
func loadData(url: NSURL) -> ResultOf<UIImage> {
var error: NSError?
if let
imageData = NSData(contentsOfURL:url, options:.allZeros, error:&error),
image = UIImage(data: imageData) {
return ResultOf(image)
} else {
return ResultOf.Error(error!)
}
}
switch whichImage {
case .Left:
return loadData(leftImageURL)
case .Right:
return loadData(rightImageURL)
}
}
/// Searches a given directory and returns all the entries under it.
///
/// :param: url - A file URL pointing to the directory to search.
/// :returns: An array of URL objects, one each for each file in the directory
///
/// This does not include hidden files in the search.
private class func contentsUnderURL(url: NSURL) -> ResultOf<[NSURL]> {
let fileManager = NSFileManager.defaultManager()
var error: NSError?
if let
fileArray = fileManager.contentsOfDirectoryAtURL(url
, includingPropertiesForKeys: nil
, options: .SkipsHiddenFiles
, error: &error),
urlArray = fileArray as? [NSURL] {
return ResultOf(urlArray)
}
return .Error(error!)
}
}
|
84957159afece8b5807d0f7a6a844c65
| 32.292763 | 98 | 0.696176 | false | false | false | false |
5calls/ios
|
refs/heads/main
|
FiveCalls/FiveCalls/ContactsManager.swift
|
mit
|
1
|
//
// ContactsManager.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/9/19.
// Copyright © 2019 5calls. All rights reserved.
//
import Foundation
enum ContactLoadResult {
case success([Contact])
case failed(Error)
}
class ContactsManager {
private let queue: OperationQueue
// contactCache stores a list of contacts for a string-serialized location
private var contactCache: [String: [Contact]]
init() {
queue = .main
contactCache = [:]
}
func fetchContacts(location: UserLocation, completion: @escaping (ContactLoadResult) -> Void) {
// if we already have contacts for this userlocation, return that
if let contacts = self.contactCache[location.description] {
completion(.success(contacts))
return
}
let operation = FetchContactsOperation(location: location)
operation.completionBlock = { [weak operation] in
if var contacts = operation?.contacts, !contacts.isEmpty {
// if we get more than one house rep here, select the first one.
// this is a split district situation and we should let the user
// pick which one is correct in the future
let houseReps = contacts.filter({ $0.area == "US House" })
if houseReps.count > 1 {
contacts = contacts.filter({ $0.area != "US House" })
contacts.append(houseReps[0])
}
self.contactCache[location.description] = contacts
DispatchQueue.main.async {
completion(.success(contacts))
}
} else if let error = operation?.error {
DispatchQueue.main.async {
completion(.failed(error))
}
}
}
queue.addOperation(operation)
}
}
|
ce8b191ac5d7e519d2c039223d91da9d
| 32.186441 | 99 | 0.562819 | false | false | false | false |
DianQK/rx-sample-code
|
refs/heads/master
|
Stopwatch/BasicViewModel.swift
|
mit
|
1
|
//
// BasicViewModel.swift
// Stopwatch
//
// Created by DianQK on 12/09/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
//import RxExtensions
struct BasicViewModel: StopwatchViewModelProtocol {
let startAStopStyle: Observable<Style.Button>
let resetALapStyle: Observable<Style.Button>
let displayTime: Observable<String>
let displayElements: Observable<[(title: Observable<String>, displayTime: Observable<String>, color: Observable<UIColor>)]>
private enum State {
case timing, stopped
}
init(input: (startAStopTrigger: Observable<Void>, resetALapTrigger: Observable<Void>)) {
let state = input.startAStopTrigger
.scan(State.stopped) {
switch $0.0 {
case .stopped: return State.timing
case .timing: return State.stopped
}
}
.shareReplay(1)
displayTime = state
.flatMapLatest { state -> Observable<TimeInterval> in
switch state {
case .stopped:
return Observable.empty()
case .timing:
return Observable<Int>.interval(0.01, scheduler: MainScheduler.instance).map { _ in 0.01 }
}
}
.scan(0, accumulator: +)
.startWith(0)
.map(Tool.convertToTimeInfo)
startAStopStyle = state
.map { state in
switch state {
case .stopped:
return Style.Button(title: "Start", titleColor: Tool.Color.green, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "green"))
case .timing:
return Style.Button(title: "Stop", titleColor: Tool.Color.red, isEnabled: true, backgroungImage: #imageLiteral(resourceName: "red"))
}
}
resetALapStyle = Observable.just(Style.Button(title: "", titleColor: UIColor.white, isEnabled: false, backgroungImage: #imageLiteral(resourceName: "gray")))
displayElements = Observable.empty()
}
}
|
7e6786f9749815ed3fe7b51ae3799ce6
| 34.145161 | 164 | 0.582836 | false | false | false | false |
wireapp/wire-ios
|
refs/heads/develop
|
Wire-iOS/Sources/UserInterface/Components/UserImageView.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireSyncEngine
/**
* A view that displays the avatar for a remote user.
*/
class UserImageView: AvatarImageView, ZMUserObserver {
/**
* The different sizes for the avatar image.
*/
enum Size: Int {
case tiny = 16
case badge = 24
case small = 32
case normal = 64
case big = 320
}
// MARK: - Interface Properties
/// The size of the avatar.
var size: Size {
didSet {
updateUserImage()
}
}
/// Whether the image should be desaturated, e.g. for unconnected users.
var shouldDesaturate: Bool = true
/// Whether the badge indicator is enabled.
var indicatorEnabled: Bool = false {
didSet {
badgeIndicator.isHidden = !indicatorEnabled
}
}
private let badgeIndicator = RoundedView()
// MARK: - Remote User
/// The user session to use to download images.
var userSession: ZMUserSessionInterface? {
didSet {
updateUser()
}
}
/// The user to display the avatar of.
var user: UserType? {
didSet {
updateUser()
}
}
private var userObserverToken: Any?
// MARK: - Initialization
override init(frame: CGRect) {
self.size = .small
super.init(frame: .zero)
configureSubviews()
configureConstraints()
}
init(size: Size = .small) {
self.size = size
super.init(frame: .zero)
configureSubviews()
configureConstraints()
}
deinit {
userObserverToken = nil
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var intrinsicContentSize: CGSize {
return CGSize(width: size.rawValue, height: size.rawValue)
}
private func configureSubviews() {
accessibilityElementsHidden = true
badgeIndicator.backgroundColor = .red
badgeIndicator.isHidden = true
badgeIndicator.shape = .circle
addSubview(badgeIndicator)
}
private func configureConstraints() {
badgeIndicator.translatesAutoresizingMaskIntoConstraints = false
setContentHuggingPriority(.required, for: .vertical)
setContentHuggingPriority(.required, for: .horizontal)
NSLayoutConstraint.activate([
badgeIndicator.topAnchor.constraint(equalTo: topAnchor),
badgeIndicator.trailingAnchor.constraint(equalTo: trailingAnchor),
badgeIndicator.heightAnchor.constraint(equalTo: badgeIndicator.widthAnchor),
badgeIndicator.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1/3)
])
}
// MARK: - Interface
/// Returns the appropriate border width for the user.
private func borderWidth(for user: UserType) -> CGFloat {
return user.isServiceUser ? 0.5 : 0
}
/// Returns the appropriate border color for the user.
private func borderColor(for user: UserType) -> CGColor? {
return user.isServiceUser ? UIColor.black.withAlphaComponent(0.08).cgColor : nil
}
/// Returns the placeholder background color for the user.
private func containerBackgroundColor(for user: UserType) -> UIColor? {
switch self.avatar {
case .image?, nil:
return user.isServiceUser ? .white : .clear
case .text?:
if user.isConnected || user.isSelfUser || user.isTeamMember || user.isWirelessUser {
return user.accentColor
} else {
return UIColor(white: 0.8, alpha: 1)
}
}
}
/// Returns the appropriate avatar shape for the user.
private func shape(for user: UserType) -> AvatarImageView.Shape {
return user.isServiceUser ? .relative : .circle
}
// MARK: - Changing the Content
/**
* Sets the avatar for the user with an optional animation.
* - parameter avatar: The avatar of the user.
* - parameter user: The currently displayed user.
* - parameter animated: Whether to animate the change.
*/
func setAvatar(_ avatar: Avatar, user: UserType, animated: Bool) {
let updateBlock = {
self.avatar = avatar
self.container.backgroundColor = self.containerBackgroundColor(for: user)
}
if animated && !ProcessInfo.processInfo.isRunningTests {
UIView.transition(with: self, duration: 0.15, options: .transitionCrossDissolve, animations: updateBlock, completion: nil)
} else {
updateBlock()
}
}
/// Updates the image for the user.
fileprivate func updateUserImage() {
guard
let user = user,
let userSession = userSession
else {
return
}
var desaturate = false
if shouldDesaturate {
desaturate = !user.isConnected && !user.isSelfUser && !user.isTeamMember && !user.isServiceUser
}
user.fetchProfileImage(session: userSession,
imageCache: UIImage.defaultUserImageCache,
sizeLimit: size.rawValue,
isDesaturated: desaturate,
completion: { [weak self] (image, cacheHit) in
// Don't set image if nil or if user has changed during fetch
guard let image = image, user.isEqual(self?.user) else { return }
self?.setAvatar(.image(image), user: user, animated: !cacheHit)
})
}
// MARK: - Updates
func userDidChange(_ changeInfo: UserChangeInfo) {
// Check for potential image changes
if size == .big {
if changeInfo.imageMediumDataChanged || changeInfo.connectionStateChanged {
updateUserImage()
}
} else {
if changeInfo.imageSmallProfileDataChanged || changeInfo.connectionStateChanged || changeInfo.teamsChanged {
updateUserImage()
}
}
// Change for accent color changes
if changeInfo.accentColorValueChanged {
updateIndicatorColor()
}
}
/// Called when the user or user session changes.
func updateUser() {
guard let user = self.user, let initials = user.initials else {
return
}
let defaultAvatar = Avatar.text(initials.localizedUppercase)
setAvatar(defaultAvatar, user: user, animated: false)
if !ProcessInfo.processInfo.isRunningTests,
let userSession = userSession as? ZMUserSession {
userObserverToken = UserChangeInfo.add(observer: self, for: user, in: userSession)
}
updateForServiceUserIfNeeded(user)
updateIndicatorColor()
updateUserImage()
}
/// Updates the color of the badge indicator.
private func updateIndicatorColor() {
self.badgeIndicator.backgroundColor = user?.accentColor
}
/// Updates the interface to reflect if the user is a service user or not.
private func updateForServiceUserIfNeeded(_ user: UserType) {
let oldValue = shape
shape = shape(for: user)
if oldValue != shape {
container.layer.borderColor = borderColor(for: user)
container.layer.borderWidth = borderWidth(for: user)
container.backgroundColor = containerBackgroundColor(for: user)
}
}
}
|
d459a0e784cf78d1b598d81802068887
| 30.237548 | 134 | 0.621489 | false | false | false | false |
airbnb/lottie-ios
|
refs/heads/master
|
Sources/Private/CoreAnimation/Animations/CombinedShapeAnimation.swift
|
apache-2.0
|
3
|
// Created by Cal Stephens on 1/28/22.
// Copyright © 2022 Airbnb Inc. All rights reserved.
import QuartzCore
extension CAShapeLayer {
/// Adds animations for the given `CombinedShapeItem` to this `CALayer`
@nonobjc
func addAnimations(
for combinedShapes: CombinedShapeItem,
context: LayerAnimationContext,
pathMultiplier: PathMultiplier)
throws
{
try addAnimation(
for: .path,
keyframes: combinedShapes.shapes.keyframes,
value: { paths in
let combinedPath = CGMutablePath()
for path in paths {
combinedPath.addPath(path.cgPath().duplicated(times: pathMultiplier))
}
return combinedPath
},
context: context)
}
}
// MARK: - CombinedShapeItem
/// A custom `ShapeItem` subclass that combines multiple `Shape`s into a single `KeyframeGroup`
final class CombinedShapeItem: ShapeItem {
// MARK: Lifecycle
init(shapes: KeyframeGroup<[BezierPath]>, name: String) {
self.shapes = shapes
super.init(name: name, type: .shape, hidden: false)
}
required init(from _: Decoder) throws {
fatalError("init(from:) has not been implemented")
}
required init(dictionary _: [String: Any]) throws {
fatalError("init(dictionary:) has not been implemented")
}
// MARK: Internal
let shapes: KeyframeGroup<[BezierPath]>
}
extension CombinedShapeItem {
/// Manually combines the given shape keyframes by manually interpolating at each frame
static func manuallyInterpolating(
shapes: [KeyframeGroup<BezierPath>],
name: String)
-> CombinedShapeItem
{
let interpolators = shapes.map { shape in
KeyframeInterpolator(keyframes: shape.keyframes)
}
let times = shapes.flatMap { $0.keyframes.map { $0.time } }
let minimumTime = times.min() ?? 0
let maximumTime = times.max() ?? 0
let animationLocalTimeRange = Int(minimumTime)...Int(maximumTime)
let interpolatedKeyframes = animationLocalTimeRange.map { localTime in
Keyframe(
value: interpolators.compactMap { interpolator in
interpolator.value(frame: AnimationFrameTime(localTime)) as? BezierPath
},
time: AnimationFrameTime(localTime))
}
return CombinedShapeItem(
shapes: KeyframeGroup(keyframes: ContiguousArray(interpolatedKeyframes)),
name: name)
}
}
|
c411d2c82bf966f76fcd6a56806af462
| 26.845238 | 95 | 0.689611 | false | false | false | false |
WestlakeAPC/game-off-2016
|
refs/heads/master
|
external/Fiber2D/Fiber2D/PhysicsBody+Internal.swift
|
apache-2.0
|
1
|
//
// PhysicsBody+Internal.swift
// Fiber2D
//
// Created by Andrey Volodin on 20.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
internal func internalBodySetMass(_ body: UnsafeMutablePointer<cpBody>, _ mass: cpFloat)
{
cpBodyActivate(body);
body.pointee.m = mass;
body.pointee.m_inv = 1.0 / mass
//cpAssertSaneBody(body);
}
internal func internalBodyUpdateVelocity(_ body: UnsafeMutablePointer<cpBody>?, _ gravity: cpVect, _ damping: cpFloat, _ dt: cpFloat) {
cpBodyUpdateVelocity(body, cpvzero, damping, dt)
// Skip kinematic bodies.
guard cpBodyGetType(body) != CP_BODY_TYPE_KINEMATIC else {
return
}
let physicsBody = Unmanaged<PhysicsBody>.fromOpaque(cpBodyGetUserData(body)).takeUnretainedValue()
if physicsBody.isGravityEnabled {
body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvadd(gravity, cpvmult(body!.pointee.f, body!.pointee.m_inv)), dt)), cpFloat(physicsBody.velocityLimit))
} else {
body!.pointee.v = cpvclamp(cpvadd(cpvmult(body!.pointee.v, damping), cpvmult(cpvmult(body!.pointee.f, body!.pointee.m_inv), dt)), cpFloat(physicsBody.velocityLimit))
}
let w_limit = cpFloat(physicsBody.angularVelocityLimit)
body!.pointee.w = cpfclamp(body!.pointee.w * damping + body!.pointee.t * body!.pointee.i_inv * dt, -w_limit, w_limit)
// Reset forces.
body!.pointee.f = cpvzero
//to check body sanity
cpBodySetTorque(body, 0.0)
}
|
998a4979ad73cae65d1c0dcecda5117d
| 38.236842 | 190 | 0.694165 | false | false | false | false |
KHPhoneTeam/connect-ios
|
refs/heads/master
|
simpleVoIP/KHPSettingsViewController.swift
|
gpl-3.0
|
1
|
//
// KHPSettingsViewController.swift
// KHPhoneConnect
//
// Created by armand on 07-01-17.
// Copyright © 2017 KHPhone. All rights reserved.
//
import UIKit
@objc class KHPSettingsViewController: UIViewController {
@IBOutlet var chooseEndpointButton: UIButton!
@IBOutlet weak var qrButton: UIButton!
@IBOutlet weak var sipAdressTextField: UITextField!
@IBOutlet weak var portNumberTextField: UITextField!
@IBOutlet weak var userPhoneNumberTextField: UITextField!
@IBOutlet var chooseEndpointTextField: UITextField!
let reachability = Reachability()
let pickerFeeder = PickerViewFeeder()
@objc var focusOnUserPhoneNeeded : Bool = false
var cameFromQR : Bool = false
fileprivate let pickerView = ToolbarPickerView()
var endpoints: [Endpoint]?
fileprivate func setupUI() {
sipAdressTextField.text = ""
chooseEndpointTextField.inputView = pickerView
chooseEndpointTextField.inputAccessoryView = pickerView.toolbar
pickerView.delegate = pickerFeeder
pickerView.toolbarDelegate = self
if let sip = KHPhonePrefUtil.returnSipURL() {
pickerView.selectRow(pickerFeeder.rowForSip(sip: sip), inComponent: 0, animated: false)
}
sipAdressTextField.delegate = self
portNumberTextField.delegate = self
userPhoneNumberTextField.delegate = self
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 0 / 255, green: 0 / 255, blue: 0 / 255, alpha: 1)
let doneButton = UIBarButtonItem(title: "Sluit", style: .done, target: self, action: #selector(donePressedOnKeyboard))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
toolBar.sizeToFit()
userPhoneNumberTextField.inputAccessoryView = toolBar
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
if focusOnUserPhoneNeeded { // this is used when the user has tapped on a setup link
focusOnUserPhoneNumber()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateTextFields()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if cameFromQR {
focusOnUserPhoneNumber()
cameFromQR = false
}
}
@IBAction func closeButtonPressed(sender: UIButton){
self.dismiss(animated: true) {
}
}
@IBAction func doneButtonPressed(sender: UIButton){
view.endEditing(true)
}
@objc func donePressedOnKeyboard(){
view.endEditing(true)
}
func focusOnUserPhoneNumber (){
userPhoneNumberTextField?.becomeFirstResponder()
}
func updateTextFields(){
if let congregationName = KHPhonePrefUtil.returnCongregationName() {
chooseEndpointTextField.text = congregationName
} else {
chooseEndpointTextField.text = "-- kies een gemeente --"
}
let sipPort = KHPhonePrefUtil.returnSipPort()
if (sipPort != 0) {
portNumberTextField.text = String(sipPort);
} else {
portNumberTextField.text = "5011"; // default
}
if let sipAddress = KHPhonePrefUtil.returnSipURL() {
sipAdressTextField.text = sipAddress;
} else {
sipAdressTextField.text = ""; // default
}
if let userPhoneNumber = KHPhonePrefUtil.returnUserPhoneNumber() {
userPhoneNumberTextField.text = userPhoneNumber;
} else {
userPhoneNumberTextField.text = ""; // default
}
}
func updatePreferences(){
let sipPort = Int(portNumberTextField.text!)
let sipAddress = sipAdressTextField.text!
let userPhoneNumber = userPhoneNumberTextField.text!
KHPhonePrefUtil.save(sipPort: sipPort!)
KHPhonePrefUtil.save(sipAddress: sipAddress)
KHPhonePrefUtil.save(userPhoneNumber: userPhoneNumber)
// register account!
}
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.
if segue.identifier == "GQSegue" {
cameFromQR = true
}
}
}
extension KHPSettingsViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
updatePreferences()
}
}
extension KHPSettingsViewController: ToolbarPickerViewDelegate {
func didTapDone() {
let selectedRow = pickerView.selectedRow(inComponent: 0)
print("Selected row: \(selectedRow)")
pickerFeeder.didSelect(row: selectedRow)
chooseEndpointTextField.resignFirstResponder()
// updateUI
updateTextFields()
}
func didTapCancel() {
chooseEndpointTextField.resignFirstResponder()
}
}
|
f51b93e1edc302d71a58e2773ad94ced
| 29.011765 | 122 | 0.712858 | false | false | false | false |
Performador/Pickery
|
refs/heads/master
|
Pickery/PhotosAsset.swift
|
mit
|
1
|
//
// PhotosAsset.swift
// Pickery
//
// Created by Okan Arikan on 8/1/16.
//
//
import Foundation
import Photos
import AVFoundation
import ReactiveSwift
/// Represents a photo image request in flight
///
/// It will cancel the request when deallocated
class PhotosRequest {
/// The request identifier to cancellation
let requestId : PHImageRequestID
/// Ctor
init(requestId: PHImageRequestID) {
self.requestId = requestId
}
/// Cancel the request
deinit {
PhotoLibrary.sharedInstance.cachingImageManager.cancelImageRequest(requestId)
}
}
/// Represents an asset in the photo library
class PhotosAsset : Asset {
/// The unique identifier
var identifier : String { return localIdentifier }
/// The pixel resolution
var pixelSize : CGSize { return CGSize(width: CGFloat(phAsset.pixelWidth), height: CGFloat(phAsset.pixelHeight)) }
/// The duration
var durationSeconds : TimeInterval { return phAsset.duration }
/// Where?
var location : CLLocation? { return phAsset.location }
/// When
var dateCreated : Date? { return phAsset.creationDate }
/// Return the associated resource types
var resourceTypes : [ ResourceType ] { return PHAssetResource.assetResources(for: phAsset).flatMap { ResourceType(resourceType: $0.type) } }
/// Is this a live photo?
var isLivePhoto : Bool { return phAsset.mediaSubtypes.contains(.photoLive) }
/// Is this a video?
var isVideo : Bool { return phAsset.mediaType == .video }
/// The photos asset
let phAsset : PHAsset
/// The local identifier in case we need it
var localIdentifier : String { return phAsset.localIdentifier }
/// If we have this asset already uploaded, here it is
var remoteAsset : RemoteAsset?
/// Ctor
init(phAsset: PHAsset) {
// Save the class members
self.phAsset = phAsset
}
/// Request an image
func requestImage(for view: AssetImageView) -> AnyObject? {
assertMainQueue()
// We must be the active asset being displayed
assert(view.asset?.identifier == identifier)
let desiredPixelSize = view.pixelSize
let cacheKey = "\(phAsset.localIdentifier)_\(desiredPixelSize)"
// Already exists in the image cache?
if let image = ImageCache.sharedInstance.imageForAsset(key: cacheKey) {
view.image = image
} else {
let placeholderKey = phAsset.localIdentifier
// Got a placeholder image?
if let placeholder = ImageCache.sharedInstance.imageForAsset(key: placeholderKey) {
view.image = placeholder
}
// We will have to request this image
let myIdentifier = identifier
let options = PHImageRequestOptions()
options.resizeMode = .exact
options.deliveryMode = .highQualityFormat
options.isSynchronous = false
options.isNetworkAccessAllowed = true
// Fire off the request
return PhotosRequest(requestId:
PhotoLibrary
.sharedInstance
.cachingImageManager
.requestImage(for: phAsset,
targetSize: desiredPixelSize,
contentMode: .default,
options: options,
resultHandler: { (image: UIImage?, info: [AnyHashable : Any]?) in
assertMainQueue()
// Were able to get an image?
if let image = image {
// Add the image to cache
ImageCache.sharedInstance.addImageForAsset(key: cacheKey, image: image)
// Have existing placeholder already larger than this?
if let placeholder = ImageCache.sharedInstance.imageForAsset(key: placeholderKey), placeholder.size.width > image.size.width {
// Nothing to do, existing placeholder is already good
} else {
// No placeholder or it's size is smaller than this, record it in the cache
ImageCache.sharedInstance.addImageForAsset(key: placeholderKey, image: image)
}
// Set the image if this is still relevant
if view.asset?.identifier == myIdentifier {
view.image = image
}
}
})
)
}
return nil
}
/// Request a player item
///
/// see Asset
func requestPlayerItem(pixelSize: CGSize) -> SignalProducer<AVPlayerItem,NSError> {
// Capture the asset
let phAsset = self.phAsset
return SignalProducer<AVPlayerItem,NSError> { sink, disposible in
// The request options
let options = PHVideoRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
// Let's see if we can create a player item directly
PhotoLibrary
.sharedInstance
.cachingImageManager
.requestPlayerItem(forVideo: phAsset,
options: options,
resultHandler: { (playerItem: AVPlayerItem?, info: [AnyHashable : Any]?) in
// Success?
if let playerItem = playerItem {
sink.send(value: playerItem)
sink.sendCompleted()
} else {
var foundVideo = false
// No player found, request the file
for resource in PHAssetResource.assetResources(for: phAsset) {
if resource.type == .video {
let fileURL = FileManager.tmpURL.appendingPathComponent(UUID().uuidString)
// Configure the resource access options
let options = PHAssetResourceRequestOptions()
options.isNetworkAccessAllowed = true
// Write the data
PHAssetResourceManager
.default()
.writeData(for: resource,
toFile: fileURL,
options: options,
completionHandler: { (error: Swift.Error?) in
// Got an error?
if let error = error {
sink.send(error: error as NSError)
} else {
sink.send(value: AVPlayerItem(asset: AVURLAsset(url: fileURL)))
sink.sendCompleted()
}
})
foundVideo = true
}
}
if foundVideo == false {
sink.send(error: PickeryError.internalAssetNotFound as NSError)
}
}
})
}
}
/// Request a live photo
///
/// see Asset
func requestLivePhoto(pixelSize: CGSize) -> SignalProducer<PHLivePhoto,NSError> {
// Capture asset
let phAsset = self.phAsset
// Fire off the request in a signal producer
return SignalProducer<PHLivePhoto,NSError> { sink, disposible in
let options = PHLivePhotoRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
PhotoLibrary
.sharedInstance
.cachingImageManager
.requestLivePhoto(for: phAsset,
targetSize: pixelSize,
contentMode: PHImageContentMode.aspectFit,
options: options,
resultHandler: { (photo: PHLivePhoto?, info: [AnyHashable : Any]?) in
// Success?
if let photo = photo {
sink.send(value: photo)
}
// Done
sink.sendCompleted()
})
}
}
}
|
10223ffbb55050017f4eab2e42b4ec31
| 38.012195 | 150 | 0.467021 | false | false | false | false |
lenssss/whereAmI
|
refs/heads/master
|
Whereami/Controller/Personal/PersonalMainViewController.swift
|
mit
|
1
|
//
// PersonalMainViewController.swift
// Whereami
//
// Created by WuQifei on 16/2/16.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import Kingfisher
//import SDWebImage
class PersonalMainViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var tableView:UITableView? = nil
var items:[String]? = nil
var logos:[String]? = nil
var currentUser:UserModel? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.setConfig()
// Do any additional setup after loading the view.
self.title = NSLocalizedString("Personal",tableName:"Localizable", comment: "")
self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.customFontWithStyle("Bold", size:18.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()]
self.items = ["Shop","Achievements","Settings","Help","Published"]
self.logos = ["shop","achievements","setting","help","published"]
self.setUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.backgroundColor = UIColor.getNavigationBarColor()
self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default)
self.navigationController?.navigationBar.barTintColor = UIColor.getNavigationBarColor()
currentUser = UserModel.getCurrentUser()
self.tableView?.reloadData()
}
func setUI(){
self.tableView = UITableView(frame: self.view.bounds)
self.tableView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.tableFooterView = UIView()
self.view.addSubview(tableView!)
self.tableView?.registerClass(PersonalHeadTableViewCell.self, forCellReuseIdentifier: "PersonalHeadTableViewCell")
self.tableView?.registerClass(PersonalMainViewCell.self, forCellReuseIdentifier: "PersonalMainViewCell")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else{
return (self.items?.count)!
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 2
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 || section == 1 {
return 13
}
else{
return 0
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 90
}
else{
return 50
}
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor.clearColor()
return view
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("PersonalHeadTableViewCell", forIndexPath: indexPath) as! PersonalHeadTableViewCell
cell.accessoryType = .DisclosureIndicator
cell.userNicknameLabel?.text = currentUser?.nickname
let avatarUrl = currentUser?.headPortraitUrl != nil ? currentUser?.headPortraitUrl : ""
// cell.userImageView?.setImageWithString(avatarUrl!, placeholderImage: UIImage(named: "avator.png")!)
cell.userImageView?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
cell.selectionStyle = .None
return cell
}
else{
let cell = tableView.dequeueReusableCellWithIdentifier("PersonalMainViewCell", forIndexPath: indexPath) as! PersonalMainViewCell
cell.itemNameLabel?.text = self.items![indexPath.row]
cell.logoView?.image = UIImage(named: self.logos![indexPath.row])
cell.accessoryType = .DisclosureIndicator
cell.selectionStyle = .None
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
let viewController = TourRecordsViewController()
viewController.userId = UserModel.getCurrentUser()?.id
viewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(viewController, animated: true)
}
else{
if indexPath.row == 0 {
let viewController = PersonalShopViewController()
viewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(viewController, animated: false)
}
else if indexPath.row == 1 {
let viewController = PersonalAchievementsViewController()
viewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(viewController, animated: true)
}
else if indexPath.row == 2 {
let viewController = PersonalSettingsViewController()
viewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
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.
}
*/
}
|
a19a1deb5e580770d80e4ec9e91d61c8
| 38.816456 | 191 | 0.657129 | false | false | false | false |
DukeLenny/Weibo
|
refs/heads/master
|
Weibo/Weibo/Class/View(视图和控制器)/Main/Controller/WBNavigationController.swift
|
mit
|
1
|
//
// WBNavigationController.swift
// Weibo
//
// Created by LiDinggui on 2017/9/1.
// Copyright © 2017年 DAQSoft. All rights reserved.
//
import UIKit
class WBNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationBar.isHidden = true
}
@objc fileprivate func popVC() {
popViewController(animated: true)
}
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.
}
*/
}
extension WBNavigationController {
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
var title = BarButtonItemTitle
if childViewControllers.count == 1 {
if let rootViewController = childViewControllers.first as? WBBaseViewController {
title = rootViewController.navItem.title ?? BarButtonItemTitle
}
}
if let viewController = viewController as? WBBaseViewController {
viewController.navItem.leftBarButtonItem = UIBarButtonItem(title: title, target: self, action: #selector(popVC))
}
}
super.pushViewController(viewController, animated: animated)
}
}
// MARK: - Rotation
extension WBNavigationController {
override var shouldAutorotate: Bool {
if let topViewController = topViewController {
return topViewController.shouldAutorotate
}
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if let topViewController = topViewController {
return topViewController.supportedInterfaceOrientations
}
return .portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
if let topViewController = topViewController {
return topViewController.preferredInterfaceOrientationForPresentation
}
return .portrait
}
}
|
bb9249e039f6998eddb5ecefd41f1033
| 30.626506 | 128 | 0.665524 | false | false | false | false |
tinypass/piano-sdk-for-ios
|
refs/heads/master
|
PianoAPI/Models/UserDto.swift
|
apache-2.0
|
1
|
import Foundation
@objc(PianoAPIUserDto)
public class UserDto: NSObject, Codable {
/// User's UID
@objc public var uid: String? = nil
/// User's email address
@objc public var email: String? = nil
/// User's first name
@objc public var firstName: String? = nil
/// User's last name
@objc public var lastName: String? = nil
/// User's personal name
@objc public var personalName: String? = nil
/// User creation date
@objc public var createDate: Date? = nil
public enum CodingKeys: String, CodingKey {
case uid = "uid"
case email = "email"
case firstName = "first_name"
case lastName = "last_name"
case personalName = "personal_name"
case createDate = "create_date"
}
}
|
7a1ea764f251012f04acefc7c4b80799
| 24.03125 | 48 | 0.615481 | false | false | false | false |
vimask/ClientCodeGen
|
refs/heads/master
|
ClientCodeGen/Misc/ApiClient.swift
|
mit
|
1
|
//
// ApiClient.swift
// JSONExport
//
// Created by Vinh Vo on 4/19/17.
// Copyright © 2017 Vinh Vo. All rights reserved.
//
import Foundation
typealias ServiceResponse = (_ success: Bool, _ jsonString: String?) -> ()
enum HttpMethod:String {
case get = "GET"
case post = "POST"
case put = "PUT"
case detele = "DELETE"
}
class ApiClient{
static let shared = ApiClient()
// MARK: - Perform a GET Request
func makeGetRequest(strURL:String, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse)
{
let urlRequest = clientURLRequest(urlString: strURL, headers: headers)
get(request: urlRequest) { (result, jsonString) in
runOnUiThread{
onCompletion(result, jsonString)
}
}
}
// MARK: - Perform a POST Request
func makePostRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) {
let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers)
post(request: urlRequest) { (result, jsonString) in
runOnUiThread{
onCompletion(result, jsonString)
}
}
}
// MARK: - Perform a PUST Request
func makePutRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) {
let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers)
put(request: urlRequest) { (result, jsonString) in
runOnUiThread{
onCompletion(result, jsonString)
}
}
}
// MARK: - Perform a DELETE Request
func makeDeleteRequest(strURL: String, body: [String:Any]?, headers:[String:Any]? = nil, onCompletion: @escaping ServiceResponse) {
let urlRequest = clientURLRequest(urlString: strURL,params: body, headers: headers)
delete(request: urlRequest) { (result, jsonString) in
runOnUiThread{
onCompletion(result, jsonString)
}
}
}
// MARK: -
private func clientURLRequest(urlString: String, params:[String:Any]? = nil, headers:[String:Any]? = nil) -> NSMutableURLRequest {
let request = NSMutableURLRequest(url: URL(string: urlString)!)
//set params
if let params = params {
// var paramString = ""
// for (key, value) in params {
// let escapedKey = key.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
// let escapedValue = (value as AnyObject).addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
// paramString += "\(String(describing: escapedKey))=\(String(describing: escapedValue))&"
// }
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
// request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
} catch let error as NSError {
print(error)
}
}
//set headers
if let headers = headers {
for (key,value) in headers {
request.setValue("\(value)", forHTTPHeaderField: key)
}
}
return request
}
// MARK: -
private func post(request: NSMutableURLRequest, completion: @escaping ServiceResponse) {
dataTask(request: request, method: "POST", completion: completion)
}
private func put(request: NSMutableURLRequest, completion: @escaping ServiceResponse) {
dataTask(request: request, method: "PUT", completion: completion)
}
private func get(request: NSMutableURLRequest, completion: @escaping ServiceResponse) {
dataTask(request: request, method: "GET", completion: completion)
}
private func delete(request: NSMutableURLRequest, completion: @escaping ServiceResponse) {
dataTask(request: request, method: "DELETE", completion: completion)
}
// MARK: - Data task
private func dataTask(request: NSMutableURLRequest, method: String, completion: @escaping ServiceResponse) {
request.httpMethod = method
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let data = data {
var jsonString = String(data: data, encoding: String.Encoding.utf8)
do {
let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: [])
let data1 = try JSONSerialization.data(withJSONObject: jsonData, options: JSONSerialization.WritingOptions.prettyPrinted)
jsonString = String(data: data1, encoding: String.Encoding.utf8)
} catch let error as NSError {
print(error)
}
if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode {
completion(true, jsonString )
} else {
completion(false, jsonString)
}
}
}.resume()
}
}
|
39b181ecf173b14202dc9dba37eb56af
| 36.096154 | 142 | 0.577328 | false | false | false | false |
sivakumarscorpian/INTPushnotification1
|
refs/heads/master
|
REIOSSDK/REiosViews.swift
|
mit
|
1
|
//
// ResulticksViews.swift
// INTPushNotification
//
// Created by Sivakumar on 14/9/17.
// Copyright © 2017 Interakt. All rights reserved.
//
import UIKit
class REiosViews: NSObject {
// MARK: Show quick survey
class func addQuickSurvey() {
let podBundle = Bundle(for: REiosRatingVc.self)
let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle")
let bundle = Bundle(url: bundleURL!)
let storyboard = UIStoryboard(name: "INTMain", bundle: bundle)
let childView = storyboard.instantiateViewController(withIdentifier: "SIDQuickSurvey") as! REiosQuickSurveyVc
if let topVc:UIViewController = UIApplication.topViewController() {
topVc.addChildViewController(childView)
childView.view.frame = topVc.view.bounds
topVc.view.addSubview(childView.view)
topVc.navigationController?.isNavigationBarHidden = true
childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childView.didMove(toParentViewController: topVc)
topVc.navigationController?.isNavigationBarHidden = true
}
}
// MARK: Show rating
class func addRatingChildView() {
let podBundle = Bundle(for: REiosRatingVc.self)
let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle")
let bundle = Bundle(url: bundleURL!)
let storyboard = UIStoryboard(name: "INTMain", bundle: bundle)
let childView = storyboard.instantiateViewController(withIdentifier: "SIDRating") as! REiosRatingVc
if let topVc:UIViewController = UIApplication.topViewController() {
topVc.addChildViewController(childView)
childView.view.frame = topVc.view.bounds
topVc.view.addSubview(childView.view)
topVc.navigationController?.isNavigationBarHidden = true
childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childView.didMove(toParentViewController: topVc)
topVc.navigationController?.isNavigationBarHidden = true
}
}
// MARK: Show rich image
class func addRichImage() {
let podBundle = Bundle(for: REiosRatingVc.self)
let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle")
let bundle = Bundle(url: bundleURL!)
let storyboard = UIStoryboard(name: "INTMain", bundle: bundle)
let childView = storyboard.instantiateViewController(withIdentifier: "SIDRichImage") as! REiosRichImageVc
if let topVc:UIViewController = UIApplication.topViewController() {
topVc.addChildViewController(childView)
childView.view.frame = topVc.view.bounds
topVc.view.addSubview(childView.view)
topVc.navigationController?.isNavigationBarHidden = true
childView.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childView.didMove(toParentViewController: topVc)
topVc.navigationController?.isNavigationBarHidden = true
}
}
}
|
274e11265225d25bf61c3b0644cc3e73
| 39.075 | 117 | 0.661572 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww
|
refs/heads/master
|
TestKitchen/TestKitchen/classes/cookbook/homePage/controller/CookbookViewController.swift
|
mit
|
1
|
//
// CookbookViewController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CookbookViewController: BaseViewController {
//滚动视图
var scrollView:UIScrollView?
//食材首页推荐视图
private var recommendView:CBRecommendView?
//首页食材视图
private var foodView:CBMaterialView?
//首页分类视图
private var categoryView:CBMaterialView?
//导航的标题视图
private var segCtrl:KTCSegmentCtrl?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
createMyNav()
self.createHomePageView()
downloadRecommendData()
downloadFoodData()
downloadCategoryData()
}
//下载分类的数据
func downloadCategoryData(){
let params = ["methodName":"CategoryIndex"]
let downloader = KTCDownloder()
downloader.delegate = self
downloader.type = .Category
downloader.postWithUrl(kHostUrl, params: params)
}
//下载食材的数据
func downloadFoodData(){
//参数
let dict = ["methodName":"MaterialSubtype"]
let downloader = KTCDownloder()
downloader.delegate = self
downloader.type = .FoodMaterial
downloader.postWithUrl(kHostUrl, params: dict)
}
//初始化视图
func createHomePageView(){
self.automaticallyAdjustsScrollViewInsets = false
//1.创建滚动视图
scrollView = UIScrollView()
scrollView!.pagingEnabled = true
scrollView!.showsHorizontalScrollIndicator = false
scrollView?.delegate = self
view.addSubview(scrollView!)
//给滚动视图添加约束
scrollView!.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0))
}
//2.创建容器视图
let containerView = UIView.createView()
scrollView!.addSubview(containerView)
containerView.snp_makeConstraints { (make) in
make.edges.equalTo(self.scrollView!)
make.height.equalTo(self.scrollView!)
}
//推荐
recommendView = CBRecommendView()
containerView.addSubview(recommendView!)
recommendView?.snp_makeConstraints(closure: {
(make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo(containerView)
})
//食材
foodView = CBMaterialView()
foodView?.backgroundColor = UIColor.redColor()
containerView.addSubview(foodView!)
foodView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((recommendView?.snp_right)!)
})
//分类
categoryView = CBMaterialView()
categoryView?.backgroundColor = UIColor.purpleColor()
containerView.addSubview(categoryView!)
categoryView?.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(kScreenWidth)
make.left.equalTo((foodView?.snp_right)!)
})
//修改容器视图的大小
containerView.snp_makeConstraints { (make) in
make.right.equalTo(categoryView!)
}
}
//下载推荐数据
func downloadRecommendData(){
let dict = ["methodName":"SceneHome"]
let downloader = KTCDownloder()
downloader.type = .Recommend
downloader.delegate = self
downloader.postWithUrl(kHostUrl, params: dict)
}
//导航视图
func createMyNav(){
//标题位置
segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"])
navigationItem.titleView = segCtrl
//设置代理
segCtrl?.delegate = self
//扫一扫功能
addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true)
//搜索功能
addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false)
}
func scanAction(){
}
func searchAction(){
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//首页推荐的部分的方法
//食材课程分集显示
func gotoFoodCoursePage(link:String){
let startRange = NSString(string: link).rangeOfString("#")
let endRange = NSString(string: link).rangeOfString("#", options: NSStringCompareOptions.BackwardsSearch, range: NSMakeRange(0, link.characters.count),locale:nil)
let id = NSString(string: link).substringWithRange(NSMakeRange(startRange.location+1, endRange.location-startRange.location-1))
//跳转界面
let foodCourseCtrl = FoodCourseController()
foodCourseCtrl.serialId = id
navigationController?.pushViewController(foodCourseCtrl, animated: true)
}
//显示首页推荐的数据
func showRecommendData(model:CBRecommendModel){
recommendView?.model = model
//点击事件
recommendView?.clickClosure = {
(title:String?,link:String) in
if link.hasPrefix("app://food_course_series") == true {
//食材课程分集显示
//第一个#
self.gotoFoodCoursePage(link)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension CookbookViewController:KTCDownloaderDelegate{
func downloader(downloader: KTCDownloder, didFailWithError error: NSError) {
}
func downloader(downloader: KTCDownloder, didFinishWithData data: NSData?) {
if downloader.type == .Recommend {
if let jsonData = data {
let model = CBRecommendModel.parseModel(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self?.showRecommendData(model)
})
}
}else if downloader.type == .FoodMaterial{
// let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print(str!)
if let jsonData = data {
let model = CBMaterialModel.parseModelWithData(jsonData)
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self?.foodView?.model = model
})
}
}else if downloader.type == .Category{
if let jsonData = data{
let model = CBMaterialModel.parseModelWithData(jsonData)
//会主线程刷新
dispatch_async(dispatch_get_main_queue(), {
[weak self] in
self?.categoryView?.model = model
})
}
}
}
}
//KTCSegCtrl的代理
extension CookbookViewController:KTCSegmentCtrlDelegate{
func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) {
// scrollView?.contentOffset = CGPointMake(kScreenWidth*CGFloat(index), 0)
//点击按钮切换视图(有动画效果)
scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true)
}
}
//UIScrollView的代理
extension CookbookViewController:UIScrollViewDelegate{
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width)
segCtrl?.selectIndex = index
}
}
|
8604bf95c5de143e8ab1db948cc8a4aa
| 26.268371 | 170 | 0.561687 | false | false | false | false |
saku/PixivLTSample
|
refs/heads/master
|
PixivLTSample/base/BaseSwiftViewController.swift
|
mit
|
1
|
//
// BaseSwiftViewController.swift
// PixivLTSample
//
// Created by saku on 2014/09/28.
// Copyright (c) 2014 Yoichiro Sakurai. All rights reserved.
//
import UIKit
class BaseSwiftViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
var button : UIButton;
button = UIButton(frame: CGRectMake(0, 0, 200, 40))
button.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 - 100);
button.setTitle("showObjcAlert", forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.addTarget(self, action: "showObjcAlert", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
button = UIButton(frame: CGRectMake(0, 0, 200, 40))
button.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2 + 100);
button.setTitle("showSwiftAlert", forState: .Normal)
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
button.addTarget(self, action: "showSwiftAlert", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func showObjcAlert() {
showObjcAlertView()
}
func showSwiftAlert() {
showSwiftAlertView(self)
}
}
|
434cf09ae8882b69adcfaacaf339a325
| 33.35 | 109 | 0.671761 | false | false | false | false |
ioramashvili/BeforeAfterSlider
|
refs/heads/master
|
BeforeAfterSlider/BeforeAfterView.swift
|
mit
|
1
|
import UIKit
import Foundation
@IBDesignable
public class BeforeAfterView: UIView {
fileprivate var leading: NSLayoutConstraint!
fileprivate var originRect: CGRect!
@IBInspectable
public var image1: UIImage = UIImage() {
didSet {
imageView1.image = image1
}
}
@IBInspectable
public var image2: UIImage = UIImage() {
didSet {
imageView2.image = image2
}
}
@IBInspectable
public var thumbColor: UIColor = UIColor.white {
didSet {
thumb.backgroundColor = thumbColor
}
}
fileprivate lazy var imageView2: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
fileprivate lazy var imageView1: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
fileprivate lazy var image1Wrapper: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.clipsToBounds = true
return v
}()
fileprivate lazy var thumbWrapper: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
v.clipsToBounds = true
return v
}()
fileprivate lazy var thumb: UIView = {
let v = UIView()
v.backgroundColor = UIColor.white
v.translatesAutoresizingMaskIntoConstraints = false
v.clipsToBounds = true
return v
}()
lazy fileprivate var setupLeadingAndOriginRect: Void = {
self.leading.constant = self.frame.width / 2
self.layoutIfNeeded()
self.originRect = self.image1Wrapper.frame
}()
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override public func layoutSubviews() {
super.layoutSubviews()
_ = setupLeadingAndOriginRect
}
}
extension BeforeAfterView {
fileprivate func initialize() {
image1Wrapper.addSubview(imageView1)
addSubview(imageView2)
addSubview(image1Wrapper)
thumbWrapper.addSubview(thumb)
addSubview(thumbWrapper)
NSLayoutConstraint.activate([
imageView2.topAnchor.constraint(equalTo: topAnchor, constant: 0),
imageView2.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0),
imageView2.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0),
imageView2.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0)
])
leading = image1Wrapper.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0)
NSLayoutConstraint.activate([
image1Wrapper.topAnchor.constraint(equalTo: topAnchor, constant: 0),
image1Wrapper.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0),
image1Wrapper.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0),
leading
])
NSLayoutConstraint.activate([
imageView1.topAnchor.constraint(equalTo: image1Wrapper.topAnchor, constant: 0),
imageView1.bottomAnchor.constraint(equalTo: image1Wrapper.bottomAnchor, constant: 0),
imageView1.trailingAnchor.constraint(equalTo: image1Wrapper.trailingAnchor, constant: 0)
])
NSLayoutConstraint.activate([
thumbWrapper.topAnchor.constraint(equalTo: image1Wrapper.topAnchor, constant: 0),
thumbWrapper.bottomAnchor.constraint(equalTo: image1Wrapper.bottomAnchor, constant: 0),
thumbWrapper.leadingAnchor.constraint(equalTo: image1Wrapper.leadingAnchor, constant: -20),
thumbWrapper.widthAnchor.constraint(equalToConstant: 40)
])
NSLayoutConstraint.activate([
thumb.centerXAnchor.constraint(equalTo: thumbWrapper.centerXAnchor, constant: 0),
thumb.centerYAnchor.constraint(equalTo: thumbWrapper.centerYAnchor, constant: 0),
thumb.widthAnchor.constraint(equalTo: thumbWrapper.widthAnchor, multiplier: 1),
thumb.heightAnchor.constraint(equalTo: thumbWrapper.widthAnchor, multiplier: 1)
])
leading.constant = frame.width / 2
thumb.layer.cornerRadius = 20
imageView1.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true
let tap = UIPanGestureRecognizer(target: self, action: #selector(gesture(sender:)))
thumbWrapper.isUserInteractionEnabled = true
thumbWrapper.addGestureRecognizer(tap)
}
@objc func gesture(sender: UIPanGestureRecognizer) {
let translation = sender.translation(in: self)
switch sender.state {
case .began, .changed:
var newLeading = originRect.origin.x + translation.x
newLeading = max(newLeading, 20)
newLeading = min(frame.width - 20, newLeading)
leading.constant = newLeading
layoutIfNeeded()
case .ended, .cancelled:
originRect = image1Wrapper.frame
default: break
}
}
}
|
dea8eb4a315164cac9b6589ca06eb8b5
| 32.107784 | 103 | 0.639537 | false | false | false | false |
kouky/Algorithms
|
refs/heads/master
|
Algorithms.playground/Pages/List Abstract Data Type.xcplaygroundpage/Contents.swift
|
mit
|
1
|
// List Abstract Data Type
// https://en.wikipedia.org/wiki/List_(abstract_data_type)
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Michael Koukoullis <http://github.com/kouky>
indirect enum List<T> {
case Cons(T, List<T>)
case Nil
}
extension List {
func head() -> T {
switch self {
case .Cons(let head, _):
return head
case .Nil:
fatalError("Invalid")
}
}
func tail() -> List {
switch self {
case .Cons(_, let tail):
return tail
case .Nil:
return List.Nil
}
}
func foldl<U>(start: U, _ f: (U, T) -> U) -> U {
switch self {
case let .Cons(head, tail):
return tail.foldl(f(start, head), f)
case .Nil:
return start
}
}
func size() -> Int {
return self.foldl(0) { (acc, _) -> Int in
return acc + 1
}
}
func reverse() -> List {
return self.foldl(List.Nil) { (acc, item) -> List in
return List.Cons(item, acc)
}
}
func filter(f: T -> Bool) -> List {
let x = self.foldl(List.Nil) { (acc, item) -> List in
if f(item) {
return List.Cons(item, acc)
}
else {
return acc
}
}
return x.reverse()
}
func map<U>(f: T -> U) -> List<U> {
let x = self.foldl(List<U>.Nil) { (acc: List<U>, item: T) -> List<U> in
return List<U>.Cons(f(item), acc)
}
return x.reverse()
}
}
extension List : CustomStringConvertible {
var description: String {
switch self {
case let .Cons(value, list):
return "\(value)," + list.description
case .Nil:
return ""
}
}
}
// Shorthand list construction
infix operator ~ { associativity right }
func ~ <T> (left: T, right: List<T>) -> List<T> {
return List.Cons(left, right)
}
// Create lists of Int
let z = 1 ~ 2 ~ 3 ~ 4 ~ 5 ~ List.Nil
z
// Create lists of tuples
let x = ("grapes", 5) ~ ("apple", 8) ~ List.Nil
x
// Head and Tail
z.head()
z.tail()
// Foldl
z.foldl(0, +)
z.foldl(1, *)
z.foldl(List.Nil) { (acc, x) in
(x * 3) ~ acc
}
// Functions implemeted with foldl
z.size()
z.reverse()
z.filter { (item) -> Bool in
item % 2 == 0
}
z.map { (item) -> Int in
item * 2
}
z.map { (item) -> String in
"$\(item).00"
}
|
37f17e6d29ef3896f28f46632c203e91
| 19.675 | 79 | 0.483676 | false | false | false | false |
librerose/iAdSample
|
refs/heads/master
|
src/iAdSample/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// iAdSample
//
// Created by Meng on 15/11/4.
// Copyright © 2015年 Libre Rose. All rights reserved.
//
import UIKit
import iAd
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.edgesForExtendedLayout = .None
view.addSubview(tableView)
_ = iAdView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var tableView: UITableView {
if nil == _tableView {
_tableView = UITableView(frame: view.bounds, style: .Plain)
}
return _tableView!
}
var _tableView: UITableView?
var iAdView: ADBannerView {
if nil == _iAdView {
_iAdView = ADBannerView(frame: CGRect.zero)
_iAdView?.delegate = self
}
return _iAdView!
}
var _iAdView: ADBannerView?
}
extension ViewController: ADBannerViewDelegate {
func bannerViewDidLoadAd(banner: ADBannerView!) {
tableView.tableHeaderView = banner
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
tableView.tableHeaderView = nil
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
}
}
|
53536dc33e0d6b8ba82b76f7672e7c22
| 22.836066 | 89 | 0.616231 | false | false | false | false |
StartAppsPe/StartAppsKitExtensions
|
refs/heads/master
|
Sources/TableViewExtensions.swift
|
mit
|
1
|
//
// TableViewExtensions.swift
// StartAppsKitExtensionsPackageDescription
//
// Created by Gabriel Lanata on 16/10/17.
//
#if os(iOS)
import UIKit
extension UITableView {
public func updateHeaderViewFrame() {
guard let headerView = self.tableHeaderView else { return }
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let fitSize = CGSize(width: self.frame.size.width, height: 3000)
let height = headerView.systemLayoutSizeFitting(fitSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow).height
var headerViewFrame = headerView.frame
headerViewFrame.size.height = height
headerView.frame = headerViewFrame
self.tableHeaderView = headerView
}
public func updateFooterViewFrame() {
guard let footerView = self.tableFooterView else { return }
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
let fitSize = CGSize(width: self.frame.size.width, height: 3000)
let height = footerView.systemLayoutSizeFitting(fitSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow).height
var footerViewFrame = footerView.frame
footerViewFrame.size.height = height
footerView.frame = footerViewFrame
self.tableFooterView = footerView
}
}
extension UITableViewCell {
public func autoLayoutHeight(_ tableView: UITableView? = nil) -> CGFloat {
if let tableView = tableView { // where frame.size.width == 0 {
frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width-13, height: 9999)
contentView.frame = frame
}
layoutIfNeeded()
let targetSize = CGSize(width: tableView!.frame.size.width-13, height: 10)
let size = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority(rawValue: 999))
return size.height+1
}
}
extension UITableView {
public func hideBottomSeparator(showLast: Bool = false) {
let inset = separatorInset.left
tableFooterView = UIView(frame: CGRect(x: inset, y: 0, width: frame.size.width-inset, height: 0.5))
tableFooterView!.backgroundColor = showLast ? separatorColor : UIColor.clear
}
public func showBottomSeparator() {
tableFooterView = nil
}
}
extension UITableView {
public func scrollToTop(animated: Bool) {
self.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: animated)
}
}
#endif
|
8586fb2da43ce38d6fa2738a5d449e0d
| 36.880952 | 186 | 0.570082 | false | false | false | false |
DrGo/LearningSwift
|
refs/heads/master
|
PLAYGROUNDS/APPLE/Patterns.playground/section-19.swift
|
gpl-3.0
|
2
|
let trainOne = Train()
let trainTwo = Train()
let trainThree = Train()
trainTwo.status = .Delayed(minutes: 2)
trainThree.status = .Delayed(minutes: 8)
|
876b6d2c9849d60804651e7ff224aa18
| 24.333333 | 40 | 0.728477 | false | false | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Modules/ServiceTerms/Modal/Modal/ServiceTermsModalScreenViewModel.swift
|
apache-2.0
|
1
|
// File created from ScreenTemplate
// $ createScreen.sh Modal/Show ServiceTermsModalScreen
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
final class ServiceTermsModalScreenViewModel: ServiceTermsModalScreenViewModelType {
// MARK: - Properties
// MARK: Private
private let serviceTerms: MXServiceTerms
// MARK: Public
var serviceUrl: String {
return serviceTerms.baseUrl
}
var serviceType: MXServiceType {
return serviceTerms.serviceType
}
var policies: [MXLoginPolicyData]?
var alreadyAcceptedPoliciesUrls: [String] = []
weak var viewDelegate: ServiceTermsModalScreenViewModelViewDelegate?
weak var coordinatorDelegate: ServiceTermsModalScreenViewModelCoordinatorDelegate?
// MARK: - Setup
init(serviceTerms: MXServiceTerms) {
self.serviceTerms = serviceTerms
}
// MARK: - Public
func process(viewAction: ServiceTermsModalScreenViewAction) {
switch viewAction {
case .load:
self.loadTerms()
case .display(let policy):
self.coordinatorDelegate?.serviceTermsModalScreenViewModel(self, displayPolicy: policy)
case .accept:
self.acceptTerms()
case .decline:
self.coordinatorDelegate?.serviceTermsModalScreenViewModelDidDecline(self)
}
}
// MARK: - Private
private func loadTerms() {
self.update(viewState: .loading)
self.serviceTerms.terms({ [weak self] (terms, alreadyAcceptedTermsUrls) in
guard let self = self else {
return
}
let policies = self.processTerms(terms: terms)
self.policies = policies
self.alreadyAcceptedPoliciesUrls = alreadyAcceptedTermsUrls ?? []
self.update(viewState: .loaded(policies: policies, alreadyAcceptedPoliciesUrls: self.alreadyAcceptedPoliciesUrls))
}, failure: { [weak self] error in
guard let self = self else {
return
}
self.update(viewState: .error(error))
})
}
private func acceptTerms() {
self.update(viewState: .loading)
self.serviceTerms.agree(toTerms: self.termsUrls, success: { [weak self] in
guard let self = self else {
return
}
self.update(viewState: .accepted)
// Send a notification to update the identity service immediately.
if self.serviceTerms.serviceType == MXServiceTypeIdentityService {
let userInfo = [MXIdentityServiceNotificationIdentityServerKey: self.serviceTerms.baseUrl]
NotificationCenter.default.post(name: .MXIdentityServiceTermsAccepted, object: nil, userInfo: userInfo)
}
// Notify the delegate.
self.coordinatorDelegate?.serviceTermsModalScreenViewModelDidAccept(self)
}, failure: { [weak self] (error) in
guard let self = self else {
return
}
self.update(viewState: .error(error))
})
}
private func processTerms(terms: MXLoginTerms?) -> [MXLoginPolicyData] {
if let policies = terms?.policiesData(forLanguage: Bundle.mxk_language(), defaultLanguage: Bundle.mxk_fallbackLanguage()) {
return policies
} else {
MXLog.debug("[ServiceTermsModalScreenViewModel] processTerms: Error: No terms for \(String(describing: terms))")
return []
}
}
private var termsUrls: [String] {
guard let policies = self.policies else {
return []
}
return policies.map({ return $0.url })
}
private func update(viewState: ServiceTermsModalScreenViewState) {
self.viewDelegate?.serviceTermsModalScreenViewModel(self, didUpdateViewState: viewState)
}
}
|
35b2526d634f4ba2562457981a1da9ca
| 32.014706 | 131 | 0.642094 | false | false | false | false |
thecb4/SwiftCRUD
|
refs/heads/master
|
Example/Tests/ModelSpec.swift
|
mit
|
1
|
//
// ModelSpec.swift
// KanoMapp
//
// Created by Cavelle Benjamin on 28/2/15.
// Copyright (c) 2015 The CB4. All rights reserved.
//
import Quick
import Nimble
import SwiftCRUD_Example
import SwiftCRUD
import CoreData
class CRUDHelper {
var name:String!
var type:NSManagedObject.Type
var count = 0
init(type:NSManagedObject.Type, name:String!) {
self.type = type
self.name = name
}
func crudClass<T>() -> T { return type as! T }
func params() -> Dictionary<String,AnyObject> {
var _params:[String:AnyObject] = [:]
switch name {
case "SuperHero":
_params["name"] = "Scarlet Witch"
_params["name"] = "Hex"
return _params
default: ()
}
return Dictionary()
}
}
class SharedCRUDSpecConfiguration: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("CRUD class") { (sharedExampleContext: SharedExampleContext) in
let helper = sharedExampleContext()["crud-class"] as! CRUDHelper
let sut = helper.type
let sutName = helper.name
it("should should have an entity name = \(sutName)") {
let expectedName = sutName
let actualName = sut.entityName()
expect(expectedName).to(equal(actualName))
}
it("should have initial count of 0 for entity type as \(sutName)") {
sut.deleteAll()
let expectedValue = 0
let actualValue = sut.count()
expect(actualValue).to(equal(expectedValue))
}
it("should create a new entity type with parameters as \(sutName)") {
let expectedID = NSNumber(integer: 1)
let params = helper.params()
let actualID = sut.createWithParameters(params);
expect(actualID).to(equal(actualID))
let entity:NSManagedObject = sut.readOne(actualID!)!
let paramKey:String = params.keys.first!
let actualValue:String = params[paramKey]! as! String
let expectedValue:String = entity.valueForKey(paramKey)! as! String
expect(expectedValue).to(equal(actualValue))
}
it("should create a new entity") {
let expectedID = NSNumber(integer: 1)
let actualID = sut.create()
expect(actualID).to(equal(actualID))
}
it("should read an entity of type \(sutName)") {
let crudID = sut.create()!
let entity:NSManagedObject? = sut.readOne(crudID)
expect(entity!).toNot(beNil())
}
it("should update an entity of type \(sutName)") {
let crudID = sut.create()!
let params = helper.params()
let updated = sut.updateOne(crudID, params)
expect(updated).to(beTrue())
}
it("should delete entity of type \(sutName)") {
let crudID = sut.create()!
let deleted = sut.deleteOne(crudID)
expect(deleted).to(beTrue())
let deletedEntity:NSManagedObject? = sut.readOne(crudID)
expect(deletedEntity).to(beNil())
}
}
}
}
class ProductSpec: QuickSpec {
override func spec() {
let manager = CoreDataManager.sharedInstance
beforeEach {
manager.resetContext();
}
itBehavesLike("CRUD class") { [ "crud-class" : CRUDHelper(type: SuperHero.self, name: "SuperHero") ] }
}
}
|
b914e721b46f224ab6779a067da4b556
| 22.037736 | 106 | 0.56047 | false | false | false | false |
magi82/MGUtils
|
refs/heads/master
|
Sources/Commons/etc/CommonReactive.swift
|
mit
|
1
|
//
// CommonReactive.swift
// Common
//
// Created by Byung Kook Hwang on 2017. 9. 21..
// Copyright © 2017년 apptube. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
extension Reactive where Base: UIImageView {
public var isHighlight: Binder<Bool> {
return Binder(self.base) { view, highlight in
view.isHighlighted = highlight
}
}
}
extension Reactive where Base: UIControl {
public var tap: ControlEvent<Void> {
return controlEvent(.touchUpInside)
}
}
extension Reactive where Base: UICollectionViewFlowLayout {
public var footerSize: Binder<CGSize> {
return Binder(self.base) { view, size in
view.footerReferenceSize = size
}
}
}
extension Reactive where Base: UIButton {
public var selectedTitle: Binder<(title: String, selectedText: String)> {
return Binder(self.base) { view, value in
view.setTitle(value.title, for: .normal)
view.isSelected = (value.title != value.selectedText)
}
}
}
extension Reactive where Base: UIViewController {
public func popVC(animated: Bool = true) -> Binder<Void> {
return Binder(self.base) { (view, _) -> () in
view.navigationController?.popViewController(animated: animated)
}
}
public func pushVC(animated: Bool = true) -> Binder<ProvideObjectProtocol> {
return Binder(self.base) { (view, object) -> () in
view.navigationController?.pushViewController(object.viewController, animated: animated)
}
}
public func dismiss(animated: Bool = true, completion: (() -> Void)? = nil) -> Binder<Void> {
return Binder(self.base) { (view, _) -> () in
view.dismiss(animated: animated, completion: completion)
}
}
public func present(animated: Bool = true, completion: (() -> Void)? = nil) -> Binder<ProvideObjectProtocol> {
return Binder(self.base) { (view, object) -> () in
view.present(object.viewController, animated: animated, completion: completion)
}
}
}
|
35bddde0c7e0d256d4c5505471482686
| 26.873239 | 112 | 0.675594 | false | false | false | false |
SpiciedCrab/MGRxKitchen
|
refs/heads/master
|
Example/MGRxKitchen/TableViewTestViewModel.swift
|
mit
|
1
|
//
// TableViewTestViewModel.swift
// RxMogo
//
// Created by Harly on 2017/8/7.
// Copyright © 2017年 Harly. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import MGRxActivityIndicator
import MGRxKitchen
import MGBricks
import Result
internal class MGItem {
var name: String = ""
init(str: String) {
name = str
}
}
internal class TableViewTestViewModel: HaveRequestRx, PageableJSONRequest, PageExtensible {
var pageOutputer: PublishSubject<MGPage> = PublishSubject<MGPage>()
typealias PageJSONType = SuperDemo
var jsonOutputer: PublishSubject<SuperDemo> = PublishSubject<SuperDemo>()
var loadingActivity: ActivityIndicator = ActivityIndicator()
var errorProvider: PublishSubject<RxMGError> = PublishSubject<RxMGError>()
var firstPage: PublishSubject<Void> = PublishSubject()
var nextPage: PublishSubject<Void> = PublishSubject()
//Output
var finalPageReached: PublishSubject<Void> = PublishSubject()
let disposeBag: DisposeBag = DisposeBag()
let service: MockService = MockService()
var serviceDriver: Observable<[Demo]>!
init() {
}
func initial() {
// pagedRequest(request: <#T##(MGPage) -> Observable<Result<([Element], MGPage), MGAPIError>>#>)
// let requestObser: Observable<Result<([Demo], MGPage), MGAPIError>> = interuptPage(origin: self.service.providePageJSONMock(on: 1)) { json -> [Demo] in
// return json.demos
// }
//
// serviceDriver = pagedRequest(request: { _ in requestObser })
serviceDriver = pagedRequest(request: { page -> Observable<Result<([String : Any], MGPage), MGAPIError>> in
return self.service.providePageJSONMock(on: page.currentPage)
}) { json -> [Demo] in
return json.demos
}
}
func sectionableData() -> Observable<[MGSection<MGItem>]> {
let item1 = MGItem(str: "1")
let item2 = MGItem(str: "2")
let item3 = MGItem(str: "4")
let item4 = MGItem(str: "5")
let section1 = MGSection(header: "header1", items: [item1, item2])
let section2 = MGSection(header: "header2", items: [item3, item4])
return Observable.of([section1, section2])
}
}
|
4a9f280c1f2c21398da83ec2b4335414
| 26.108434 | 160 | 0.660444 | false | false | false | false |
Automattic/Automattic-Tracks-iOS
|
refs/heads/trunk
|
Sources/Remote Logging/Crash Logging/TestHelpers.swift
|
gpl-2.0
|
1
|
import Foundation
import ObjectiveC
import Sentry
typealias EventLoggingCallback = (Event) -> ()
typealias ShouldSendEventCallback = (Event?, Bool) -> ()
private var errorLoggingCallback: EventLoggingCallback? = nil
private var messageLoggingCallback: EventLoggingCallback? = nil
private var eventSendCallback: ShouldSendEventCallback? = nil
internal extension CrashLoggingDataProvider {
var didLogErrorCallback: EventLoggingCallback? {
get { return errorLoggingCallback }
set { errorLoggingCallback = newValue }
}
var didLogMessageCallback: EventLoggingCallback? {
get { return messageLoggingCallback }
set { messageLoggingCallback = newValue }
}
}
|
3b46783acbf5bcc6363b77a93cf9cd31
| 29.565217 | 63 | 0.755334 | false | false | false | false |
ubi-naist/SenStick
|
refs/heads/master
|
SenStickSDK/SenStickSDK/UVSensorService.swift
|
mit
|
1
|
//
// UVSensorService.swift
// SenStickSDK
//
// Created by AkihiroUehara on 2016/05/24.
// Copyright © 2016年 AkihiroUehara. All rights reserved.
//
import Foundation
public enum UVSensorRange : UInt16, CustomStringConvertible
{
case uvRangeDefault = 0x00
public var description : String {
switch self {
case .uvRangeDefault: return "uvRangeDefault"
}
}
}
struct UVRawData
{
var rawValue : UInt16
init(rawValue:UInt16)
{
self.rawValue = rawValue
}
// 物理センサーの1uW/cm^2あたりのLBSの値
static func getLSBperuWcm2(_ range: UVSensorRange) -> Double
{
switch range {
case .uvRangeDefault: return (1.0 / 5.0)
}
}
static func unpack(_ data: [Byte]) -> UVRawData
{
let value = UInt16.unpack(data[0..<2])
return UVRawData(rawValue: value!)
}
}
public struct UVSensorData : SensorDataPackableType
{
public var uv: Double
public init(uv: Double) {
self.uv = uv
}
public typealias RangeType = UVSensorRange
public static func unpack(_ range:UVSensorRange, value: [UInt8]) -> UVSensorData?
{
guard value.count >= 2 else {
return nil
}
let rawData = UVRawData.unpack(value)
let LSBperuWcm = UVRawData.getLSBperuWcm2(range)
//debugPrint("\(rawData), LSBperuWcm:\(LSBperuWcm)")
return UVSensorData(uv: (Double(rawData.rawValue) / LSBperuWcm));
}
}
// センサー各種のベースタイプ, Tはセンサデータ独自のデータ型, Sはサンプリングの型、
open class UVSensorService: SenStickSensorService<UVSensorData, UVSensorRange>
{
required public init?(device:SenStickDevice)
{
super.init(device: device, sensorType: SenStickSensorType.ultraVioletSensor)
}
}
|
028d71a2612d09c8d51beffdd983f92a
| 22.381579 | 85 | 0.633089 | false | false | false | false |
neotron/SwiftBot-Discord
|
refs/heads/master
|
SwiftBot/AppDelegate.swift
|
gpl-3.0
|
1
|
//
// AppDelegate.swift
// SwiftBot
//
// Created by David Hedbor on 2/20/16.
// Copyright © 2016 NeoTron. All rights reserved.
//
import Foundation
import AppKit
import DiscordAPI
import Fabric
import Crashlytics
private class CrashlyticsLogger : Logger {
override init() {
UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true])
Fabric.with([Crashlytics.self])
super.init()
}
override func log(_ message: String, args: CVaListPointer) {
CLSNSLogv(message, args)
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
fileprivate var main: SwiftBotMain?
@IBOutlet weak var window: NSWindow!
func launchWatchDog() {
guard let watcherPath = Bundle.main.path(forResource: "SwiftBotKeeperAliver", ofType: nil, inDirectory: "../MacOS"),
let selfPath = Bundle.main.path(forResource: "SwiftBot", ofType: nil, inDirectory: "../MacOS") else {
LOG_ERROR("Can't find the watcher.")
return
}
let task = Process()
task.launchPath = watcherPath
task.arguments = [selfPath, "\(getpid())"]
task.launch()
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
Logger.instance = CrashlyticsLogger();
let args = ProcessInfo.processInfo.arguments
Config.development = args.contains("--development")
#if false
if !Config.development {
launchWatchDog()
}
#endif
self.main = SwiftBotMain()
main?.runWithDoneCallback({
LOG_INFO("Exiting gracefully.")
NSApp.terminate(self.main!)
})
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
|
4aa588a5f361a177267c3812ecbf1b85
| 25.463768 | 124 | 0.646221 | false | false | false | false |
KagasiraBunJee/TryHard
|
refs/heads/master
|
TryHard/QExpandVC.swift
|
mit
|
1
|
//
// QExpandVC.swift
// TryHard
//
// Created by Sergey on 5/13/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
class QExpandVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let tableViewContent:[Array<String>] = [
[
"Value 1",
"Value 2",
"Value 3"
],
[
"Value 4",
"Value 5",
"Value 6"
]
]
var hiddenSections = NSMutableDictionary()
var hiddenSection = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
//MARK:- UITapGestureRecognizer
func sectionTapped(gesture:UIGestureRecognizer) {
if let view = gesture.view {
let section = view.tag
if hiddenSections.objectForKey(section) != nil {
hiddenSections.removeObjectForKey(section)
} else {
hiddenSections.setObject(section, forKey: section)
}
let set = NSMutableIndexSet()
set.addIndex(section)
tableView.reloadSections(set, withRowAnimation: UITableViewRowAnimation.None)
}
}
//MARK:- UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if hiddenSections.objectForKey(section) != nil {
return 0
}
return tableViewContent[section].count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tableViewContent.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("expandCell")!
cell.textLabel!.text = tableViewContent[indexPath.section][indexPath.row]
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRectMake(0, 0, self.tableView.frame.width, 50))
view.backgroundColor = UIColor.whiteColor()
view.tag = section
let label = UILabel(frame: view.frame)
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.sectionTapped(_:)))
view.addGestureRecognizer(gesture)
var isHidden = ""
if hiddenSections.objectForKey(section) != nil {
isHidden = " hidden"
}
let title = "Section \(section+1)"+isHidden
label.text = title
view.addSubview(label)
return view
}
}
|
26f62c23f4c8103ef3109aa8c8716ff4
| 26.731481 | 109 | 0.584307 | false | false | false | false |
AngryLi/Onmyouji
|
refs/heads/master
|
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchResultViewModel.swift
|
mit
|
8
|
//
// SearchResultViewModel.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/3/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class SearchResultViewModel {
let searchResult: WikipediaSearchResult
var title: Driver<String>
var imageURLs: Driver<[URL]>
let API = DefaultWikipediaAPI.sharedAPI
let $: Dependencies = Dependencies.sharedDependencies
init(searchResult: WikipediaSearchResult) {
self.searchResult = searchResult
self.title = Driver.never()
self.imageURLs = Driver.never()
let URLs = configureImageURLs()
self.imageURLs = URLs.asDriver(onErrorJustReturn: [])
self.title = configureTitle(URLs).asDriver(onErrorJustReturn: "Error during fetching")
}
// private methods
func configureTitle(_ imageURLs: Observable<[URL]>) -> Observable<String> {
let searchResult = self.searchResult
let loadingValue: [URL]? = nil
return imageURLs
.map(Optional.init)
.startWith(loadingValue)
.map { URLs in
if let URLs = URLs {
return "\(searchResult.title) (\(URLs.count) pictures)"
}
else {
return "\(searchResult.title) (loading…)"
}
}
.retryOnBecomesReachable("⚠️ Service offline ⚠️", reachabilityService: $.reachabilityService)
}
func configureImageURLs() -> Observable<[URL]> {
let searchResult = self.searchResult
return API.articleContent(searchResult)
.observeOn($.backgroundWorkScheduler)
.map { page in
do {
return try parseImageURLsfromHTMLSuitableForDisplay(page.text as NSString)
} catch {
return []
}
}
.shareReplayLatestWhileConnected()
}
}
|
044c3c2e6b62f64e7b5be59147635017
| 27.710145 | 105 | 0.594144 | false | true | false | false |
IngmarStein/swift
|
refs/heads/master
|
test/Driver/options-interpreter.swift
|
apache-2.0
|
24
|
// RUN: not %swift_driver -deprecated-integrated-repl -emit-module 2>&1 | %FileCheck -check-prefix=IMMEDIATE_NO_MODULE %s
// RUN: not %swift_driver -emit-module 2>&1 | %FileCheck -check-prefix=IMMEDIATE_NO_MODULE %s
// REQUIRES: swift_interpreter
// IMMEDIATE_NO_MODULE: error: unsupported option '-emit-module'
// RUN: %swift_driver -### %s | %FileCheck -check-prefix INTERPRET %s
// INTERPRET: -interpret
// RUN: %swift_driver -### %s a b c | %FileCheck -check-prefix ARGS %s
// ARGS: -- a b c
// RUN: %swift_driver -### -parse-stdlib %s | %FileCheck -check-prefix PARSE_STDLIB %s
// RUN: %swift_driver -### -parse-stdlib | %FileCheck -check-prefix PARSE_STDLIB %s
// PARSE_STDLIB: -parse-stdlib
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -resource-dir /RSRC/ %s | %FileCheck -check-prefix=CHECK-RESOURCE-DIR-ONLY %s
// CHECK-RESOURCE-DIR-ONLY: # DYLD_LIBRARY_PATH=/RSRC/macosx{{$}}
// RUN: %swift_driver -### -target x86_64-unknown-linux-gnu -resource-dir /RSRC/ %s | %FileCheck -check-prefix=CHECK-RESOURCE-DIR-ONLY-LINUX${LD_LIBRARY_PATH+_LAX} %s
// CHECK-RESOURCE-DIR-ONLY-LINUX: # LD_LIBRARY_PATH=/RSRC/linux{{$}}
// CHECK-RESOURCE-DIR-ONLY-LINUX_LAX: # LD_LIBRARY_PATH=/RSRC/linux{{$|:}}
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -L/foo/ %s | %FileCheck -check-prefix=CHECK-L %s
// CHECK-L: # DYLD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/macosx$}}
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-L2 %s
// CHECK-L2: # DYLD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/macosx$}}
// RUN: env DYLD_LIBRARY_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-L2-ENV %s
// CHECK-L2-ENV: # DYLD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/macosx:/abc/$}}
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 %s | %FileCheck -check-prefix=CHECK-NO-FRAMEWORKS %s
// RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 %s | %FileCheck -check-prefix=CHECK-NO-FRAMEWORKS %s
// CHECK-NO-FRAMEWORKS-NOT: DYLD_FRAMEWORK_PATH
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -F/foo/ %s | %FileCheck -check-prefix=CHECK-F %s
// CHECK-F: -F /foo/
// CHECK-F: #
// CHECK-F: DYLD_FRAMEWORK_PATH=/foo/{{$}}
// RUN: %swift_driver -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ %s | %FileCheck -check-prefix=CHECK-F2 %s
// CHECK-F2: -F /foo/
// CHECK-F2: -F /bar/
// CHECK-F2: #
// CHECK-F2: DYLD_FRAMEWORK_PATH=/foo/:/bar/{{$}}
// RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ %s | %FileCheck -check-prefix=CHECK-F2-ENV %s
// CHECK-F2-ENV: -F /foo/
// CHECK-F2-ENV: -F /bar/
// CHECK-F2-ENV: #
// CHECK-F2-ENV: DYLD_FRAMEWORK_PATH=/foo/:/bar/:/abc/{{$}}
// RUN: env DYLD_FRAMEWORK_PATH=/abc/ %swift_driver_plain -### -target x86_64-apple-macosx10.9 -F/foo/ -F/bar/ -L/foo2/ -L/bar2/ %s | %FileCheck -check-prefix=CHECK-COMPLEX %s
// CHECK-COMPLEX: -F /foo/
// CHECK-COMPLEX: -F /bar/
// CHECK-COMPLEX: #
// CHECK-COMPLEX-DAG: DYLD_FRAMEWORK_PATH=/foo/:/bar/:/abc/{{$| }}
// CHECK-COMPLEX-DAG: DYLD_LIBRARY_PATH={{/foo2/:/bar2/:[^:]+/lib/swift/macosx($| )}}
// RUN: %swift_driver -### -target x86_64-unknown-linux-gnu -L/foo/ %s | %FileCheck -check-prefix=CHECK-L-LINUX${LD_LIBRARY_PATH+_LAX} %s
// CHECK-L-LINUX: # LD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/linux$}}
// CHECK-L-LINUX_LAX: # LD_LIBRARY_PATH={{/foo/:[^:]+/lib/swift/linux($|:)}}
// RUN: env LD_LIBRARY_PATH=/abc/ %swift_driver_plain -### -target x86_64-unknown-linux-gnu -L/foo/ -L/bar/ %s | %FileCheck -check-prefix=CHECK-LINUX-COMPLEX${LD_LIBRARY_PATH+_LAX} %s
// CHECK-LINUX-COMPLEX: # LD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/linux:/abc/$}}
// CHECK-LINUX-COMPLEX_LAX: # LD_LIBRARY_PATH={{/foo/:/bar/:[^:]+/lib/swift/linux:/abc/($|:)}}
|
0ba8089d1544e5daf4bfbb4f08530fdd
| 57.074627 | 183 | 0.650989 | false | false | true | false |
digipost/ios
|
refs/heads/master
|
Digipost/Constants.swift
|
apache-2.0
|
1
|
//
// Copyright (C) Posten Norge AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct Constants {
struct APIClient {
static let taskCounter = "taskCounter"
static var baseURL : String {
return k__SERVER_URI__
}
struct AttributeKey {
static let location = "location"
static let subject = "subject"
static let folderId = "folderId"
static let identifier = "id"
static let name = "name"
static let icon = "icon"
static let folder = "folder"
static let token = "token"
static let device = "device"
}
}
struct FolderName {
static let inbox = "INBOX"
static let folder = "FOLDER"
}
struct HTTPHeaderKeys {
static let accept = "Accept"
static let contentType = "Content-Type"
}
struct Error {
static let apiErrorDomainOAuthUnauthorized = "oAuthUnauthorized"
static let apiClientErrorDomain = "APIManagerErrorDomain"
static let noOAuthTokenPresent = "APInoOAuthTokenPresent"
enum Code : Int {
case oAuthUnathorized = 4001
case uploadFileDoesNotExist = 4002
case uploadFileTooBig = 4003
case uploadLinkNotFoundInRootResource = 4004
case uploadFailed = 4005
case needHigherAuthenticationLevel = 4006
case unknownError = 4007
case noOAuthTokenPresent = 4008
}
static let apiClientErrorScopeKey = "scope"
}
struct Account {
static let viewControllerIdentifier = "accountViewController"
static let refreshContentNotification = "refreshContentNotificiation"
static let accountCellIdentifier = "accountCellIdentifier"
static let mainAccountCellIdentifier = "mainAccountCellIdentifier"
static let accountCellNibName = "AccountTableViewCell"
static let mainAccountCellNibName = "MainAccountTableViewCell"
}
struct Invoice {
static let InvoiceBankTableViewNibName = "InvoiceBankTableView"
static let InvoiceBankTableViewCellNibName = "InvoiceBankTableViewCell"
}
struct Composer {
static let imageModuleCellIdentifier = "ImageModuleCell"
static let textModuleCellIdentifier = "TextModuleCell"
}
struct Recipient {
static let name = "name"
static let recipient = "recipient"
static let address = "address"
static let mobileNumber = "mobile-number"
static let organizationNumber = "organisation-number"
static let uri = "uri"
static let digipostAddress = "digipost-address"
}
}
func == (left:Int, right:Constants.Error.Code) -> Bool {
return left == right.rawValue
}
func == (left:Constants.Error.Code, right:Int) -> Bool {
return left.rawValue == right
}
|
58fdbb2ccbac35dc3d175e6b7973e576
| 30.303571 | 79 | 0.640616 | false | false | false | false |
nzaghini/b-viper
|
refs/heads/master
|
Weather/Modules/WeatherDetail/Core/Presenter/WeatherDetailPresenter.swift
|
mit
|
2
|
import Foundation
struct WeatherDetailViewModel {
let cityName: String
let temperature: String
let forecasts: [WeatherDetailForecastViewModel]
}
struct WeatherDetailForecastViewModel {
let day: String
let temp: String
}
protocol WeatherDetailPresenter: class {
func loadContent()
}
class WeatherDetailDefaultPresenter: WeatherDetailPresenter {
let interactor: WeatherDetailInteractor
weak var view: WeatherDetailView?
required init(interactor: WeatherDetailInteractor, view: WeatherDetailView) {
self.interactor = interactor
self.view = view
}
// MARK: - WeatherDetailPresenter
func loadContent() {
self.view?.displayLoading()
self.interactor.fetchWeather {(result) in
switch result {
case .success(let weather):
let vm = self.buildViewModel(weather)
self.view?.displayWeatherDetail(vm)
break
case .failure(let reason):
self.view?.displayError(reason.localizedDescription)
}
}
}
fileprivate func buildViewModel(_ data: Weather) -> WeatherDetailViewModel {
var forecasts = [WeatherDetailForecastViewModel]()
let df = DateFormatter()
df.dateFormat = "EEEE"
var date = Date()
for temp in data.forecastInDays {
let day = df.string(from: date)
let forecast = WeatherDetailForecastViewModel(day: day, temp: temp + data.temperatureUnit)
forecasts.append(forecast)
date = date.addingTimeInterval(24 * 60 * 60)
}
return WeatherDetailViewModel(cityName: data.locationName,
temperature: data.temperature + data.temperatureUnit,
forecasts: forecasts)
}
}
|
63507a2a7c5811afc107cfd4d460f702
| 28.569231 | 102 | 0.603018 | false | false | false | false |
vandadnp/chorizo
|
refs/heads/master
|
Chorizo/ChorizoUrlConnection.swift
|
mit
|
1
|
//
// ChorizoUrlConnection.swift
// Chorizo
//
// Created by Vandad Nahavandipoor on 06/11/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
import Foundation
class ChorizoAsyncUrlConnection{
typealias ChorizoUrlConnectionSuccessBlock = (data: NSData) -> ()
typealias ChorizoUrlConnectionFailureBlock = (error: NSError) -> ()
private var request = NSMutableURLRequest()
var timeout: NSTimeInterval = 20.0
var successBlock: ChorizoUrlConnectionSuccessBlock?
var failureBlock: ChorizoUrlConnectionFailureBlock?
var url: NSURL{
set{
self.request.URL = newValue
}
get{
return self.request.URL!
}
}
init(url: String){
self.url = NSURL(string: url)!
}
func setBody(data: NSData) -> Self{
self.request.HTTPBody = data
return self
}
func setHeaders(headers: [NSObject : AnyObject]) -> Self{
self.request.allHTTPHeaderFields = headers
return self
}
func onSuccess(successBlock: ChorizoUrlConnectionSuccessBlock) -> Self{
self.successBlock = successBlock
return self
}
func onFailure(failureBlock: ChorizoUrlConnectionFailureBlock) -> Self{
self.failureBlock = failureBlock
return self
}
func start() -> Self{
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error != nil{
self.failureBlock?(error: error)
} else {
self.successBlock?(data: data)
}
}
return self
}
}
|
7b1ea38f7acf2cb914418ecef3179d1d
| 24.811594 | 164 | 0.598876 | false | false | false | false |
olkakusiak/SearchInGitHub
|
refs/heads/master
|
SearchInGitHub/RepoDetailsViewController.swift
|
mit
|
1
|
//
// RepoDetailsViewController.swift
// SearchInGitHub
//
// Created by Aleksandra Kusiak on 27.11.2016.
// Copyright © 2016 ola. All rights reserved.
//
import UIKit
class RepoDetailsViewController: UIViewController {
@IBOutlet weak var userAvatar: UIImageView!
@IBOutlet weak var userDetailsContainer: UIView!
@IBOutlet weak var fullNameLabel: UILabel!
@IBOutlet weak var languageLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var numberOfStarsLabel: UILabel!
@IBOutlet weak var numberOfForksLabel: UILabel!
@IBOutlet weak var numberOfIssuesLabel: UILabel!
@IBOutlet weak var numberOfWatchersLabel: UILabel!
@IBOutlet weak var starsLabel: UILabel!
@IBOutlet weak var forksLabel: UILabel!
@IBOutlet weak var issuesLabel: UILabel!
@IBOutlet weak var watchersLabel: UILabel!
var singleRepo: SingleRepoData?
var userLogin: String?
var repoName: String?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
DataManager.instance.getSingleRepo(userLogin: userLogin!, repoName: repoName!, repoDownloaded: {repo in
self.singleRepo = repo
self.reloadLabels()
}, error: {error in
print("error with getting single repo")
})
}
func setupView(){
userDetailsContainer.backgroundColor = UIColor.forkMidnightBlue
userAvatar.layer.cornerRadius = 10.0
userAvatar.clipsToBounds = true
userAvatar.layer.borderWidth = 1
userAvatar.layer.borderColor = UIColor.cloudsGrey.cgColor
fullNameLabel.textColor = UIColor.cloudsGrey
languageLabel.textColor = UIColor.cloudsGrey
descriptionLabel.textColor = UIColor.cloudsGrey
starsLabel.textColor = UIColor.forkMidnightBlue
numberOfStarsLabel.textColor = UIColor.forkMidnightBlue
forksLabel.textColor = UIColor.forkMidnightBlue
numberOfForksLabel.textColor = UIColor.forkMidnightBlue
issuesLabel.textColor = UIColor.forkMidnightBlue
numberOfIssuesLabel.textColor = UIColor.forkMidnightBlue
watchersLabel.textColor = UIColor.forkMidnightBlue
numberOfWatchersLabel.textColor = UIColor.forkMidnightBlue
userAvatar.image = #imageLiteral(resourceName: "placeholder")
fullNameLabel.text = ""
languageLabel.text = ""
descriptionLabel.text = ""
numberOfStarsLabel.text = ""
numberOfForksLabel.text = ""
numberOfIssuesLabel.text = ""
numberOfWatchersLabel.text = ""
}
func reloadLabels(){
if let repo = singleRepo{
userAvatar.sd_setImage(with: URL(string: repo.avatarURL), placeholderImage: #imageLiteral(resourceName: "placeholder"))
fullNameLabel.text = repo.fullName
languageLabel.text = "language: \(repo.language)"
descriptionLabel.text = repo.description
numberOfStarsLabel.text = "\(repo.stars)"
numberOfForksLabel.text = "\(repo.forks)"
numberOfIssuesLabel.text = "\(repo.issues)"
numberOfWatchersLabel.text = "\(repo.watchers)"
}
}
}
|
efba17af85b47613feae443048d07ceb
| 31.689655 | 122 | 0.768284 | false | false | false | false |
Mattmlm/codepath-twitter-redux
|
refs/heads/master
|
Codepath Twitter/Codepath Twitter/ComposeTweetViewController.swift
|
mit
|
1
|
//
// ComposeTweetViewController.swift
// Codepath Twitter
//
// Created by admin on 10/4/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController {
@IBOutlet weak var tweetField: UITextField!
var replyToTweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#55ACEE");
self.navigationController?.navigationBar.isTranslucent = false;
self.navigationController?.navigationBar.tintColor = UIColor.white;
if replyToTweet != nil {
self.tweetField.text = "@\((replyToTweet!.user?.screenname)!) "
}
self.tweetField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCancelButtonPressed(sender: Any) {
dismiss(animated: true, completion: nil);
}
@IBAction func onTweetButtonPressed(sender: Any) {
// let dict = NSMutableDictionary()
// dict["status"] = tweetField.text!
// if replyToTweet != nil {
// dict["in_reply_to_status_id"] = replyToTweet!.idString!
// }
// TwitterClient.sharedInstance.composeTweetWithCompletion(dict) { (tweet, error) -> () in
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.dismiss(animated:true, completion: nil);
// })
// }
}
/*
// 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.
}
*/
}
|
855779ccb3fa44b882a71c6afa34353d
| 30.75 | 125 | 0.645206 | false | false | false | false |
MartinOSix/DemoKit
|
refs/heads/master
|
dSwift/SwiftDemoKit/SwiftDemoKit/CollectionViewAnimationCell.swift
|
apache-2.0
|
1
|
//
// CollectionViewAnimationCell.swift
// SwiftDemoKit
//
// Created by runo on 17/5/5.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class CollectionViewAnimationCell: UICollectionViewCell {
let imageV = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth-20, height: 100))
let textV = UITextView(frame: CGRect(x: 0, y: 110, width: kScreenWidth-20, height: 30))
let backBtn = UIButton(frame: CGRect(x: 10, y: 10, width: 40, height: 40))
var backBtnClickBlock: (()->())?
override init(frame: CGRect) {
super.init(frame: frame)
imageV.contentMode = .center
imageV.clipsToBounds = true
textV.font = UIFont.systemFont(ofSize: 14)
textV.isUserInteractionEnabled = false
backBtn.setImage(#imageLiteral(resourceName: "Back-icon"), for: .normal)
backBtn.isHidden = true
backBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
backgroundColor = UIColor.gray
addSubview(imageV)
addSubview(textV)
addSubview(backBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleCellSelected() {
backBtn.isHidden = false
superview?.bringSubview(toFront: self)
}
func backBtnClick() {
backBtn.isHidden = true
backBtnClickBlock!()
}
func preparaCell(model : CellModel) {
imageV.frame = CGRect(x: 0, y: 0, width: kScreenWidth-20, height: 100)
textV.frame = CGRect(x: 0, y: 110, width: kScreenWidth-20, height: 30)
imageV.image = model.img
textV.text = model.title
}
}
|
ab736b684a0a9409074957c59d06743f
| 22.613333 | 92 | 0.614342 | false | false | false | false |
theScud/Lunch
|
refs/heads/wip
|
lunchPlanner/UI/SplashViewController.swift
|
apache-2.0
|
1
|
//
// SplashViewController.swift
// lunchPlanner
//
// Created by Sudeep Kini on 04/11/16.
// Copyright © 2016 TestLabs. All rights reserved.
//
import UIKit
import CoreLocation
class SplashViewController: UIViewController,CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var gotlocation = false
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
// Getting user Location
//Location Manager Request for Locations
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
locationManager.stopUpdatingLocation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let location = locations.last {
if(gotlocation == false ){
appDelegate.appState?.updateUserLocation(location:location)
self.performSegue(withIdentifier:"gotoCategoriesPage", sender: self)
locationManager.stopUpdatingLocation()
gotlocation = true
}
}
}
}
|
7c2753828ef45aeca83a231332f71318
| 27.555556 | 100 | 0.652585 | false | false | false | false |
heigong/Shared
|
refs/heads/master
|
iOS/a_Playgrounds/Basic_Enum.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
// Declare a simple enum
enum Direction: Int {
case North = 0, East, South, West
}
class Road {
var direction: Direction
init(){
direction = .North
}
}
let road = Road()
road.direction.rawValue
// ** Important **
// Init with rawValue returns an optional value
road.direction = Direction(rawValue: 0)!
road.direction.rawValue
switch road.direction {
case .North:
println("North")
default:
println("Other directions")
}
// Associated values
// each member can have its own value, can be different type if needed
enum Barcode{
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
let barcode1 = Barcode.UPCA(1, 2, 3, 4)
let barcode2 = Barcode.QRCode("1234")
// Assorciated values can be extract by switch cases:
switch barcode1 {
case let .UPCA(a, b, c, d):
println("\(a)-\(b)-\(c)-\(d)")
case let .QRCode(a):
println("\(a)")
}
|
98f0ed7d432a84328c8cca2011a4eaa5
| 18.583333 | 70 | 0.658147 | false | false | false | false |
edulpn/rxmoyatest
|
refs/heads/master
|
RxMoyaTest/RxMoyaTest/UserEntity.swift
|
mit
|
1
|
//
// UserEntity.swift
// RxMoyaTest
//
// Created by Eduardo Pinto on 8/30/17.
// Copyright © 2017 Eduardo Pinto. All rights reserved.
//
import Foundation
import ObjectMapper
struct UserEntity: ImmutableMappable {
let login: String
let id: Int
let avatarURL: String
let gravatarId: String
let URL: String
let htmlURL: String
let followersURL: String
let followingURL: String
let gistsURL: String
let starredURL: String
let subscriptionsURL: String
let organizationsURL: String
let reposURL: String
let eventsURL: String
let receivedEventsURL: String
let type: String
let isSiteAdmin: Bool
init(map: Map) throws {
login = try map.value("login")
id = try map.value("id")
avatarURL = try map.value("avatar_url")
gravatarId = try map.value("gravatar_id")
URL = try map.value("url")
htmlURL = try map.value("html_url")
followersURL = try map.value("followers_url")
followingURL = try map.value("following_url")
gistsURL = try map.value("gists_url")
starredURL = try map.value("starred_url")
subscriptionsURL = try map.value("subscriptions_url")
organizationsURL = try map.value("organizations_url")
reposURL = try map.value("repos_url")
eventsURL = try map.value("events_url")
receivedEventsURL = try map.value("received_events_url")
type = try map.value("type")
isSiteAdmin = try map.value("site_admin")
}
}
|
1e1269aedf0aa2bf31f1031c78926727
| 29.58 | 64 | 0.646174 | false | false | false | false |
yoonhg84/ModalPresenter
|
refs/heads/master
|
RxModalityStack/Transition/SlideTransition.swift
|
mit
|
1
|
//
// Created by Chope on 2018. 3. 15..
// Copyright (c) 2018 Chope Industry. All rights reserved.
//
import UIKit
public enum Direction: Equatable {
case up
case down
case left
case right
}
class SlideTransition: TransitionAnimatable {
let duration: TimeInterval = 0.3
let direction: Direction
init(direction: Direction) {
self.direction = direction
}
func animateTransition(to: TransitionInfo, animation: @escaping () -> Void, completion: @escaping () -> Void) {
var frame = to.finalFrame
switch direction {
case .up:
frame.origin.y = frame.height
case .down:
frame.origin.y = -frame.height
case .left:
frame.origin.x = frame.width
case .right:
frame.origin.x = -frame.width
}
to.view.frame = frame
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseInOut,
animations: {
to.view.frame = to.finalFrame
animation()
},
completion: { _ in
completion()
})
}
func animateTransition(from: TransitionInfo, animation: @escaping () -> Void, completion: @escaping () -> Void) {
var frame = from.initialFrame
switch direction {
case .up:
frame.origin.y = frame.height
case .down:
frame.origin.y = -frame.height
case .left:
frame.origin.x = frame.width
case .right:
frame.origin.x = -frame.width
}
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseInOut,
animations: {
from.view.frame = frame
animation()
},
completion: { _ in
completion()
})
}
}
|
bbb214b63fc42af105acde0dd1495562
| 24.12987 | 117 | 0.518863 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS
|
refs/heads/master
|
UberGo/UberGo/DriverAnnotation.swift
|
mit
|
1
|
//
// DriverAnnotation.swift
// UberGo
//
// Created by Nghia Tran on 9/7/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Foundation
import Mapbox
import UberGoCore
class DriverAnnotation: MGLPointAnnotation {
// MARK: - Variable
public lazy var image: MGLAnnotationImage = {
let image = NSImage(imageLiteralResourceName: "driver_mark")
return MGLAnnotationImage(image: image,
reuseIdentifier: "driver_mark")
}()
// MARK: - Variable
fileprivate var driverObj: DriverObj!
fileprivate var vehicleObj: VehicleObj!
fileprivate var driverLocation: UberCoordinateObj!
fileprivate lazy var _calloutController: NSViewController = {
let controller = CalloutAnnotations(nibName: "CalloutAnnotations", bundle: nil)!
controller.setupCallout(mode: .noTimeEstimation, timeETA: nil, calloutTitle: self.title)
return controller
}()
// MARK: - Init
public init?(tripObj: TripObj) {
guard let driverObj = tripObj.driver else { return nil }
guard let driverLocation = tripObj.location else { return nil }
guard let vehicleObj = tripObj.vehicle else { return nil }
self.driverObj = driverObj
self.driverLocation = driverLocation
self.vehicleObj = vehicleObj
super.init()
self.coordinate = driverLocation.coordinate
self.title = "\(driverObj.name) - \(vehicleObj.model) \(vehicleObj.licensePlate)"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - UberAnnotationType
extension DriverAnnotation: UberAnnotationType {
var imageAnnotation: MGLAnnotationImage? {
return image
}
var calloutViewController: NSViewController? {
return _calloutController
}
}
|
f32861bcaea37ddc2e14d62dd118c21c
| 27.828125 | 96 | 0.672087 | false | false | false | false |
mlilback/rc2SwiftClient
|
refs/heads/master
|
Rc2Common/themes/ThemeManager.swift
|
isc
|
1
|
//
// ThemeManager.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import ReactiveSwift
import SwiftyUserDefaults
import MJLLogger
fileprivate extension DefaultsKeys {
static let activeOutputTheme = DefaultsKey<OutputTheme?>("rc2.activeOutputTheme")
static let activeSyntaxTheme = DefaultsKey<SyntaxTheme?>("rc2.activeSyntaxTheme")
}
enum ThemeError: Error {
case notEditable
}
/// wraps the information about a type of theme to allow it to be used generically
public class ThemeWrapper<T: Theme> {
public var themes: [T] { return getThemes() }
public var selectedTheme: T { return getSelectedTheme() }
public var builtinThemes: [T] { return themes.filter { $0.isBuiltin } }
public var userThemes: [T] { return themes.filter { !$0.isBuiltin } }
private var getThemes: () -> [T]
private var getSelectedTheme: () -> T
public init() {
// swiftlint:disable force_cast
if T.self == OutputTheme.self {
getThemes = { return ThemeManager.shared.outputThemes as! [T] }
getSelectedTheme = { return ThemeManager.shared.activeOutputTheme.value as! T }
} else {
getThemes = { return ThemeManager.shared.syntaxThemes as! [T] }
getSelectedTheme = { return ThemeManager.shared.activeSyntaxTheme.value as! T }
}
// swiftlint:enable force_cast
}
}
public class ThemeManager {
public static let shared = ThemeManager()
public var outputThemes: [OutputTheme] { return _outputThemes }
public var syntaxThemes: [SyntaxTheme] { return _syntaxThemes }
private var _outputThemes = [OutputTheme]()
private var _syntaxThemes = [SyntaxTheme]()
public let activeOutputTheme: MutableProperty<OutputTheme>!
public let activeSyntaxTheme: MutableProperty<SyntaxTheme>!
/// sets the active theme based on the type of theme passed as an argument
public func setActive<T: Theme>(theme: T) {
if let otheme = theme as? OutputTheme {
activeOutputTheme.value = otheme
} else if let stheme = theme as? SyntaxTheme {
activeSyntaxTheme.value = stheme
} else {
fatalError("invalid theme")
}
}
@objc private func syntaxThemeChanged(_ note: Notification) {
guard let theme = note.object as? SyntaxTheme else { return }
if activeSyntaxTheme.value.dirty {
do {
try activeSyntaxTheme.value.save()
} catch {
Log.error("error saving theme: \(error)", .core)
}
}
activeSyntaxTheme.value = theme
}
@objc private func outputThemeChanged(_ note: Notification) {
guard let theme = note.object as? OutputTheme else { return }
if theme != activeOutputTheme.value, activeOutputTheme.value.dirty {
do {
try activeOutputTheme.value.save()
} catch {
Log.error("error saving theme: \(error)", .core)
}
}
activeOutputTheme.value = theme
}
/// returns a duplicate of theme with a unique name that has already been inserted in the correct array
public func duplicate<T: Theme>(theme: T) -> T {
let currentNames = existingNames(theme)
let baseName = "\(theme.name) copy"
var num = 0
var curName = baseName
while currentNames.contains(curName) {
num += 1
curName = baseName + " \(num)"
}
let newTheme = clone(theme: theme, name: curName)
setActive(theme: newTheme)
return newTheme
}
/// clone theme by force casting due to limitation in swift type system
private func clone<T: Theme>(theme: T, name: String) -> T {
// swiftlint:disable force_cast
if let outputTheme = theme as? OutputTheme {
let copy = outputTheme.duplicate(name: name) as! T
_outputThemes.append(copy as! OutputTheme)
return copy
} else if let syntaxTheme = theme as? SyntaxTheme {
let copy = syntaxTheme.duplicate(name: name) as! T
_syntaxThemes.append(copy as! SyntaxTheme)
return copy
}
// swiftlint:enable force_try
fatalError()
}
/// returns array of names of existing themes of the same type as instance
private func existingNames<T: Theme>(_ instance: T) -> [String] {
if instance is OutputTheme {
return _outputThemes.map { $0.name }
} else if instance is SyntaxTheme {
return _syntaxThemes.map { $0.name }
}
fatalError()
}
private init() {
_syntaxThemes = BaseTheme.loadThemes()
_outputThemes = BaseTheme.loadThemes()
let activeSyntax = ThemeManager.findDefaultSyntaxTheme(in: _syntaxThemes)
activeSyntaxTheme = MutableProperty(activeSyntax)
let activeOutput = ThemeManager.findDefaultOutputTheme(in: _outputThemes)
activeOutputTheme = MutableProperty(activeOutput)
NotificationCenter.default.addObserver(self, selector: #selector(syntaxThemeChanged(_:)), name: .SyntaxThemeModified, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(outputThemeChanged(_:)), name: .OutputThemeModified, object: nil)
}
private static func findDefaultOutputTheme(in array: [OutputTheme]) -> OutputTheme {
if let theme: OutputTheme = Defaults[.activeOutputTheme] {
return theme
}
//look for one named default
if let defaultTheme = array.first(where: { $0.name == "Default" }) {
return defaultTheme
}
return OutputTheme.defaultTheme as! OutputTheme
}
private static func findDefaultSyntaxTheme(in array: [SyntaxTheme]) -> SyntaxTheme {
if let theme: SyntaxTheme = Defaults[.activeSyntaxTheme] {
return theme
}
//look for one named default
if let defaultTheme = array.first(where: { $0.name == "Default" }) {
return defaultTheme
}
return SyntaxTheme.defaultTheme as! SyntaxTheme
}
}
|
d4d1527c3797603dcbd8c41e700f9bf6
| 31.801205 | 132 | 0.722498 | false | false | false | false |
ukitaka/FPRealm
|
refs/heads/master
|
Tests/CompositionSpec.swift
|
mit
|
2
|
//
// CompositionSpec.swift
// RealmIO
//
// Created by ukitaka on 2017/04/25.
// Copyright © 2017年 waft. All rights reserved.
//
import RealmSwift
import RealmIO
import XCTest
import Quick
import Nimble
class CompositionSpec: QuickSpec {
let realm = try! Realm(configuration: Realm.Configuration(fileURL: nil, inMemoryIdentifier: "for test"))
override func spec() {
super.spec()
let readIO = RealmRO<Void> { _ in }
let writeIO = RealmRW<Void> { _ in }
let readAnyIO = AnyRealmIO<Void>(io: readIO)
let writeAnyIO = AnyRealmIO<Void>(io: writeIO)
it("should be `write` when compose `write` and `write`.") {
let io = writeIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `read` and `write`.") {
let io = readIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `write` and `read`.") {
let io = writeIO.flatMap { _ in readIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `read` when compose `read` and `read`.") {
let io = readIO.flatMap { _ in readIO }
expect(io.isReadOnly).to(beTrue())
}
it("should be `read` when compose `any(read)` and `read`.") {
let io = readAnyIO.flatMap { _ in readIO }
expect(io.isReadOnly).to(beTrue())
}
it("should be `write` when compose `any(read)` and `write`.") {
let io = readAnyIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `any(write)` and `read`.") {
let io = writeAnyIO.flatMap { _ in readIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `any(write)` and `write`.") {
let io = writeAnyIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
}
}
|
80bacc1ba14c07d7b9d9379b4cb53781
| 30.348485 | 108 | 0.560174 | false | false | false | false |
umutbozkurt/10k
|
refs/heads/master
|
10k/Delegates/AppDelegate.swift
|
mit
|
2
|
//
// AppDelegate.swift
// 10k
//
// Created by Umut Bozkurt on 03/09/15.
// Copyright (c) 2015 Umut Bozkurt. All rights reserved.
//
import Cocoa
import RealmSwift
import Fabric
import Crashlytics
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var window: NSWindow!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
let popover = NSPopover()
var eventMonitor: EventMonitor?
func applicationDidFinishLaunching(aNotification: NSNotification)
{
if let button = self.statusItem.button
{
button.image = NSImage(named: "10k")
button.action = Selector("togglePopover:")
}
self.eventMonitor = EventMonitor(mask: NSEventMask.LeftMouseDownMask | NSEventMask.RightMouseDownMask){
[unowned self] event in
if self.popover.shown
{
self.hidePopover(event)
}
}
// Run automatically at startup
let isStartupSet = NSUserDefaults.standardUserDefaults().boolForKey("isStartupSet")
if (!isStartupSet)
{
if (!LaunchStarter.applicationIsInStartUpItems())
{
LaunchStarter.toggleLaunchAtStartup()
}
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isStartupSet")
}
let config = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
})
Realm.Configuration.defaultConfiguration = config
// Realm().write { () -> Void in
// Realm().deleteAll()
// }
if (Realm().objects(Subject).count == 0)
{
self.popover.contentViewController = WelcomeViewController(nibName:"WelcomeViewController", bundle:nil)
}
else
{
self.popover.contentViewController = TrackerViewController(nibName:"TrackerViewController", bundle:nil)
}
Fabric.with([Crashlytics.self])
NSUserDefaults.standardUserDefaults().registerDefaults(["NSApplicationCrashOnExceptions": true])
}
func applicationWillTerminate(aNotification: NSNotification)
{
}
private func showPopover(sender: AnyObject?)
{
if let button = statusItem.button {
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
}
self.eventMonitor?.start()
}
private func hidePopover(sender: AnyObject?)
{
popover.performClose(sender)
self.eventMonitor?.stop()
}
func togglePopover(sender: AnyObject?)
{
if self.popover.shown
{
self.hidePopover(sender)
}
else
{
self.showPopover(sender)
}
}
}
// MARK: NSUserNotificationCenter Delegate Methods
extension AppDelegate: NSUserNotificationCenterDelegate
{
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool
{
return true
}
func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification)
{
if (notification.activationType == NSUserNotificationActivationType.ActionButtonClicked)
{
let subjects = notification.valueForKey("_alternateActionButtonTitles") as! NSArray
let index = notification.valueForKey("_alternateActionIndex") as! Int
// There will be multiple Records on userInfo, delete irrelevant ones and save current subject's Record
let realm = Realm()
realm.write{
let payload = notification.userInfo as! Dictionary<String, Array<String>>
for recordId in payload["recordIDs"]!
{
let record = realm.objectForPrimaryKey(Record.self, key: recordId)!
let relevant = record.subject!.name == (subjects[index] as! String)
if (relevant)
{
record.endedAt = NSDate()
realm.add(record, update: true)
NSLog("FLUSH DB")
}
else
{
realm.delete(record)
}
}
}
}
}
}
|
84837edd1f095a866f5dee05652a9370
| 29.569536 | 133 | 0.578423 | false | false | false | false |
epaga/PenguinMath
|
refs/heads/master
|
PenguinRace/GameScene.swift
|
apache-2.0
|
1
|
//
// GameScene.swift
// PenguinRace
//
// Created by John Goering on 21/06/15.
// Copyright (c) 2015 John Goering. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var screen1: GameScreenNode?
var screen2: GameScreenNode?
var pos1: CGFloat = 0
var pos2: CGFloat = 0
let baseSpeed: CGFloat = 3
var speed1: CGFloat = 2
var speed2: CGFloat = 2
var lastTime: NSTimeInterval = 0
override init(size: CGSize) {
super.init(size:size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
screen1 = GameScreenNode(gameWindow:self.frame, pixelWindow:CGSize(width: 2*self.frame.size.width, height: 2 * self.frame.size.height))
screen2 = GameScreenNode(gameWindow:self.frame, pixelWindow:CGSize(width: 2*self.frame.size.width, height: 2 * self.frame.size.height))
screen2?.screenNode.position = CGPoint(x:self.frame.size.width, y:self.frame.size.height)
screen2?.screenNode.zRotation = CGFloat(M_PI)
self.addChild(screen1!.screenNode)
self.addChild(screen2!.screenNode)
}
override func update(currentTime: CFTimeInterval) {
if lastTime == 0 {
lastTime = currentTime-0.01
}
let elapsedTime = CGFloat(currentTime - lastTime)
if speed1 < baseSpeed {
speed1 *= 1.01
} else if speed1 > baseSpeed {
speed1 *= 0.999
}
if speed2 < baseSpeed {
speed2 *= 1.01
} else if speed2 > baseSpeed {
speed2 *= 0.999
}
pos1 += elapsedTime*speed1
pos2 += elapsedTime*speed2
if pos1 >= 100 {
pos1 = 100
}
if pos2 >= 100 {
pos2 = 100
}
screen1?.moveToPosition(pos1)
screen1?.moveOtherToPosition(pos2)
screen2?.moveToPosition(pos2)
screen2?.moveOtherToPosition(pos1)
lastTime = currentTime
}
}
|
7a088022641335fd2f63868fc925034e
| 30.835821 | 143 | 0.60947 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Shared/ExtensionPoints/ExtensionPointIdentifer.swift
|
mit
|
1
|
//
// ExtensionPointIdentifer.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
enum ExtensionPointIdentifer: Hashable {
#if os(macOS)
case marsEdit
case microblog
#endif
case twitter(String)
case reddit(String)
var extensionPointType: ExtensionPoint.Type {
switch self {
#if os(macOS)
case .marsEdit:
return SendToMarsEditCommand.self
case .microblog:
return SendToMicroBlogCommand.self
#endif
case .twitter:
return TwitterFeedProvider.self
case .reddit:
return RedditFeedProvider.self
}
}
public var userInfo: [AnyHashable: AnyHashable] {
switch self {
#if os(macOS)
case .marsEdit:
return [
"type": "marsEdit"
]
case .microblog:
return [
"type": "microblog"
]
#endif
case .twitter(let screenName):
return [
"type": "twitter",
"screenName": screenName
]
case .reddit(let username):
return [
"type": "reddit",
"username": username
]
}
}
public init?(userInfo: [AnyHashable: AnyHashable]) {
guard let type = userInfo["type"] as? String else { return nil }
switch type {
#if os(macOS)
case "marsEdit":
self = ExtensionPointIdentifer.marsEdit
case "microblog":
self = ExtensionPointIdentifer.microblog
#endif
case "twitter":
guard let screenName = userInfo["screenName"] as? String else { return nil }
self = ExtensionPointIdentifer.twitter(screenName)
case "reddit":
guard let username = userInfo["username"] as? String else { return nil }
self = ExtensionPointIdentifer.reddit(username)
default:
return nil
}
}
public func hash(into hasher: inout Hasher) {
switch self {
#if os(macOS)
case .marsEdit:
hasher.combine("marsEdit")
case .microblog:
hasher.combine("microblog")
#endif
case .twitter(let screenName):
hasher.combine("twitter")
hasher.combine(screenName)
case .reddit(let username):
hasher.combine("reddit")
hasher.combine(username)
}
}
}
|
495e28190a7f9b08d3a5c3cd8fc01555
| 19.919192 | 79 | 0.686142 | false | false | false | false |
dooch/mySwiftStarterApp
|
refs/heads/master
|
SwiftWeather/Essentials.swift
|
mit
|
1
|
//
// Essentials.swift
// SwiftWeather
//
// Created by CB on 4/02/2016.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import Foundation
import UIKit
public class ImageLoader {
var cache = NSCache()
class var sharedLoader : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
let data: NSData? = self.cache.objectForKey(urlString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data!)
self.cache.setObject(data!, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
}
|
b46bc46de85dce630479e5199b9dcbd8
| 31.482143 | 214 | 0.518417 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.