repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GianniCarlo/Audiobook-Player | Shared/Constants.swift | 1 | 4104 | //
// Constants.swift
// BookPlayer
import Foundation
public enum Constants {
public enum UserDefaults: String {
// Application information
case completedFirstLaunch = "userSettingsCompletedFirstLaunch"
case lastPauseTime = "userSettingsLastPauseTime"
case lastPlayedBook = "userSettingsLastPlayedBook"
case appIcon = "userSettingsAppIcon"
case donationMade = "userSettingsDonationMade"
case showPlayer = "userSettingsShowPlayer"
// User preferences
case themeBrightnessEnabled = "userSettingsBrightnessEnabled"
case themeBrightnessThreshold = "userSettingsBrightnessThreshold"
case themeDarkVariantEnabled = "userSettingsThemeDarkVariant"
case systemThemeVariantEnabled = "userSettingsSystemThemeVariant"
case chapterContextEnabled = "userSettingsChapterContext"
case remainingTimeEnabled = "userSettingsRemainingTime"
case smartRewindEnabled = "userSettingsSmartRewind"
case boostVolumeEnabled = "userSettingsBoostVolume"
case globalSpeedEnabled = "userSettingsGlobalSpeed"
case autoplayEnabled = "userSettingsAutoplay"
case autolockDisabled = "userSettingsDisableAutolock"
case autolockDisabledOnlyWhenPowered = "userSettingsAutolockOnlyWhenPowered"
case rewindInterval = "userSettingsRewindInterval"
case forwardInterval = "userSettingsForwardInterval"
}
public enum SmartRewind: TimeInterval {
case threshold = 599.0 // 599 = 10 mins
case maxTime = 30.0
}
public enum Volume: Float {
case normal = 1.0
case boosted = 2.0
}
public static let UserActivityPlayback = Bundle.main.bundleIdentifier! + ".activity.playback"
public static let ApplicationGroupIdentifier = "group.\(Bundle.main.configurationString(for: .bundleIdentifier)).files"
public enum DefaultArtworkColors {
case primary
case secondary
case accent
case separator
case systemBackground
case secondarySystemBackground
case tertiarySystemBackground
case systemGroupedBackground
case systemFill
case secondarySystemFill
case tertiarySystemFill
case quaternarySystemFill
var lightColor: String {
switch self {
case .primary:
return "#37454E"
case .secondary:
return "#3488D1"
case .accent:
return "#7685B3"
case .separator:
return "#DCDCDC"
case .systemBackground:
return "#FAFAFA"
case .secondarySystemBackground:
return "#FCFBFC"
case .tertiarySystemBackground:
return "#E8E7E9"
case .systemGroupedBackground:
return "#EFEEF0"
case .systemFill:
return "#87A0BA"
case .secondarySystemFill:
return "#ACAAB1"
case .tertiarySystemFill:
return "#7685B3"
case .quaternarySystemFill:
return "#7685B3"
}
}
var darkColor: String {
switch self {
case .primary:
return "#EEEEEE"
case .secondary:
return "#3488D1"
case .accent:
return "#7685B3"
case .separator:
return "#434448"
case .systemBackground:
return "#050505"
case .secondarySystemBackground:
return "#111113"
case .tertiarySystemBackground:
return "#333538"
case .systemGroupedBackground:
return "#2C2D30"
case .systemFill:
return "#647E98"
case .secondarySystemFill:
return "#707176"
case .tertiarySystemFill:
return "#7685B3"
case .quaternarySystemFill:
return "#7685B3"
}
}
}
}
| gpl-3.0 | 8c75aa956e055468da1aba676a932ed1 | 33.2 | 123 | 0.59771 | 5.392904 | false | false | false | false |
jilouc/kuromoji-swift | kuromoji-swift/buffer/FeatureInfoMap.swift | 1 | 1169 | //
// FeatureInfoMap.swift
// kuromoji-swift
//
// Created by Jean-Luc Dagon on 14/11/2016.
// Copyright © 2016 Cocoapps. All rights reserved.
//
import Foundation
public struct FeatureInfoMap : CustomStringConvertible {
var featureMap = [String: Int]()
private var maxValue: Int = 0
mutating public func mapFeatures(_ features: [String]) -> [Int] {
var posFeatureIds = [Int]()
for feature in features {
if let posFeatureId = featureMap[feature] {
posFeatureIds.append(posFeatureId)
} else {
featureMap[feature] = maxValue
posFeatureIds.append(maxValue)
maxValue += 1
}
}
return posFeatureIds
}
public func invert() -> [Int: String] {
var features = [Int: String]()
for (key, value) in featureMap {
features[value] = key
}
return features
}
public func getEntryCount() -> Int {
return maxValue
}
public var description: String {
return "FeatureInfoMap{featureMap=\(featureMap), maxValue=\(maxValue)}"
}
}
| apache-2.0 | bae6d20628b0e45e74706fb6f586f100 | 24.955556 | 79 | 0.568493 | 4.492308 | false | false | false | false |
aestesis/Aether | Sources/Aether/Foundation/Paint.swift | 1 | 17253 | //
// Paint.swift
// Aether
//
// Created by renan jegouzo on 01/04/2016.
// Copyright © 2016 aestesis. 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 Foundation
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Interpolator {
var values=[Double:Double]()
public init() {
}
public init(_ values:[Double:Double]) {
self.values=values
}
public mutating func add(_ position:Double,_ v:Double) {
values[position]=v
}
public func value(_ position:Double) -> Double {
let keys = values.keys.sorted()
var i=0
while keys[i+1]<position {
i += 1
}
let p0 = keys[i]
let v0 = values[p0]!
let p1 = keys[i+1]
let v1 = values[p1]!
let c = (position-p0)/(p1-p0)
return v0 + (v1-v0) * c
}
public func values(from min:Double,to max:Double,count:Int) -> [Double] {
let keys = values.keys.sorted()
func val(_ position:Double) -> Double {
var i=0
while keys[i+1]<position {
i += 1
}
let p0 = keys[i]
let v0 = values[p0]!
let p1 = keys[i+1]
let v1 = values[p1]!
let c = (position-p0)/(p1-p0)
return v0 + (v1-v0) * c
}
var data = [Double](repeating:0,count:count)
for i in 0..<count {
let p = (Double(i)/Double(count-1))*(max-min)+min
data[i] = val(p)
}
return data
}
}
public struct ColorGradient {
var colors=[Double:Color]()
public private(set) var useAlpha=false
public init() {
}
public init(_ colors:[Double:Color]) {
self.colors=colors
}
public mutating func add(_ position:Double,_ c:Color) {
colors[position]=c
if c.a<1 {
useAlpha=true
}
}
public func value(_ position:Double) -> Color {
let keys = colors.keys.sorted()
var i=0
while keys[i+1]<position {
i += 1
}
let p0 = keys[i]
let c0 = colors[p0]!
let p1 = keys[i+1]
let c1 = colors[p1]!
return c0.lerp(to:c1,coef:(position-p0)/(p1-p0))
}
public func values(from min:Double,to max:Double,count:Int) -> [Color] {
let keys = colors.keys.sorted()
func val(_ position:Double) -> Color {
var i=0
while keys[i+1]<position {
i += 1
}
let p0 = keys[i]
let c0 = colors[p0]!
let p1 = keys[i+1]
let c1 = colors[p1]!
return c0.lerp(to:c1,coef:(position-p0)/(p1-p0))
}
var data = [Color](repeating:.black,count:count)
for i in 0..<count {
let p = (Double(i)/Double(count-1))*(max-min)+min
data[i] = val(p)
}
return data
}
public func createBitmap(parent:NodeUI,width:Double) -> Bitmap {
let dc = self.values(from:0,to:1,count:Int(width))
let b=Bitmap(parent:parent,size:Size(width,1))
var v = [UInt32](repeating:0,count:Int(width))
for x in 0..<v.count {
v[x] = dc[x].bgra
}
b.set(pixels:v)
return b
}
public func process(source:Bitmap, destination:Bitmap, blend:BlendMode = .opaque,color:Color = .white, _ fn:@escaping (RenderPass.Result)->()) {
let b = destination
let g = Graphics(image:b)
g.program("program.gradient",blend:blend)
g.uniforms(g.matrix)
g.textureVertices(4) { vert in
let strip=b.bounds.strip
var uv = Rect(x:0,y:0,w:1,h:1).strip
for i in 0...3 {
vert[i]=TextureVertice(position:strip[i].infloat3,uv:uv[i].infloat2,color:color.infloat4)
}
}
g.sampler("sampler.clamp")
g.render.use(texture:source)
let bg = self.createBitmap(parent: destination, width: 16)
g.render.use(texture:bg,atIndex:1)
g.render.draw(trianglestrip:4)
g.done { ok in
bg.detach()
fn(ok)
}
}
public static var blackWhite : ColorGradient {
var cg = ColorGradient()
cg.add(0, .black)
cg.add(1, .white)
return cg
}
public static var rainbow : ColorGradient {
var cg = ColorGradient()
var h = 0.0
var i = 0.0
let dh = 1.0/16
let di = 1.0/16
for _ in 1...16 {
cg.add(i, Color(h: h, s: 1, b: 1))
i += di
h += dh
}
cg.add(i, Color(h: h, s: 1, b: 1))
return cg
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class Paint : NodeUI {
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var _renderer:Renderer?=nil
var renderer:Renderer? {
get { return _renderer }
set(r) {
if let r = _renderer {
r.detach()
}
_renderer = r
}
}
public private(set) var mode:PaintMode
public var blend:BlendMode
public var strokeWidth:Double=1.0
public private(set) var useAlpha:Bool=false
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var computedBlend:BlendMode {
if blend == .opaque && useAlpha {
return .alpha
}
return blend
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(parent:NodeUI,mode:PaintMode=PaintMode.fill,blend:BlendMode=BlendMode.opaque,color:Color?=nil) {
self.mode=mode
self.blend=blend
super.init(parent:parent)
if let c=color {
self.color = c
}
}
public init(parent:NodeUI,mode:PaintMode=PaintMode.fill,blend:BlendMode=BlendMode.opaque,linear:ColorGradient) {
self.mode=mode
self.blend=blend
super.init(parent:parent)
self.linearGradient(p0: Point.zero, p1: Point(1,1), cramp: linear)
}
public init(parent:NodeUI,mode:PaintMode=PaintMode.fill,blend:BlendMode=BlendMode.opaque,radial:ColorGradient) {
self.mode=mode
self.blend=blend
super.init(parent:parent)
self.radialGradient(colors:radial)
}
public init(parent:NodeUI,mode:PaintMode=PaintMode.fill,blend:BlendMode=BlendMode.opaque,color:Color=Color.white,bitmap:Bitmap) {
self.mode=mode
self.blend=blend
super.init(parent:parent)
self.bitmap(image:bitmap,color:color)
}
public init(parent:NodeUI,mode:PaintMode=PaintMode.fill,blend:BlendMode=BlendMode.opaque,pattern:Bitmap,scale:Size=Size(1,1),offset:Point=Point.zero) {
self.mode=mode
self.blend=blend
super.init(parent:parent)
self.pattern(image:pattern,scale:scale,offset:offset)
}
public init(parent:NodeUI,mode:PaintMode=PaintMode.stroke,blend:BlendMode=BlendMode.opaque,color:Color=Color.white,line:Bitmap,strokeWidth:Double=1) {
self.strokeWidth = strokeWidth
self.mode=mode
self.blend=blend
super.init(parent:parent)
self.line(image:line,color:color)
}
override public func detach() {
if let renderer=renderer {
renderer.detach()
self.renderer=nil
}
super.detach()
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public var color:Color {
get {
if let p=renderer as? RenderColor {
return p.color
} else if let p=renderer as? RenderTexture {
return p.color
}
return Color.white
}
set(c) {
if let r = renderer as? RenderColor {
r.color = c
} else if let r = renderer as? RenderTexture {
r.color = c
} else {
renderer=RenderColor(color:c)
}
useAlpha=(c.a != 1)
}
}
public func linearGradient(p0:Point,p1:Point,cramp:ColorGradient) {
renderer = RenderLinearGradient(p0:p0,p1:p1,colors:cramp)
useAlpha = cramp.useAlpha
}
public func radialGradient(center:Point=Point(0.5,0.5),focal:Point=Point(0.5,0.5),radius:Double=0.5,colors:ColorGradient) {
renderer = RenderRadialGradient(center:center,focal:focal,radius:radius,colors:colors)
useAlpha = colors.useAlpha
}
public func pattern(image:Bitmap,scale:Size=Size(1,1),offset:Point=Point.zero) {
renderer=RenderPattern(image:image,scale:scale,offset:offset)
}
public func bitmap(image:Bitmap,color:Color=Color.white) {
renderer=RenderBitmap(image:image,color:color)
}
public func line(image:Bitmap,color:Color=Color.white) {
renderer=RenderLine(image:image,color:color)
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public enum PaintMode {
case fill
case stroke
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Renderer {
enum UV {
case none
case boundingBox
case trace
}
var uv:UV {
return .none
}
var sampler:String {
return "sampler.clamp"
}
func offset(_ boudingBox:Rect) -> Point {
return Point.zero
}
func scale(_ boundingBox:Rect) -> Size {
return Size(1,1)
}
func detach() {
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class RenderColor : Renderer {
var color:Color
init(color:Color=Color.white) {
self.color=color
}
}
class RenderTexture : Renderer {
var color:Color
override var uv:UV {
return .boundingBox
}
func texture(parent:NodeUI) -> Texture2D? {
return nil
}
init(color:Color=Color.white) {
self.color=color
}
}
class RenderLinearGradient : RenderTexture {
var colors:ColorGradient
var p0:Point
var p1:Point
init(p0:Point=Point.zero,p1:Point=Point(1,1),colors:ColorGradient) {
self.colors=colors
self.p0=p0
self.p1=p1
super.init()
}
override func texture(parent:NodeUI) -> Texture2D? {
return nil
}
}
class RenderRadialGradient : RenderTexture {
var colors:ColorGradient
var center:Point
var focal:Point
var radius:Double
var texture:Bitmap?
init(center:Point=Point(0.5,0.5),focal:Point=Point(0.5,0.5),radius:Double=0.5,colors:ColorGradient) {
self.center=center
self.focal=focal
self.radius=radius
self.colors=colors
super.init()
}
override func texture(parent:NodeUI) -> Texture2D? {
if let t=texture {
return t
}
let sz=SizeI(32,32)
let t = Bitmap(parent:parent,size:Size(sz))
var pix=[UInt32](repeating:0,count:sz.w*sz.h)
let ir = 0.5 / radius
var i = 0
let m = (Size(sz)-Size(1,1))*0.5
for y in 0..<Int(sz.h) {
let dy = (Double(y)-m.h)/m.h
for x in 0..<Int(sz.w) {
let dx = (Double(x)-m.w)/m.w
let d = max(0.0,min(1.0,sqrt(dx*dx+dy*dy)*ir))
pix[i] = colors.value(d).bgra
i += 1
}
}
t.set(pixels: pix)
texture=t
return t
}
}
class RenderPattern : RenderTexture {
override var sampler:String {
return "sampler.wrap"
}
var image:Bitmap
var scale:Size
var offset:Point
override func offset(_ boundingBox:Rect) -> Point {
return boundingBox.origin/(image.size*scale)
}
override func scale(_ boundingBox:Rect) -> Size {
return boundingBox.size/(scale*image.size)
}
init(image:Bitmap,scale:Size=Size(1,1),offset:Point=Point.zero) {
self.image=image
self.scale=scale
self.offset=offset
}
override func detach() {
image.detach()
super.detach()
}
override func texture(parent:NodeUI) -> Texture2D? {
return image
}
}
class RenderBitmap : RenderTexture {
var image:Bitmap
init(image:Bitmap,color:Color=Color.white) {
self.image=image
super.init(color:color)
}
override func detach() {
image.detach()
super.detach()
}
override func texture(parent:NodeUI) -> Texture2D? {
return image
}
}
class RenderLine : RenderTexture {
override var uv:UV {
return .trace
}
override func scale(_ boundingBox:Rect) -> Size {
return Size(1,1)/image.size
}
var image:Bitmap
init(image:Bitmap,color:Color=Color.white) {
self.image=image
super.init(color:color)
}
override func texture(parent:NodeUI) -> Texture2D? {
return image
}
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | 9b599725da905afe5d444413f462d607 | 37.252772 | 155 | 0.420763 | 4.681682 | false | false | false | false |
stripe/stripe-ios | StripeCardScan/StripeCardScan/Source/CardVerify/CardVerifyStateMachine.swift | 1 | 12953 | //
// CardVerifyStateMachine.swift
// CardVerify
//
// Created by Adam Wushensky on 8/7/20.
//
import Foundation
typealias StrictModeFramesCount = CardImageVerificationSheet.StrictModeFrameCount
protocol CardVerifyStateMachineProtocol {
var requiredLastFour: String? { get }
var requiredBin: String? { get }
var strictModeFramesCount: StrictModeFramesCount { get }
var visibleMatchingCardCount: Int { get set }
func resetCountAndReturnToInitialState() -> MainLoopState
func determineFinishedState() -> MainLoopState
}
class CardVerifyStateMachine: OcrMainLoopStateMachine, CardVerifyStateMachineProtocol {
var requiredLastFour: String?
var requiredBin: String?
var strictModeFramesCount: StrictModeFramesCount
var visibleMatchingCardCount: Int = 0
let ocrAndCardStateDurationSeconds = 1.5
let ocrOnlyStateDurationSeconds = 1.5
let ocrDelayForCardStateDurationSeconds = 2.0
let ocrIncorrectDurationSeconds = 2.0
let ocrForceFlashDurationSeconds = 1.5
init(
requiredLastFour: String? = nil,
requiredBin: String? = nil,
strictModeFramesCount: CardImageVerificationSheet.StrictModeFrameCount
) {
self.requiredLastFour = requiredLastFour
self.requiredBin = requiredBin
self.strictModeFramesCount = strictModeFramesCount
}
convenience init(
requiredLastFour: String? = nil,
requiredBin: String? = nil
) {
self.init(
requiredLastFour: requiredLastFour,
requiredBin: requiredBin,
strictModeFramesCount: .none
)
}
func resetCountAndReturnToInitialState() -> MainLoopState {
visibleMatchingCardCount = 0
return .initial
}
func determineFinishedState() -> MainLoopState {
if Bouncer.useFlashFlow {
return .ocrForceFlash
}
/// The ocr and card state timer has elapsed. If visible card count hasn't been met within the time limit, then reset the timer and try again
return visibleMatchingCardCount >= strictModeFramesCount.totalFrameCount
? .finished : resetCountAndReturnToInitialState()
}
override func transition(prediction: CreditCardOcrPrediction) -> MainLoopState? {
let frameHasOcr = prediction.number != nil
let frameOcrMatchesRequiredLastFour =
requiredLastFour == nil
|| String(prediction.number?.suffix(4) ?? "") == requiredLastFour
let frameOcrMatchesRequiredBin =
requiredBin == nil || String(prediction.number?.prefix(6) ?? "") == requiredBin
let frameOcrMatchesRequired = frameOcrMatchesRequiredBin && frameOcrMatchesRequiredLastFour
let frameHasCard = prediction.centeredCardState?.hasCard() ?? false
let secondsInState = -startTimeForCurrentState.timeIntervalSinceNow
if frameHasCard && frameOcrMatchesRequired {
visibleMatchingCardCount += 1
}
switch (self.state, secondsInState, frameHasOcr, frameHasCard, frameOcrMatchesRequired) {
// MARK: Initial State
case (.initial, _, true, true, true):
// successful OCR and card
return .ocrAndCard
case (.initial, _, true, _, false):
// saw an incorrect card
return .ocrIncorrect
case (.initial, _, _, true, _):
// got a frame with a card
return .cardOnly
case (.initial, _, true, _, true):
// successful OCR and the card matches required
return .ocrOnly
// MARK: Card Only State
case (.cardOnly, _, true, _, false):
// if we're cardOnly and we get a frame with OCR and it does not match the required card
return .ocrIncorrect
case (.cardOnly, _, true, _, true):
// if we're cardonly and we get a frame with OCR and it matches the required card
return .ocrAndCard
// MARK: OCR Only State
case (.ocrOnly, _, _, true, _):
// if we're ocrOnly and we get a card
return .ocrAndCard
case (.ocrOnly, self.ocrOnlyStateDurationSeconds..., _, _, _):
// ocrOnly times out without getting a card
return .ocrDelayForCard
// MARK: OCR and Card State
case (.ocrAndCard, self.ocrAndCardStateDurationSeconds..., _, _, _):
return determineFinishedState()
// MARK: OCR Incorrect State
case (.ocrIncorrect, _, true, false, true):
// if we're ocrIncorrect and we get a valid pan
return .ocrOnly
case (.ocrIncorrect, _, true, true, true):
// if we're ocrIncorrect and we get a valid pan and card
return .ocrAndCard
case (.ocrIncorrect, _, true, _, false):
// if we're ocrIncorrect and we get another bad pan, restart the timer
return .ocrIncorrect
case (.ocrIncorrect, self.ocrIncorrectDurationSeconds..., _, _, _):
// if we're ocrIncorrect and the timer has elapsed
return resetCountAndReturnToInitialState()
// MARK: OCR Delay for Card State
case (.ocrDelayForCard, _, _, true, _):
// if we're ocrDelayForCard and we get a card
return .ocrAndCard
case (.ocrDelayForCard, self.ocrDelayForCardStateDurationSeconds..., _, _, _):
// if we're ocrDelayForCard and we time out
return determineFinishedState()
// MARK: OCR Force Flash State
case (.ocrForceFlash, self.ocrForceFlashDurationSeconds..., _, _, _):
return .finished
default:
return nil
}
}
override func reset() -> MainLoopStateMachine {
return CardVerifyStateMachine(
requiredLastFour: requiredLastFour,
requiredBin: requiredBin,
strictModeFramesCount: strictModeFramesCount
)
}
}
@available(iOS 13.0, *)
class CardVerifyAccurateStateMachine: OcrMainLoopStateMachine, CardVerifyStateMachineProtocol {
var requiredLastFour: String?
var requiredBin: String?
var strictModeFramesCount: StrictModeFramesCount
var visibleMatchingCardCount: Int = 0
var hasNamePrediction = false
var hasExpiryPrediction = false
let ocrAndCardStateDurationSeconds = 1.5
let ocrOnlyStateDurationSeconds = 1.5
let ocrDelayForCardStateDurationSeconds = 2.0
let ocrIncorrectDurationSeconds = 2.0
let ocrForceFlashDurationSeconds = 1.5
var nameExpiryDurationSeconds = 4.0
init(
requiredLastFour: String? = nil,
requiredBin: String? = nil,
maxNameExpiryDurationSeconds: Double,
strictModeFramesCount: StrictModeFramesCount
) {
self.requiredLastFour = requiredLastFour
self.requiredBin = requiredBin
self.nameExpiryDurationSeconds = maxNameExpiryDurationSeconds
self.strictModeFramesCount = strictModeFramesCount
}
convenience init(
requiredLastFour: String? = nil,
requiredBin: String? = nil,
maxNameExpiryDurationSeconds: Double
) {
self.init(
requiredLastFour: requiredLastFour,
requiredBin: requiredBin,
maxNameExpiryDurationSeconds: maxNameExpiryDurationSeconds,
strictModeFramesCount: .none
)
}
func resetCountAndReturnToInitialState() -> MainLoopState {
visibleMatchingCardCount = 0
return .initial
}
func determineFinishedState() -> MainLoopState {
if Bouncer.useFlashFlow {
return .ocrForceFlash
}
/// The ocr and card state timer has elapsed. If visible card count hasn't been met within the time limit, then reset the timer and try again
return visibleMatchingCardCount >= strictModeFramesCount.totalFrameCount
? .finished : resetCountAndReturnToInitialState()
}
override func transition(prediction: CreditCardOcrPrediction) -> MainLoopState? {
hasExpiryPrediction = hasExpiryPrediction || prediction.expiryForDisplay != nil
hasNamePrediction = hasNamePrediction || prediction.name != nil
let frameHasOcr = prediction.number != nil
let frameOcrMatchesRequiredLastFour =
requiredLastFour == nil
|| String(prediction.number?.suffix(4) ?? "") == requiredLastFour
let frameOcrMatchesRequiredBin =
requiredBin == nil || String(prediction.number?.prefix(6) ?? "") == requiredBin
let frameOcrMatchesRequired = frameOcrMatchesRequiredBin && frameOcrMatchesRequiredLastFour
let frameHasCard = prediction.centeredCardState?.hasCard() ?? false
let hasNameAndExpiry = hasNamePrediction && hasExpiryPrediction
let secondsInState = -startTimeForCurrentState.timeIntervalSinceNow
if frameHasCard && frameOcrMatchesRequired {
visibleMatchingCardCount += 1
}
switch (
self.state, secondsInState, frameHasOcr, frameHasCard, frameOcrMatchesRequired,
hasNameAndExpiry
) {
// MARK: Initial State
case (.initial, _, true, true, true, _):
// successful OCR and card
return .ocrAndCard
case (.initial, _, true, _, false, _):
// saw an incorrect card
return .ocrIncorrect
case (.initial, _, _, true, _, _):
// got a frame with a card
return .cardOnly
case (.initial, _, true, _, true, _):
// successful OCR and the card matches required
return .ocrOnly
// MARK: Card Only State
case (.cardOnly, _, true, _, false, _):
// if we're cardOnly and we get a frame with OCR and it does not match the required card
return .ocrIncorrect
case (.cardOnly, _, true, _, true, _):
// if we're cardonly and we get a frame with OCR and it matches the required card
return .ocrAndCard
// MARK: Ocr Only State
case (.ocrOnly, _, _, true, _, _):
// if we're ocrOnly and we get a card
return .ocrAndCard
case (.ocrOnly, self.ocrOnlyStateDurationSeconds..., _, _, _, _):
// ocrOnly times out without getting a card
return .ocrDelayForCard
// MARK: Ocr Incorrect State
case (.ocrIncorrect, _, true, false, true, _):
// if we're ocrIncorrect and we get a valid pan
return .ocrOnly
case (.ocrIncorrect, _, true, true, true, _):
// if we're ocrIncorrect and we get a valid pan and card
return .ocrAndCard
case (.ocrIncorrect, _, true, _, false, _):
// if we're ocrIncorrect and we get another bad pan, restart the timer
return .ocrIncorrect
case (.ocrIncorrect, self.ocrIncorrectDurationSeconds..., _, _, _, _):
// if we're ocrIncorrect and the timer has elapsed
return .initial
// MARK: Ocr and Card State
case (.ocrAndCard, self.ocrAndCardStateDurationSeconds..., _, _, _, false):
// if we're in ocr&card and dont have name&expiry
return .nameAndExpiry
case (.ocrAndCard, self.ocrAndCardStateDurationSeconds..., _, _, _, true):
// if we're in ocr&card and we have name&expiry
return determineFinishedState()
// MARK: Ocr Delay For Card State
case (.ocrDelayForCard, self.ocrDelayForCardStateDurationSeconds..., _, _, _, false):
// if we're ocrDelayForCard, we time out, and we dont have name&expiry
return .nameAndExpiry
case (.ocrDelayForCard, self.ocrDelayForCardStateDurationSeconds..., _, _, _, true):
// if we're ocrDelayForCard, we time out but we have name&expiry
return determineFinishedState()
case (.ocrDelayForCard, _, _, true, _, _):
// if we're ocrDelayForCard and we get a card
return .ocrAndCard
// MARK: Name And Expiry State
case (.nameAndExpiry, self.nameExpiryDurationSeconds..., _, _, _, _):
// if we're checking for name&expiry and we time out
return Bouncer.useFlashFlow ? .ocrForceFlash : .finished
case (.nameAndExpiry, _, _, _, _, true):
// if we're checking for name&expiry and we find name&expiry
return determineFinishedState()
// MARK: Ocr Force Flash State
case (.ocrForceFlash, self.ocrForceFlashDurationSeconds..., _, _, _, _):
return .finished
default:
return nil
}
}
override func reset() -> MainLoopStateMachine {
return CardVerifyAccurateStateMachine(
requiredLastFour: requiredLastFour,
requiredBin: requiredBin,
maxNameExpiryDurationSeconds: nameExpiryDurationSeconds,
strictModeFramesCount: strictModeFramesCount
)
}
}
| mit | e3c45178073d00ed7f8995d4caf4f488 | 38.733129 | 149 | 0.631282 | 4.804525 | false | false | false | false |
dobnezmi/EmotionNote | EmotionNote/Charts/Renderers/Scatter/CircleShapeRenderer.swift | 1 | 2147 | //
// CircleShapeRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
open class CircleShapeRenderer : NSObject, IShapeRenderer
{
open func renderShape(
context: CGContext,
dataSet: IScatterChartDataSet,
viewPortHandler: ViewPortHandler,
point: CGPoint,
color: NSUIColor)
{
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius
let shapeHoleSize = shapeHoleSizeHalf * 2.0
let shapeHoleColor = dataSet.scatterShapeHoleColor
let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0
let shapeStrokeSizeHalf = shapeStrokeSize / 2.0
if shapeHoleSize > 0.0
{
context.setStrokeColor(color.cgColor)
context.setLineWidth(shapeStrokeSize)
var rect = CGRect()
rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf
rect.size.width = shapeHoleSize + shapeStrokeSize
rect.size.height = shapeHoleSize + shapeStrokeSize
context.strokeEllipse(in: rect)
if let shapeHoleColor = shapeHoleColor
{
context.setFillColor(shapeHoleColor.cgColor)
rect.origin.x = point.x - shapeHoleSizeHalf
rect.origin.y = point.y - shapeHoleSizeHalf
rect.size.width = shapeHoleSize
rect.size.height = shapeHoleSize
context.fillEllipse(in: rect)
}
}
else
{
context.setFillColor(color.cgColor)
var rect = CGRect()
rect.origin.x = point.x - shapeHalf
rect.origin.y = point.y - shapeHalf
rect.size.width = shapeSize
rect.size.height = shapeSize
context.fillEllipse(in: rect)
}
}
}
| apache-2.0 | d98f0ca23c4f947dff9c30c140821ca0 | 33.629032 | 77 | 0.607359 | 5.223844 | false | false | false | false |
tbaranes/SwiftyUtils | Tests/Extensions/AppKit/NSView/NSViewExtensionsTest.swift | 1 | 693 | //
// NSViewExtensionsTest.swift
// SwiftyUtils
//
// Created by Mulang Su on 12/01/2017.
// Copyright © 2017 Tom Baranes. All rights reserved.
//
#if os(macOS)
import XCTest
import AppKit
final class NSViewExtensionTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
}
extension NSViewExtensionTests {
func testXYWHChanges() {
let view = NSView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.x = 10
view.y = 20
view.width = 30
view.height = 40
XCTAssertEqual(view.frame, CGRect(x: 10, y: 20, width: 30, height: 40))
}
}
#endif
| mit | 863f1e141b6095b5a68702ea42cc60fe | 17.702703 | 79 | 0.608382 | 3.56701 | false | true | false | false |
austinzheng/swift-compiler-crashes | crashes-duplicates/18363-no-stacktrace.swift | 11 | 2351 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
{
{
struct B<I : Any))?
case c] = {
typealias e == [Void{
case c: e : NSObject {
var d : b { func b
case c
{
case c
struct c
struct d
class d<T where h: B)?
protocol A {
var d : Any))
struct d<T where g: B)?
func b<T {
init( [ ]
case c] = b
var d { func c: T where T> {
var d {
{
}
class d
{
class B : Any)
class b
{
{
func c] = [Void{
{
static let end = a
}
}
case c
var d : d<I : C {
}
struct d<f = [Void{
case c
}
protocol a {
enum e : b { class b
struc
println
typealias b
struct S<d where g: T where g: Any, A<T where g: Any, d = compose<Q
func c
}
let i: d
S<T where H.e : c: e {
let start = [Void{
{
let i: NSObject {
func p
class a<T>
enum b { func b<T where g: T where h: NSObject {
}
S<T where g: Any, A.c,
d
func c: NSObject {
struct d
va d<I : B? {
struct S<T where g: A {
var d where g: A.b>: B<T where g< > U)?
struct d<T where H.h == [Void{
class
{
class
}
d
}
case c,
struct d<T where T>
class b<f = compose<T.h == 0
{
}
class
class n {
class
static let a {
println() { class B? {
struct d<d {
static let i: B
func f<T>: B? {
{
func c] = e, A<c
let i: A<h == a<T.e : d
struct S<T where B : A? {
struct B<I : d where g: NSManagedObject {
static let a {
var d {
(f(f: e == 0
d<T where T>
class
class n {
struct d<b
case c<T : b { p(T>
class A {
}
}
struct A? {
func e, g: d<T where h: B? {
func b
class
if true {
case c,
}
if true {
() as a
("
struct B?
let a {
S<T where T>
S<d { func c
typealias e : A.c,
{
class
va d<T where H.c
func b<T where h: Any, A.g : Any)
protocol P {
class
case c,
let h = r([Void{
func f: b class A {
class
class B<I : A : Any)"
case c
let a {
class d
}
[ ]
struct S<T.c,
func a
protocol A {
class B<S : d
import Foundation
{
{
enum e : U : NSManagedObject {
case c,
protocol A {
let start = [Void{
let end = [Void{
{
struct B? {
struct d
Void{
}
class
func e() as a
func e, g.b<f = [Void{
class n {
struct S<T where H : T where A.c] = {
var d : Array<f = b<T where T: A {
func f: A {
struct B)?
class b
{
var _ = {
struct B<T where g.h = compose<T where g: c
S<T : e : e where H.c
}
{
struct A : Any, A.c] = B<T where g: B? {
case c
case c,
class A {
{
func e([Void{
func c: d
}
class
struct B)
class
class B<T>
{
}
class
var f =
| mit | b8f5513fdd9577d6e1467619466dba59 | 11.777174 | 87 | 0.599745 | 2.311701 | false | false | false | false |
leo150/Pelican | Sources/Pelican/Pelican/Update/Update.swift | 1 | 3901 | //
// Pelican+Update.swift
// party
//
// Created by Takanu Kyriako on 29/06/2017.
//
//
import Foundation
import Vapor
/**
Encapsulates a single update received from a Telegram bot.
*/
public class Update {
// RAW DATA
/// The type of data being carried by the update.
public var type: UpdateType
/// The data package contained in the update as a UpdateModel type.
public var data: UpdateModel
/// The data package contained in the update as a Node, which you can either access through subscripting the type or directly.
public var node: Node
/// The time the update was received by Pelican.
public var time = Date()
// HEADER CONTENT
/// Defines the unique identifier for the content (not the ID of the entity that contains the content).
public var id: Int
/// The basic package of content provided in the update by the sending user, to be used by Route filters.
public var content: String
/// The user who triggered the update. This only has the potential to unwrap as nil if the message originated from a channel.
public var from: User?
/// The chat the update came from, if the update is a Message type. If it isn't, it'll return nil.
public var chat: Chat?
// LINKED SESSIONS
/** Defines any sessions that were linked to this update. This occurs when more than one SessionBuilder
captures the same update, and through the optional `collision` function type on a SessionBuilder, a Builder
wanted the relevant session to be linked in the update rather than executed.
*/
public var linkedSessions: [Session] = []
/// Contains basic information about the update depending on the
//public var header: [String:String] = [:]
init(withData data: UpdateModel, node: Node) {
self.data = data
self.node = node
// Need to ensure the type can be interpreted as other types (edited messages, channel posts)
if data is Message {
self.type = .message
let message = data as! Message
self.id = message.tgID
self.content = message.text ?? ""
self.chat = message.chat
if message.from != nil {
self.from = message.from!
}
}
else if data is CallbackQuery {
self.type = .callbackQuery
let query = data as! CallbackQuery
self.id = Int(query.id)!
self.from = query.from
self.chat = query.message?.chat
self.content = query.data ?? ""
}
else if data is InlineQuery {
self.type = .inlineQuery
let query = data as! InlineQuery
self.id = Int(query.id)!
self.content = query.query
self.from = query.from
}
else {
self.type = .chosenInlineResult
let result = data as! ChosenInlineResult
self.id = Int(result.resultID)!
self.content = result.query
self.from = result.from
}
}
/* Unable to find a clean way to enable subscripting while converting the requested type
into it's original type, then return it as an Any type. Maybe Swift 4 Codable will help.
*/
/**
/**
Attempts to subscript a node entry into a String result, for quick glancing into the contents of an update.
*/
subscript(_ list: String...) -> Any? {
let item = node[list]
let object = node[list] as Any
print(object)
return item
}
*/
/**
*/
public func matches(_ pattern: String, types: [String]) -> Bool {
if pattern == content {
//print("Match found C: .\n\(pattern) - \(content)")
return true
}
else {
//print("Match not found.\n\(pattern) - \(content)")
return false
}
// For a simple test, do direct text-matching only.
/*
let regex = try! NSRegularExpression.init(pattern: pattern)
let matches = regex.matches(in: content, range: NSRangeFromString(content))
if matches.count > 0 {
print("Match found C: .\n\(pattern) - \(content)")
return true
}
else {
print("Match not found.\n\(pattern) - \(content)")
return false
}
*/
}
}
| mit | 5b9ef87af81e1c975bc50a44d328b613 | 23.229814 | 127 | 0.669316 | 3.635601 | false | false | false | false |
tkester/swift-algorithm-club | Breadth-First Search/BreadthFirstSearch.playground/Pages/Simple example.xcplaygroundpage/Contents.swift | 1 | 1269 | // last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
func breadthFirstSearch(_ graph: Graph, source: Node) -> [String] {
var queue = Queue<Node>()
queue.enqueue(source)
var nodesExplored = [source.label]
source.visited = true
while let node = queue.dequeue() {
for edge in node.neighbors {
let neighborNode = edge.neighbor
if !neighborNode.visited {
queue.enqueue(neighborNode)
neighborNode.visited = true
nodesExplored.append(neighborNode.label)
}
}
}
return nodesExplored
}
let graph = Graph()
let nodeA = graph.addNode("a")
let nodeB = graph.addNode("b")
let nodeC = graph.addNode("c")
let nodeD = graph.addNode("d")
let nodeE = graph.addNode("e")
let nodeF = graph.addNode("f")
let nodeG = graph.addNode("g")
let nodeH = graph.addNode("h")
graph.addEdge(nodeA, neighbor: nodeB)
graph.addEdge(nodeA, neighbor: nodeC)
graph.addEdge(nodeB, neighbor: nodeD)
graph.addEdge(nodeB, neighbor: nodeE)
graph.addEdge(nodeC, neighbor: nodeF)
graph.addEdge(nodeC, neighbor: nodeG)
graph.addEdge(nodeE, neighbor: nodeH)
graph.addEdge(nodeE, neighbor: nodeF)
graph.addEdge(nodeF, neighbor: nodeG)
let nodesExplored = breadthFirstSearch(graph, source: nodeA)
print(nodesExplored)
| mit | 6256381d6a0b6142608a0ab990b08b05 | 24.897959 | 67 | 0.706068 | 3.44837 | false | false | false | false |
joalbright/Switchary | Example/Switchary/ViewController.swift | 1 | 2650 | //
// ViewController.swift
// Switchary
//
// Created by Jo Albright on 01/05/2016.
// Copyright (c) 2016 Jo Albright. All rights reserved.
//
import UIKit
import Switchary
extension UIView: SwitchInit { }
enum LifeStatus: Int { case Alive, Dead, Zombie }
enum AgeGroup: Int { case Baby, Toddler, Kid, Preteen, Teen, Adult }
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let life: LifeStatus = .Dead
// embedded ternary operators ... old way of writing it
// let _ = life == .Alive ? UIColor.greenColor()
// : life == .Dead ? UIColor.redColor()
// : life == .Zombie ? UIColor.grayColor()
// : UIColor.whiteColor()
// Switchary assignment inline
let _ = life ??? .Alive --> UIColor.greenColor()
||| .Dead --> UIColor.redColor()
||| .Zombie --> UIColor.grayColor()
*** UIColor.magentaColor()
// Switchary assignment closure
let _ = life ??? {
switch $0 {
case .Alive: return UIColor.greenColor()
case .Dead: return UIColor.redColor()
case .Zombie: return UIColor.grayColor()
}
}
// Switchary Range
let _ = 21 ??? (0...3) --> AgeGroup.Baby
||| (4...12) --> AgeGroup.Kid
||| (13...19) --> AgeGroup.Teen
*** AgeGroup.Adult
// closure pattern matching
let _ = 12 ??? {
switch $0 {
case 0..<10: return UIColor.clearColor()
case let x where x < 20: return UIColor.yellowColor()
case let x where x < 30: return UIColor.orangeColor()
case let x where x < 40: return UIColor.redColor()
default: return UIColor.whiteColor()
}
}
// Switchary initializer
let button = UIButton (life) {
switch $0 {
case .Alive : $1.setTitle("Eat Lunch", forState: .Normal)
case .Dead : $1.setTitle("Eat Dirt", forState: .Normal)
case .Zombie : $1.setTitle("Eat Brains", forState: .Normal)
}
}
view.addSubview(button)
}
}
| mit | 1ee3dc9d1a392e641ea6386cff088bbb | 26.894737 | 80 | 0.469057 | 5.038023 | false | false | false | false |
back2mach/OAuthSwift | OAuthSwiftTests/TestOAuthSwiftURLHandler.swift | 10 | 2967 | //
// TestOAuthSwiftURLHandler.swift
// OAuthSwift
//
// Created by phimage on 17/11/15.
// Copyright © 2015 Dongri Jin. All rights reserved.
//
import Foundation
import OAuthSwift
enum AccessTokenResponse {
case accessToken(String), code(String, state:String?), error(String,String), none
var responseType: String {
switch self {
case .accessToken:
return "token"
case .code:
return "code"
case .error:
return "code"
case .none:
return "code"
}
}
}
class TestOAuthSwiftURLHandler: NSObject, OAuthSwiftURLHandlerType {
let callbackURL: String
let authorizeURL: String
let version: OAuthSwiftCredential.Version
var accessTokenResponse: AccessTokenResponse?
var authorizeURLComponents: URLComponents? {
return URLComponents(url: URL(string: self.authorizeURL)!, resolvingAgainstBaseURL: false)
}
init(callbackURL: String, authorizeURL: String, version: OAuthSwiftCredential.Version) {
self.callbackURL = callbackURL
self.authorizeURL = authorizeURL
self.version = version
}
@objc func handle(_ url: URL) {
switch version {
case .oauth1:
handleV1(url)
case .oauth2:
handleV2(url)
}
}
func handleV1(_ url: URL) {
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
if let queryItems = urlComponents?.queryItems {
for queryItem in queryItems {
if let value = queryItem.value , queryItem.name == "oauth_token" {
let url = "\(self.callbackURL)?oauth_token=\(value)"
OAuthSwift.handle(url: URL(string: url)!)
}
}
}
urlComponents?.query = nil
if urlComponents != authorizeURLComponents {
print("bad authorizeURL \(url), must be \(authorizeURL)")
return
}
// else do nothing
}
func handleV2(_ url: URL) {
var url = "\(self.callbackURL)/"
if let response = accessTokenResponse {
switch response {
case .accessToken(let token):
url += "?access_token=\(token)"
case .code(let code, let state):
url += "?code='\(code)'"
if let state = state {
url += "&state=\(state)"
}
case .error(let error,let errorDescription):
let e = error.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let ed = errorDescription.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
url += "?error='\(e)'&errorDescription='\(ed)'"
case .none: break
// nothing
}
}
OAuthSwift.handle(url: URL(string: url)!)
}
}
| mit | d71f7a383282a4aa3cbabc6ea6b45b10 | 28.959596 | 104 | 0.561362 | 5.113793 | false | false | false | false |
ayong6/iOSNote | swift语言/swift语言/7. class类.playground/Contents.swift | 1 | 9038 | //: Playground - noun: a place where people can play
import UIKit
//类的介绍
/*
* Swift也是一门面向对象开发的语言
* 面向对象的基础是类,类产生了对象
* 在Swift中如何定义类呢?
*/
// 类的定义
/*
class 类名 : SuperClass {
// 定义属性和方法
}
*/
// 注意:
// 定义的类,可以没有父类.那么该类是rootClass
// 通常情况下,定义类时.继承自NSObject(非OC的NSObject)
// 类的属性介绍
// Swift中类的属性有多种
// 存储属性:存储实例的常量和变量
// 计算属性:通过某种方式计算出来的属性
// 类属性:与整个类自身相关的属性
// 1. 存储属性
// 1.1 存储属性就是存储在特定类和结构体的实例中的一个常量或者变量
// 1.2 可以在定义存储属性的时候指定默认值,也可以在构造过程中设置或修改存储属性的值。
struct Person {
let id: Int
var name: String
var height: Double = 171.0
}
let person = Person(id: 10, name: "xiaoming", height: 172)
person.id
person.name
person.height
// 1.3 如果实例化结构体赋值给一个常量,则无法修改该实例的任何属性,即使结构体里定义了变量存储属性。因为结构体是值类型,当值类型的实例被声明为常量的时候,它的所有属性也成了常量。
// person.height = 177 // 报错
// 2. 计算属性
// 计算属性不能直接存储值,而是提供一个get和一个可选的set,来间接获取和设置其他属性和变量的值
// 必须使用 var 关键字来定义计算属性
// 如果set没有定义新值的参数名,则可以使用默认名称 newValue
class Person1 {
private var personName = ""
var name: String {
get {
return personName
}
set {
personName = newValue
}
}
}
// 只读计算属性
// 只有get没有set的计算属性就是只读计算属性
// 只读属性的声明可以去掉 get 关键字
class Person2 {
var name_ = ""
var name: String {
return name_
}
}
// 3. 类属性
// 类属性是与类相关联的,而不是与类的实例相关联
// 所有的类和实例都共有一份类属性.因此在某一处修改之后,该类属性就会被修改
// 类属性的设置和修改,需要通过类来完成
// 下面是类属性的写法
// 类属性使用static来修饰
// courseCount是类属性,用来记录学生有多少门课程
class Student : NSObject {
// 类属性
static var corseCount : Int = 0
}
// 设置类属性的值
Student.corseCount = 3
// 取出类属性的值
print(Student.corseCount)
// ------------------------------------------------------
// 属性观察器
// 在oc中我们可以重写set方法来监听属性的改变
// 在swift中可以通过属性观察器来监听和响应属性值的变化
// 属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察期
// willSet 在新的值被设置之前调用
// willSet会将新的属性值作为常量参数传入,默认参数名 newValue,可自定义参数名
// didSet 在新的值设置之后调用
// didSet会将旧的属性值作为常量参数传入,默认参数名 oldValue, 可自定义参数名
// 1> willSet与didSet只有属性被赋值时才会调用,在初始化时,不会去调用这些监听方法
// 2> 新值和当前值相同也会调用属性观察器
// 3> 除了延迟存储属性之外的其他存储属性都可以添加属性观察器
// 4> 可以通过重写属性的方式为继承的属性添加或重写属性观察器
// 5> 如果一个属性在didSet观察器里为它赋值,这个值会替代之前设置的值
class Person3 {
var name = "xiaoming" {
willSet {
print("新值\(newValue)设置之前调用")
}
didSet {
print("被设置的旧值\(oldValue)")
name = "xiaoxiao" // 4> 中的例子,在didSet里赋值,会替代之前设置的值
}
}
}
let person3 = Person3()
person3.name = "zhangsan"
person3.name // 因为在didSet里赋值,所以替代了上一行的赋值,输出为“xiaoxiao”
// 1.4 延迟存储属性 lazy
// 1.4.1 延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性。在属性声明前使用 lazy 标识一个延迟存储属性
// 1.4.2 必须将延迟存储属性声明成变量。因为属性的初始值可能在实例构造完成之后才会得到,而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性
// 苹果的设计思想:希望所有的对象在使用时才真正加载到内存中
// 懒加载的格式: 定义变量时前面使用lazy来修饰变量,后面赋值一个闭包
// lazy var 变量: 类型 = { 创建变量代码 }()
// 注意: 1.必须声明成var, 2.闭包后面必须跟上()
// 懒加载的本质是,在第一次使用的时候执行闭包,将闭包的返回值赋值给属性
// lazy的作用是只会赋值一次
/*
lazy var array : [String] = {
() -> [String] in
return ["why", "lmj", "lnj"]
}()
// 如果闭包是用于懒加载,那么闭包内的in和in之前的代码都可以删除
lazy var array : [String] = {
return ["why", "lmj", "lnj"]
}()
*/
// 全局变量和局部变量
// 全局变量:在函数、方法、闭包或任何类型之外定义的变量
// 局部变量: 在函数、方法、闭包内部定义的变量
// 1> 全局的常量或者变量都是延迟计算的,跟延迟存储属性相似,不同的在于,全局的常量或者变量不需要标记 lazy修饰符
// 2> 局部范围的常量和变量不延迟计算
// ------------------------------------------------------
// 类构造函数的介绍
// 构造函数类似于OC中的初始化方法:init方法
// 默认情况下载创建一个类时,必然会调用一个构造函数
// 即便是没有编写任何构造函数,编译器也会提供一个默认的构造函数。
// 如果是继承自NSObject,可以对父类的构造函数进行重写
// 构造函数的基本使用
// 类的属性必须有值
// 如果不是在定义时初始化值,可以在构造函数中赋值
class Person4: NSObject {
var name : String
var age : Int
// 重写了NSObject(父类)的构造方法
override init() {
name = ""
age = 0
}
}
let person4 = Person4()
// 初始化时给属性赋值
// 很多时候,我们在创建一个对象时就会给属性赋值
// 可以自定义构造函数
// 注意:如果自定义了构造函数,会覆盖init()方法.即不在有默认的构造函数
class Person5: NSObject {
var name : String
var age : Int
// 自定义构造函数,会覆盖init()函数
init(name : String, age : Int) {
self.name = name
self.age = age
}
}
let person5 = Person5(name: "xiaohei", age: 18)
/*
* 如果构造方法前面没有convenience关键字,代表着是一个初始化构造方法(指定构造方法)
* 如果构造方法前面有convenience关键字,代表着是一个便利构造方法
*
* 指定构造方法和便利构造方法的区别:
* 1.指定构造方法中必须对所有的属性进行初始化
* 2.便利构造方法中不用对所以的属性进行初始化,因为便利构造方法依赖于指定构造方法
* 3.一般情况下如果想给系统的类提供一个快速创建的方法,就自定义一个便利构造方法
*/
// ---------------------------------------------------------
// 字典转模型(初始化时传入字典)
// 真实创建对象时,更多的是将字典转成模型
// 注意:
// 去字典中取出的是NSObject,任意类型.
// 可以通过as!转成需要的类型,再赋值(不可以直接赋值)
class Person6: NSObject {
var name : String
var age : Int
// 自定义构造函数,会覆盖init()函数
init(dict : [String : NSObject]) {
name = dict["name"] as! String
age = dict["age"] as! Int
}
}
let dict6 = ["name": "why", "age": 18]
let person6 = Person6(dict: dict6)
// 字典转模型(利用KVC转化)
// 利用KVC字典转模型会更加方便
// 注意:
// KVC并不能保证会给所有的属性赋值
// 因此属性需要有默认值
// 基本数据类型默认值设置为0
// 对象或者结构体类型定义为可选类型即可(可选类型没有赋值前为nil)
class Person7: NSObject {
// 结构体或者类的类型,必须是可选类型.因为不能保证一定会赋值
var name : String?
// 基本数据类型不能是可选类型,否则KVC无法转化
var age : Int = 0
// 自定义构造函数,会覆盖init()函数
init(dict : [String : NSObject]) {
// 必须先初始化对象
super.init()
// 调用对象的KVC方法字典转模型
setValuesForKeysWithDictionary(dict)
}
}
let dict7 = ["name" : "why", "age" : 18]
let person7 = Person7(dict: dict7)
| apache-2.0 | acdf7399e138d4f4c6e39e5aff3cd35a | 17.589928 | 92 | 0.642802 | 2.501452 | false | false | false | false |
wangzheng0822/algo | swift/06_linkedlist/SinglyLinkedList.swift | 1 | 3139 | //
// Created by Jiandan on 2018/10/12.
// Copyright © 2018 Jiandan. All rights reserved.
//
import Foundation
class Node<T> {
var value: T?
var next: Node?
init(){}
init(value: T) {
self.value = value
}
}
/// 单链表
/// 实现插入、删除、查找操作
class List<Element: Equatable> {
private var dummy = Node<Element>() // 哨兵结点,不存储数据
var size: Int {
var num = 0
var tmpNode = dummy.next
while tmpNode != nil {
num += 1
tmpNode = tmpNode!.next
}
return num
}
var isEmpty: Bool { return size > 0 }
/// find node with value
func node(with value: Element) -> Node<Element>? {
var node = dummy.next
while node != nil {
if node!.value == value {
return node
}
node = node!.next
}
return nil
}
// 约定:链表的 index 从 1 开始
func node(at index: Int) -> Node<Element>? {
var num = 1
var node = dummy.next
while node != nil {
if num == index {
return node
}
node = node!.next
num += 1
}
return nil
}
func insertToHead(value: Element) {
let newNode = Node(value: value)
return insertToHead(node: newNode)
}
func insertToHead(node: Node<Element>) {
node.next = dummy.next
dummy.next = node
}
func insert(after node: Node<Element>, newValue: Element) {
let newNode = Node(value: newValue)
return insert(after: node, newNode: newNode)
}
func insert(after node: Node<Element>, newNode: Node<Element>) {
newNode.next = node.next
node.next = newNode
}
func insert(before node: Node<Element>, newValue: Element) {
let newNode = Node(value: newValue)
return insert(before: node, newNode: newNode)
}
func insert(before node: Node<Element>, newNode: Node<Element>) {
var lastNode = dummy
var tmpNode = dummy.next
while tmpNode != nil {
if tmpNode === node {
newNode.next = tmpNode
lastNode.next = newNode
break
}
lastNode = tmpNode!
tmpNode = tmpNode!.next
}
}
func delete(node: Node<Element>) {
var lastNode = dummy
var tmpNode = dummy.next
while tmpNode != nil {
if tmpNode === node {
lastNode.next = tmpNode!.next
break
}
lastNode = tmpNode!
tmpNode = tmpNode!.next
}
}
/// 删除首个 value 符合要求的结点
func delete(value: Element) {
var lastNode = dummy
var tmpNode = dummy.next
while tmpNode != nil {
if tmpNode!.value == value {
lastNode.next = tmpNode!.next
break
}
lastNode = tmpNode!
tmpNode = tmpNode!.next
}
}
}
| apache-2.0 | cd3248d0a12ba4d5afb178bea0becb2c | 22.8125 | 69 | 0.495735 | 4.204138 | false | false | false | false |
lpniuniu/bookmark | bookmark/bookmark/Util/Date+Zero.swift | 1 | 1501 | //
// File.swift
// bookmark
//
// Created by FanFamily on 17/1/11.
// Copyright © 2017年 niuniu. All rights reserved.
//
import Foundation
extension Date
{
var zeroOfDate:Date{
let calendar:Calendar = Calendar.current
let date = self
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
var components:DateComponents = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = 8
components.minute = 0
components.second = 0
return calendar.date(from: components)!
}
var startMonthOfDate:Date{
let calendar:Calendar = Calendar.current
let date = self
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
var components:DateComponents = DateComponents()
components.year = year
components.month = month
components.hour = 8
return calendar.date(from: components)!
}
var endMonthOfDate:Date{
let calendar:Calendar = Calendar.current
let components = NSDateComponents()
components.month = 1
components.day = -1
let endOfMonth = calendar.date(byAdding: components as DateComponents, to: startMonthOfDate)!
return endOfMonth
}
}
| mit | 9c4cf46f33a40ea0f68714414f6c6544 | 27.807692 | 101 | 0.62016 | 4.609231 | false | false | false | false |
kaideyi/KDYSample | KYChat/KYChat/Helper/Extension/UIKit/UIColor+Extension.swift | 1 | 1587 | //
// UIColor+Extension.swift
// KDYWeChat
//
// Created by kaideyi on 16/9/10.
// Copyright © 2016年 kaideyi.com. All rights reserved.
//
import Foundation
typealias KYColor = UIColor.AppColorName
/// 统一管理颜色
extension UIColor {
enum AppColorName: String {
case ChatGreen = "#09BB07"
case ChatLightGreen = "#A8E980"
case BarTint = "#1A1A1A"
case TabbarSelectedText = "#68BB1E"
case TableBackground = "#f5f5f5"
case Separator = "#C8C8C8"
case NetworkFailed = "#FFC8C8"
case TextThree = "#333333"
case TextSix = "#666666"
case TextNine = "#999999"
case RecordBgNormal = "#F3F4F8"
case RecordBgSelect = "#C6C7CB"
var color: UIColor {
return UIColor(colorHex: self.rawValue)!
}
}
convenience init?(colorHex: String, alpha: CGFloat = 1.0) {
var formatted = colorHex.replacingOccurrences(of: "0x", with: "")
formatted = formatted.replacingOccurrences(of: "#", with: "")
if let hex = Int(formatted, radix: 16) {
let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
self.init(red: red, green: green, blue: blue, alpha: alpha)
} else {
return nil
}
}
}
| mit | 98ae033227be8cfeeed4d1e6c2b5e250 | 28.660377 | 73 | 0.523537 | 3.797101 | false | false | false | false |
IamAlchemist/DemoAnimations | Animations/LayerAnimationViewController.swift | 2 | 5411 | //
// LayerAnimationViewController.swift
// DemoAnimations
//
// https://www.objc.io/issues/12-animations/view-layer-synergy/
//
// Created by wizard on 5/27/16.
// Copyright © 2016 Alchemist. All rights reserved.
//
import UIKit
struct RD_popAnimationContext {
static var context : Bool = false
}
class LayerAnimationViewController: UIViewController {
@IBOutlet weak var orangeView: UIView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func showAnimation(sender: UIButton) {
UIView.RD_popAnimationWithDuration(2) {
self.orangeView.layer.setAffineTransform(CGAffineTransformMakeRotation(CGFloat(M_PI_4)))
// self.orangeView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
}
self.orangeView.layer.setAffineTransform(CGAffineTransformIdentity)
// self.orangeView.transform = CGAffineTransformIdentity
}
}
class RDInspectionLayer : CALayer {
override func addAnimation(anim: CAAnimation, forKey key: String?) {
print("adding animation \(anim.debugDescription), \(key)")
super.addAnimation(anim, forKey: key)
}
}
class RDInspectionView : UIView {
override class func layerClass() -> AnyClass {
return RDInspectionLayer.self
}
}
extension UIView {
public override class func initialize() {
struct Static {
static var token : dispatch_once_t = 0
}
if self !== UIView.self {
return
}
dispatch_once(&Static.token) {
let originalSelector = #selector(NSObject.actionForLayer(_:forKey:))
let swizzledSelector = #selector(RD_actionForLayer(_:forKey:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
public class func RD_popAnimationWithDuration(duration: NSTimeInterval, animations:()->()) {
RD_popAnimationContext.context = true
animations();
if let allStatus = RD_savedPopAnimationStates {
for status in allStatus {
guard let oldValue = status.oldValue,
let newValue = status.layer.valueForKey(status.keyPath)
else { continue }
let anim = CAKeyframeAnimation(keyPath: status.keyPath)
let easing : Float = 0.1
let easeIn = CAMediaTimingFunction(controlPoints: 1.0, 0.0, (1.0-easing), 1.0)
let easeOut = CAMediaTimingFunction(controlPoints: easing, 0.0, 0.0, 1.0)
anim.duration = duration
anim.keyTimes = [0, 0.1, 1]
anim.values = [oldValue, newValue, oldValue]
anim.timingFunctions = [easeIn, easeOut]
status.layer.addAnimation(anim, forKey: status.keyPath)
}
}
RD_savedPopAnimationStates?.removeAll()
RD_popAnimationContext.context = false
}
func RD_actionForLayer(layer: CALayer, forKey event:String) -> CAAction? {
if RD_popAnimationContext.context {
UIView.RD_savedPopAnimationStates?.append(RDSavedPopAnimationState.savedStateWithLayer(layer, keyPath: event))
return NSNull()
}
return RD_actionForLayer(layer, forKey: event)
}
}
extension UIView {
private struct AssociatedKeys {
static var DescriptiveName = "rd_savedPopAnimationStates"
}
class var RD_savedPopAnimationStates: [RDSavedPopAnimationState]? {
get {
if objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) == nil {
self.RD_savedPopAnimationStates = []
}
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? [RDSavedPopAnimationState]
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
(newValue as NSArray),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
}
class RDSavedPopAnimationState : NSObject {
var layer : CALayer
var keyPath : String
var oldValue : AnyObject?
static func savedStateWithLayer(layer: CALayer, keyPath: String) -> RDSavedPopAnimationState {
return RDSavedPopAnimationState(layer: layer, keyPath: keyPath, oldValue: layer.valueForKey(keyPath))
}
init(layer: CALayer, keyPath: String, oldValue : AnyObject?) {
self.layer = layer
self.keyPath = keyPath
self.oldValue = oldValue
super.init()
}
}
| mit | 6d67cb6eb9cdb3f088eca436a545df75 | 33.025157 | 152 | 0.608133 | 5.142586 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Playback/Time Pitch Stretching/AKTimePitch.swift | 1 | 2237 | //
// AKTimePitch.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// AudioKit version of Apple's TimePitch Audio Unit
///
open class AKTimePitch: AKNode, AKToggleable, AKInput {
fileprivate let timePitchAU = AVAudioUnitTimePitch()
/// Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
@objc open dynamic var rate: Double = 1.0 {
didSet {
rate = (0.031_25...32).clamp(rate)
timePitchAU.rate = Float(rate)
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return !timePitchAU.bypass
}
/// Pitch (Cents) ranges from -2400 to 2400 (Default: 0.0)
@objc open dynamic var pitch: Double = 0.0 {
didSet {
pitch = (-2_400...2_400).clamp(pitch)
timePitchAU.pitch = Float(pitch)
}
}
/// Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
@objc open dynamic var overlap: Double = 8.0 {
didSet {
overlap = (3...32).clamp(overlap)
timePitchAU.overlap = Float(overlap)
}
}
/// Initialize the time pitch node
///
/// - Parameters:
/// - input: Input node to process
/// - rate: Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
/// - pitch: Pitch (Cents) ranges from -2400 to 2400 (Default: 1.0)
/// - overlap: Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
///
@objc public init(
_ input: AKNode? = nil,
rate: Double = 1.0,
pitch: Double = 0.0,
overlap: Double = 8.0) {
self.rate = rate
self.pitch = pitch
self.overlap = overlap
super.init()
self.avAudioNode = timePitchAU
AudioKit.engine.attach(self.avAudioNode)
input?.connect(to: self)
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
timePitchAU.bypass = false
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
timePitchAU.bypass = true
}
}
| mit | 25db2d262fee541f89fa8e7b8fe6a6aa | 28.038961 | 78 | 0.58229 | 3.777027 | false | false | false | false |
tiger8888/Reflect | Reflect/Convert3.swift | 4 | 673 | //
// Convert3.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
/** 属性值为数组的转换 */
class Person3: Reflect {
var name: String!
var score: [Int]!
var bags: [Bag]!
class func convert(){
let person3 = Person3()
person3.name = "jack"
person3.score = [98,87,95]
let bag1 = Bag(color: "red", price: 12)
let bag2 = Bag(color: "blue", price: 15.8)
// person3.bags = [bag1,bag2]
let dict = person3.toDict()
println(dict)
}
}
| mit | feea52e0963ccfddd654ce86d25539c3 | 15.487179 | 50 | 0.496112 | 3.366492 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Utility/Migrations/ReaderTopicToReaderDefaultTopic37to38.swift | 4 | 1642 | import Foundation
class ReaderTopicToReaderDefaultTopic37to38: NSEntityMigrationPolicy {
override func createDestinationInstances(forSource sInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws {
// Only handle ReaderTopic entites that are defaults
let path = sInstance.value(forKey: "path") as! NSString
if path.range(of: "/list/").location != NSNotFound ||
path.range(of: "/tags/").location != NSNotFound ||
path.range(of: "/site/").location != NSNotFound {
return
}
// Create the destination ReaderTagTopic
let newTopic = NSEntityDescription.insertNewObject(forEntityName: ReaderDefaultTopic.classNameWithoutNamespaces(),
into: manager.destinationContext)
// Update the destination topic's properties
// Abstract
newTopic.setValue(sInstance.value(forKey: "isSubscribed"), forKey: "following")
newTopic.setValue(sInstance.value(forKey: "path"), forKey: "path")
newTopic.setValue(sInstance.value(forKey: "isMenuItem"), forKey: "showInMenu")
newTopic.setValue(sInstance.value(forKey: "title"), forKey: "title")
newTopic.setValue(ReaderDefaultTopic.TopicType, forKey: "type")
// Associate the source and destination instances
manager.associate(sourceInstance: sInstance, withDestinationInstance: newTopic, for: mapping)
}
override func createRelationships(forDestination dInstance: NSManagedObject, in mapping: NSEntityMapping, manager: NSMigrationManager) throws {
// preserve no posts
return
}
}
| gpl-2.0 | 89e8691fbcf4e002918835852e1e85d6 | 47.294118 | 149 | 0.702192 | 4.829412 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Post/LoadMoreCounter.swift | 2 | 1588 | import Foundation
/// Temporary counter to help investigate an old issue with load more analytics being spammed.
/// See https://github.com/wordpress-mobile/WordPress-iOS/issues/6819
class LoadMoreCounter {
private(set) var count: Int = 0
private var dryRun = false
/// Initializer
///
/// Parameters:
/// - startingCount - Optionally set the starting number for the counter. Default is 0.
/// - dryRun - pass true to avoid dispatching tracks events. Useful for testing. Default is false.
///
init(startingCount: Int = 0, dryRun: Bool = false) {
self.count = startingCount
self.dryRun = dryRun
}
/// Increments the counter.
/// Returns true if Analytics were bumped. False otherwise.
///
@discardableResult
func increment(properties: [String: AnyObject]) -> Bool {
count += 1
// For thresholds use the following:
// 1: Baseline. Confirms we're bumping the stat and lets us roughly calculate uniques.
// 100: Its unlikely this should happen in a normal session. Bears more investigation.
// 1000: We should never see this many in a normal session. Something is probably broken.
// 10000: Ditto
let benchmarks = [1, 100, 1000, 10000]
guard benchmarks.contains(count) else {
return false
}
if !dryRun {
var props = properties
props["count"] = count as AnyObject
WPAnalytics.track(.postListExcessiveLoadMoreDetected, withProperties: props)
}
return true
}
}
| gpl-2.0 | 4a95927b1d34e57318904ca1a68db51c | 32.787234 | 103 | 0.639798 | 4.616279 | false | false | false | false |
RebornSoul/YNImageAsync | YNImageAsync/Source/Core/CommonFunctions.swift | 2 | 1059 | //
// YNCommonFunctions.swift
// ImageAsyncTest
//
// Created by Yury Nechaev on 15.10.16.
// Copyright © 2016 Yury Nechaev. All rights reserved.
//
import Foundation
func yn_logError(_ items: Any...) {
yn_log(items, level: .errors)
}
func yn_logDebug(_ items: Any...) {
yn_log(items, level: .debug)
}
func yn_logInfo(_ items: Any...) {
yn_log(items, level: .info)
}
func yn_log(_ items: Any..., level: LogLevel) {
if YNImageAsync.sharedInstance.logLevel.contains(level) {
print(items)
}
}
public struct LogLevel : OptionSet {
public let rawValue: Int
public static let none = LogLevel(rawValue: 0)
public static let errors = LogLevel(rawValue: 1 << 0)
public static let debug = LogLevel(rawValue: (1 << 1) | errors.rawValue)
public static let info = LogLevel(rawValue: (1 << 2) | debug.rawValue)
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
func synced(lock: AnyObject, closure: () -> ()) {
objc_sync_enter(lock)
closure()
objc_sync_exit(lock)
}
| mit | 8de029219c45dca968a7a3728e903034 | 22 | 77 | 0.635161 | 3.380192 | false | false | false | false |
karstengresch/rw_studies | Apprentice/Checklists09/Checklists/ChecklistViewController.swift | 1 | 4521 | //
// ViewController.swift
// Checklists
//
// Created by Karsten Gresch on 25.11.15.
// Copyright © 2015 Closure One. All rights reserved.
//
import UIKit
class ChecklistViewController: UITableViewController, ItemDetailViewControllerDelegate {
var checklist: Checklist!
// MARK: Delegate protocol implementations
func itemDetailViewControllerDidCancel(_ controller: ItemDetailViewController) {
dismiss(animated: true, completion: nil)
}
func itemDetailViewController(_ controller: ItemDetailViewController, didFinishAddingItem checklistItem: ChecklistItem) {
let newRowIndex = checklist.checklistItems.count
checklist.checklistItems.append(checklistItem)
let indexPath = IndexPath(row: newRowIndex, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
dismiss(animated: true, completion: nil)
}
func itemDetailViewController(_ controller: ItemDetailViewController, didFinishEditingItem checklistItem: ChecklistItem) {
if let index = checklist.checklistItems.index(of: checklistItem) {
let indexPath = IndexPath(row: index, section: 0)
if let cell = tableView.cellForRow(at: indexPath) {
configureTextForCell(cell, withChecklistItem: checklistItem)
}
}
dismiss(animated: true, completion: nil)
}
// MARK: General view related methods
override func viewDidLoad() {
super.viewDidLoad()
title = checklist.name
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddCheckListItem" {
print("AddCheckListItem segue called")
let navigationController = segue.destination as? UINavigationController
let controller = navigationController?.topViewController as? ItemDetailViewController
controller?.delegate = self
}
if segue.identifier == "EditCheckListItem" {
let navigationController = segue.destination as? UINavigationController
let controller = navigationController?.topViewController as? ItemDetailViewController
controller?.delegate = self
if let indexPath = tableView.indexPath(for: (sender as? UITableViewCell)!) {
controller?.checklistItemToEdit = checklist.checklistItems[(indexPath as NSIndexPath).row]
}
}
}
// MARK: Content related methods
func configureCheckmarkForCell(_ cell: UITableViewCell, withChecklistItem checklistItem: ChecklistItem) {
let label = cell.viewWithTag(1001) as? UILabel
label?.textColor = view.tintColor
if checklistItem.checked {
label?.text = "√"
} else {
label?.text = ""
}
}
func configureTextForCell(_ cell: UITableViewCell, withChecklistItem checklistItem: ChecklistItem) {
let label = cell.viewWithTag(1000) as? UILabel
// label?.text = checklistItem.text
label?.text = "\(checklistItem.itemId) : \(checklistItem.text)"
}
// MARK: Data Source methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return checklist.checklistItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)
let checklistItem = checklist.checklistItems[(indexPath as NSIndexPath).row]
configureTextForCell(cell, withChecklistItem: checklistItem)
configureCheckmarkForCell(cell, withChecklistItem: checklistItem)
return cell
}
// MARK: Table delegate methods
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
let checklistItem = checklist.checklistItems[(indexPath as NSIndexPath).row]
checklistItem.toggleChecked()
configureCheckmarkForCell(cell, withChecklistItem: checklistItem)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
checklist.checklistItems.remove(at: (indexPath as NSIndexPath).row)
let indexPaths = [indexPath]
tableView.deleteRows(at: indexPaths, with: .automatic)
}
}
| unlicense | eb41b11490dec2b0141349cd7109c2d9 | 31.978102 | 134 | 0.721337 | 5.122449 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/KeyVerification/User/UserVerificationCoordinator.swift | 1 | 9178 | // File created from FlowTemplate
// $ createRootCoordinator.sh UserVerification UserVerification
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
@objcMembers
final class UserVerificationCoordinator: NSObject, UserVerificationCoordinatorType {
// MARK: - Properties
// MARK: Private
private let presenter: Presentable
private let navigationRouter: NavigationRouterType
private let session: MXSession
private let userId: String
private let userDisplayName: String?
private var deviceId: String?
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: UserVerificationCoordinatorDelegate?
// MARK: - Setup
init(presenter: Presentable, session: MXSession, userId: String, userDisplayName: String?) {
self.presenter = presenter
self.navigationRouter = NavigationRouter(navigationController: RiotNavigationController())
self.session = session
self.userId = userId
self.userDisplayName = userDisplayName
}
convenience init(presenter: Presentable, session: MXSession, userId: String, userDisplayName: String?, deviceId: String) {
self.init(presenter: presenter, session: session, userId: userId, userDisplayName: userDisplayName)
self.deviceId = deviceId
}
// MARK: - Public methods
func start() {
// Do not start again if existing coordinators are presented
guard self.childCoordinators.isEmpty else {
return
}
guard self.session.crypto.crossSigning.canCrossSign else {
self.presentBootstrapNotSetup()
return
}
let rootCoordinator: Coordinator & Presentable
if let deviceId = self.deviceId {
rootCoordinator = self.createSessionStatusCoordinator(with: deviceId, for: self.userId, userDisplayName: self.userDisplayName)
} else {
rootCoordinator = self.createUserVerificationSessionsStatusCoordinator()
}
rootCoordinator.start()
self.add(childCoordinator: rootCoordinator)
self.navigationRouter.setRootModule(rootCoordinator, hideNavigationBar: true, animated: false, popCompletion: {
self.remove(childCoordinator: rootCoordinator)
})
let rootViewController = self.navigationRouter.toPresentable()
rootViewController.modalPresentationStyle = .formSheet
self.presenter.toPresentable().present(rootViewController, animated: true, completion: nil)
}
func toPresentable() -> UIViewController {
return self.navigationRouter.toPresentable()
}
// MARK: - Private methods
private func createUserVerificationSessionsStatusCoordinator() -> UserVerificationSessionsStatusCoordinator {
let coordinator = UserVerificationSessionsStatusCoordinator(session: self.session, userId: self.userId)
coordinator.delegate = self
return coordinator
}
private func createSessionStatusCoordinator(with deviceId: String, for userId: String, userDisplayName: String?) -> UserVerificationSessionStatusCoordinator {
let coordinator = UserVerificationSessionStatusCoordinator(session: self.session, userId: userId, userDisplayName: userDisplayName, deviceId: deviceId)
coordinator.delegate = self
return coordinator
}
private func presentSessionStatus(with deviceId: String, for userId: String, userDisplayName: String?) {
let coordinator = self.createSessionStatusCoordinator(with: deviceId, for: userId, userDisplayName: userDisplayName)
coordinator.start()
self.navigationRouter.push(coordinator, animated: true) {
self.remove(childCoordinator: coordinator)
}
}
private func presentDeviceVerification(for deviceId: String) {
let keyVerificationCoordinator = KeyVerificationCoordinator(session: self.session, flow: .verifyDevice(userId: self.userId, deviceId: deviceId), navigationRouter: self.navigationRouter)
keyVerificationCoordinator.delegate = self
keyVerificationCoordinator.start()
self.add(childCoordinator: keyVerificationCoordinator)
self.navigationRouter.push(keyVerificationCoordinator, animated: true, popCompletion: {
self.remove(childCoordinator: keyVerificationCoordinator)
})
}
private func presentBootstrapNotSetup() {
let alert = UIAlertController(title: VectorL10n.keyVerificationBootstrapNotSetupTitle,
message: VectorL10n.keyVerificationBootstrapNotSetupMessage,
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: Bundle.mxk_localizedString(forKey: "ok"), style: .cancel, handler: { _ in
})
alert.addAction(cancelAction)
self.presenter.toPresentable().present(alert, animated: true, completion: nil)
}
private func presentManualDeviceVerification(for deviceId: String, of userId: String) {
let coordinator = KeyVerificationManuallyVerifyCoordinator(session: self.session, deviceId: deviceId, userId: userId)
coordinator.delegate = self
coordinator.start()
self.navigationRouter.push(coordinator, animated: true) {
self.remove(childCoordinator: coordinator)
}
}
}
// MARK: - UserVerificationSessionsStatusCoordinatorDelegate
extension UserVerificationCoordinator: UserVerificationSessionsStatusCoordinatorDelegate {
func userVerificationSessionsStatusCoordinatorDidClose(_ coordinator: UserVerificationSessionsStatusCoordinatorType) {
self.presenter.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
func userVerificationSessionsStatusCoordinator(_ coordinator: UserVerificationSessionsStatusCoordinatorType, didSelectDeviceWithId deviceId: String, for userId: String) {
self.presentSessionStatus(with: deviceId, for: userId, userDisplayName: self.userDisplayName)
}
}
// MARK: - UserVerificationSessionStatusCoordinatorDelegate
extension UserVerificationCoordinator: UserVerificationSessionStatusCoordinatorDelegate {
func userVerificationSessionStatusCoordinator(_ coordinator: UserVerificationSessionStatusCoordinatorType, wantsToVerifyDeviceWithId deviceId: String, for userId: String) {
self.presentDeviceVerification(for: deviceId)
}
func userVerificationSessionStatusCoordinator(_ coordinator: UserVerificationSessionStatusCoordinatorType, wantsToManuallyVerifyDeviceWithId deviceId: String, for userId: String) {
self.presentManualDeviceVerification(for: deviceId, of: userId)
}
func userVerificationSessionStatusCoordinatorDidClose(_ coordinator: UserVerificationSessionStatusCoordinatorType) {
self.presenter.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
}
// MARK: - UserVerificationCoordinatorDelegate
extension UserVerificationCoordinator: KeyVerificationCoordinatorDelegate {
func keyVerificationCoordinatorDidComplete(_ coordinator: KeyVerificationCoordinatorType, otherUserId: String, otherDeviceId: String) {
dismissPresenter(coordinator: coordinator)
}
func keyVerificationCoordinatorDidCancel(_ coordinator: KeyVerificationCoordinatorType) {
dismissPresenter(coordinator: coordinator)
}
func dismissPresenter(coordinator: KeyVerificationCoordinatorType) {
self.presenter.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
}
// MARK: - KeyVerificationManuallyVerifyCoordinatorDelegate
extension UserVerificationCoordinator: KeyVerificationManuallyVerifyCoordinatorDelegate {
func keyVerificationManuallyVerifyCoordinator(_ coordinator: KeyVerificationManuallyVerifyCoordinatorType, didVerifiedDeviceWithId deviceId: String, of userId: String) {
self.presenter.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
func keyVerificationManuallyVerifyCoordinatorDidCancel(_ coordinator: KeyVerificationManuallyVerifyCoordinatorType) {
self.presenter.toPresentable().dismiss(animated: true) {
self.remove(childCoordinator: coordinator)
}
}
}
| apache-2.0 | bd7ba3fd02e3747f4f63756c7dc77fc2 | 40.718182 | 193 | 0.719656 | 5.686493 | false | false | false | false |
shengzhc/Demo | DemoApp/DemoApp/Demo_SCTreeMenuViewController.swift | 1 | 7198 | //
// Demo_SCTreeMenuViewController.swift
// DemoApp
//
// Created by Shengzhe Chen on 11/29/14.
// Copyright (c) 2014 Shengzhe Chen. All rights reserved.
//
import Foundation
import UIKit
import SCTreeMenu
enum Demo_SCTreeMenuCellIdentifier: String
{
case DemoSCMenuItemCellIdentifier = "DemoSCMenuItemCellIdentifier", DemoSCSubMenuItemCellIdentifier = "DemoSCSubMenuItemCellIdentifier"
}
class Demo_SCTreeMenuItem: SCTreeMenuItem
{
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell: SCTreeMenuItemCell?
if !self.isRoot {
if indexPath.row <= self.depth {
cell = tableView.dequeueReusableCellWithIdentifier(Demo_SCTreeMenuCellIdentifier.DemoSCMenuItemCellIdentifier.rawValue, forIndexPath: indexPath) as? Demo_SCTreeMenuItemCell
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Demo_SCTreeMenuCellIdentifier.DemoSCSubMenuItemCellIdentifier.rawValue, forIndexPath: indexPath) as? Demo_SCTreeSubMenuItemCell
}
} else {
cell = tableView.dequeueReusableCellWithIdentifier(Demo_SCTreeMenuCellIdentifier.DemoSCMenuItemCellIdentifier.rawValue, forIndexPath: indexPath) as? Demo_SCTreeMenuItemCell
}
cell?.menuItem = self.menuItemAtIndexPath(indexPath)
if let menuView = tableView as? SCTreeMenuItemCellDelegate {
cell?.delegate = menuView
}
return cell!
}
}
class Demo_SCTreeMenuItemCell: SCTreeMenuItemCell
{
override var menuItem: SCTreeMenuItem? {
willSet {
if let menuItem = newValue {
if menuItem.isRoot {
self.menuItemActionButton.hidden = true
} else {
self.menuItemActionButton.hidden = menuItem.descendents.count <= 0
}
}
}
didSet {
self.menuItemTextLabel.text = self.menuItem?.text
if let menuItem = self.menuItem {
if menuItem.isCollapsed {
self.menuItemActionButton.setBackgroundImage(DemoIcons.defaultIcon, forState: UIControlState.Normal)
} else {
self.menuItemActionButton.setBackgroundImage(DemoIcons.rotateIcon, forState: UIControlState.Normal)
}
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.menuItemActionButton.setTitle(nil, forState: .Normal)
self.menuItemActionButton.setBackgroundImage(DemoIcons.defaultIcon, forState: .Normal)
self.seperator?.backgroundColor = ColorPalate.LightFuji.color.colorWithAlphaComponent(0.8)
self.contentView.addSubview(self.seperator!)
}
override func actionButtonClicked(sender: AnyObject?)
{
if let menuItem = self.menuItem {
var animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.duration = 0.1
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
var completion = {[unowned self] () -> Void in
self.delegate?.menuItemCell!(cell: self, didActionButtonClicked: sender)
return
}
if menuItem.isCollapsed {
menuItem.drillDown()
animation.byValue = M_PI_4
self.menuItemActionButton.layer.addAnimation(animation, forKey: "Animation")
CATransaction.commit()
} else {
menuItem.collapse()
animation.byValue = -M_PI_4
}
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
self.menuItemActionButton.layer.addAnimation(animation, forKey: "Animation")
CATransaction.commit()
}
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class Demo_SCTreeSubMenuItemCell: Demo_SCTreeMenuItemCell
{
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.backgroundColor = ColorPalate.LightBeige.color
self.menuItemTextLabel.font = UIFont(name: "AvenirNextCondensed-Regular", size: 12.0)
self.seperator?.hidden = true
}
override func layoutSubviews()
{
super.layoutSubviews()
self.menuItemTextLabel.frame = CGRectMake(24.0, (self.contentView.bounds.size.height - self.menuItemTextLabel.bounds.size.height)/2.0, self.menuItemTextLabel.bounds.size.width, self.menuItemTextLabel.bounds.size.height)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class Demo_SCTreeMenuView: SCTreeMenuView
{
required init(menuItem: SCTreeMenuItem)
{
super.init(menuItem: menuItem)
self.registerClass(Demo_SCTreeMenuItemCell.self, forCellReuseIdentifier: Demo_SCTreeMenuCellIdentifier.DemoSCMenuItemCellIdentifier.rawValue)
self.registerClass(Demo_SCTreeSubMenuItemCell.self, forCellReuseIdentifier: Demo_SCTreeMenuCellIdentifier.DemoSCSubMenuItemCellIdentifier.rawValue)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
class Demo_SCTreeMenuViewController: SCTreeMenuViewController
{
private func f(raw: [String: AnyObject]) -> SCTreeMenuItem
{
var root = Demo_SCTreeMenuItem(parent: nil, text: raw["text"] as String)
var descendents = raw["descendents"] as [[String: AnyObject]]
for descendent in descendents {
var subItem = f(descendent)
subItem.parent = root
root.descendents.append(subItem)
}
return root
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
self.title = "Demo SCTreeMenuViewController"
}
override func setupTree()
{
if let path = NSBundle.mainBundle().pathForResource("menu", ofType: "json") {
if let jsonData = NSData(contentsOfFile: path) {
if let jsonObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error: nil) as? [String: AnyObject] {
self.root = f(jsonObject)
}
}
}
}
override func setupMenuView()
{
self.menuView = Demo_SCTreeMenuView(menuItem: self.root!)
self.menuView?.frame = self.view.bounds
self.view.addSubview(self.menuView!)
self.menuView?.menuViewDelegate = self
}
override func menuView(#menuView: SCTreeMenuView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
var menuItem = menuView.menuItem.menuItemAtIndexPath(indexPath) as? Demo_SCTreeMenuItem
if menuItem != nil {
self.title = menuItem!.text
}
}
} | mit | b37eadf1d2f1bd5d44c84d00af8e34a0 | 36.108247 | 227 | 0.654765 | 4.870095 | false | false | false | false |
tingkerians/master | doharmony/UserDetailsViewController.swift | 1 | 4479 | //
// UserDetailsViewController.swift
// doharmony
//
// Created by Eleazer Toluan on 2/22/16.
// Copyright © 2016 Eleazer Toluan. All rights reserved.
//
import UIKit
class UserDetailsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBAction func closeButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var friendImage: UIButton!
@IBOutlet weak var ProfilePicture: UIImageView!
@IBOutlet weak var TracksTableView: UITableView!
var TitleArray : [String] = ["Little Star", "Jingle Bell", "Canon", "Two Tiger", "Bayer No.8", "Silent Night", "The Painter", "Gavotte", "Minuet 1", "Moments"]
var CoverPhotoArray : [String] = ["littleStar", "jingleBell", "canon", "default", "default", "default", "default", "default", "default", "default"]
let relationship = "friend"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ProfilePicture.layer.cornerRadius = ProfilePicture.frame.width / 2
self.TracksTableView.registerNib(UINib(nibName: "UserTracksTableViewCell", bundle: nil), forCellReuseIdentifier: "UserTracksTableViewCell")
// self.TracksTableView.rowHeight = UITableViewAutomaticDimension
// self.TracksTableView.setNeedsLayout()
// self.TracksTableView.layoutIfNeeded()
FriendFollowButton(friendImage)
}
@IBAction func unFriendFollowButton(sender: AnyObject) {
var Image : UIImage!
if relationship == "friend" {
Image = UIImage(named: "friend");
} else if relationship == "following" {
Image = UIImage(named: "follow");
}
let tintedImage = Image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
friendImage.setImage(tintedImage, forState: .Normal)
friendImage.tintColor = UIColor.whiteColor()
self.dismissViewControllerAnimated(true, completion: nil)
print("un\(relationship)!!!")
}
func FriendFollowButton(friendImage: UIButton) {
if relationship == "friend" {
friendImage.setImage(UIImage(named: "friend"), forState: UIControlState.Normal)
friendImage.tintColor = UIColor.whiteColor()
} else if relationship == "follow" {
friendImage.setImage(UIImage(named: "follow"), forState: UIControlState.Normal)
friendImage.tintColor = UIColor.orangeColor()
}
self.view.addSubview(friendImage)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(TracksTableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(TracksTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return TitleArray.count
}
func tableView(TracksTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : UserTracksTableViewCell = TracksTableView.dequeueReusableCellWithIdentifier("UserTracksTableViewCell") as! UserTracksTableViewCell
cell.TitleLabel.text = TitleArray[indexPath.row]
cell.ImageView.image = UIImage(named: CoverPhotoArray[indexPath.row])
return cell
}
func tableView(TracksTableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50.0
}
func tableView(TracksTableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let vc = TrackDetailsViewController(nibName: "TrackDetailsViewController", bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)
self.presentViewController(vc, animated: true, completion: nil)
}
/*
// 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.
}
*/
}
| unlicense | 122da7fd6e1795d8e1a1beed1c5b6f97 | 38.280702 | 163 | 0.682894 | 5.129439 | false | false | false | false |
kylef/Stencil | Sources/Inheritence.swift | 1 | 5746 | class BlockContext {
class var contextKey: String { return "block_context" }
// contains mapping of block names to their nodes and templates where they are defined
var blocks: [String: [BlockNode]]
init(blocks: [String: BlockNode]) {
self.blocks = [:]
blocks.forEach { self.blocks[$0.key] = [$0.value] }
}
func push(_ block: BlockNode, forKey blockName: String) {
if var blocks = blocks[blockName] {
blocks.append(block)
self.blocks[blockName] = blocks
} else {
self.blocks[blockName] = [block]
}
}
func pop(_ blockName: String) -> BlockNode? {
if var blocks = blocks[blockName] {
let block = blocks.removeFirst()
if blocks.isEmpty {
self.blocks.removeValue(forKey: blockName)
} else {
self.blocks[blockName] = blocks
}
return block
} else {
return nil
}
}
}
extension Collection {
func any(_ closure: (Iterator.Element) -> Bool) -> Iterator.Element? {
for element in self {
if closure(element) {
return element
}
}
return nil
}
}
class ExtendsNode: NodeType {
let templateName: Variable
let blocks: [String: BlockNode]
let token: Token?
class func parse(_ parser: TokenParser, token: Token) throws -> NodeType {
let bits = token.components
guard bits.count == 2 else {
throw TemplateSyntaxError("'extends' takes one argument, the template file to be extended")
}
let parsedNodes = try parser.parse()
guard (parsedNodes.any { $0 is ExtendsNode }) == nil else {
throw TemplateSyntaxError("'extends' cannot appear more than once in the same template")
}
let blockNodes = parsedNodes.compactMap { $0 as? BlockNode }
let nodes = blockNodes.reduce(into: [String: BlockNode]()) { accumulator, node in
accumulator[node.name] = node
}
return ExtendsNode(templateName: Variable(bits[1]), blocks: nodes, token: token)
}
init(templateName: Variable, blocks: [String: BlockNode], token: Token) {
self.templateName = templateName
self.blocks = blocks
self.token = token
}
func render(_ context: Context) throws -> String {
guard let templateName = try self.templateName.resolve(context) as? String else {
throw TemplateSyntaxError("'\(self.templateName)' could not be resolved as a string")
}
let baseTemplate = try context.environment.loadTemplate(name: templateName)
let blockContext: BlockContext
if let currentBlockContext = context[BlockContext.contextKey] as? BlockContext {
blockContext = currentBlockContext
for (name, block) in blocks {
blockContext.push(block, forKey: name)
}
} else {
blockContext = BlockContext(blocks: blocks)
}
do {
// pushes base template and renders it's content
// block_context contains all blocks from child templates
return try context.push(dictionary: [BlockContext.contextKey: blockContext]) {
try baseTemplate.render(context)
}
} catch {
// if error template is already set (see catch in BlockNode)
// and it happend in the same template as current template
// there is no need to wrap it in another error
if let error = error as? TemplateSyntaxError, error.templateName != token?.sourceMap.filename {
throw TemplateSyntaxError(reason: error.reason, stackTrace: error.allTokens)
} else {
throw error
}
}
}
}
class BlockNode: NodeType {
let name: String
let nodes: [NodeType]
let token: Token?
class func parse(_ parser: TokenParser, token: Token) throws -> NodeType {
let bits = token.components
guard bits.count == 2 else {
throw TemplateSyntaxError("'block' tag takes one argument, the block name")
}
let blockName = bits[1]
let nodes = try parser.parse(until(["endblock"]))
_ = parser.nextToken()
return BlockNode(name: blockName, nodes: nodes, token: token)
}
init(name: String, nodes: [NodeType], token: Token) {
self.name = name
self.nodes = nodes
self.token = token
}
func render(_ context: Context) throws -> String {
if let blockContext = context[BlockContext.contextKey] as? BlockContext, let child = blockContext.pop(name) {
let childContext = try self.childContext(child, blockContext: blockContext, context: context)
// render extension node
do {
return try context.push(dictionary: childContext) {
try child.render(context)
}
} catch {
throw error.withToken(child.token)
}
}
return try renderNodes(nodes, context)
}
// child node is a block node from child template that extends this node (has the same name)
func childContext(_ child: BlockNode, blockContext: BlockContext, context: Context) throws -> [String: Any] {
var childContext: [String: Any] = [BlockContext.contextKey: blockContext]
if let blockSuperNode = child.nodes.first(where: {
if let token = $0.token, case .variable = token.kind, token.contents == "block.super" {
return true
} else {
return false
}
}) {
do {
// render base node so that its content can be used as part of child node that extends it
childContext["block"] = ["super": try self.render(context)]
} catch {
if let error = error as? TemplateSyntaxError {
throw TemplateSyntaxError(
reason: error.reason,
token: blockSuperNode.token,
stackTrace: error.allTokens)
} else {
throw TemplateSyntaxError(
reason: "\(error)",
token: blockSuperNode.token,
stackTrace: [])
}
}
}
return childContext
}
}
| bsd-2-clause | cd7e2ffbb9b585c4ae0711c34c81f123 | 30.059459 | 113 | 0.645841 | 4.28806 | false | false | false | false |
BeitIssieShapiro/IssieBoard | ConfigurableKeyboard/Shapes.swift | 2 | 13908 |
import UIKit
///////////////////
// SHAPE OBJECTS //
///////////////////
class BackspaceShape: Shape {
override func drawCall(_ color: UIColor) {
drawBackspace(self.bounds, color: color)
}
}
class ShiftShape: Shape {
var withLock: Bool = false {
didSet {
self.overflowCanvas.setNeedsDisplay()
}
}
override func drawCall(_ color: UIColor) {
drawShift(self.bounds, color: color, withRect: self.withLock)
}
}
class GlobeShape: Shape {
override func drawCall(_ color: UIColor) {
drawGlobe(self.bounds, color: color)
}
}
class Shape: UIView {
var color: UIColor? {
didSet {
if let _ = self.color {
self.overflowCanvas.setNeedsDisplay()
}
}
}
// in case shapes draw out of bounds, we still want them to show
var overflowCanvas: OverflowCanvas!
convenience init() {
self.init(frame: CGRect.zero)
}
override required init(frame: CGRect) {
super.init(frame: frame)
self.isOpaque = false
self.clipsToBounds = false
self.overflowCanvas = OverflowCanvas(shape: self)
self.addSubview(self.overflowCanvas)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && self.bounds.equalTo(oldBounds!) {
return
}
oldBounds = self.bounds
super.layoutSubviews()
let overflowCanvasSizeRatio = CGFloat(1.25)
let overflowCanvasSize = CGSize(width: self.bounds.width * overflowCanvasSizeRatio, height: self.bounds.height * overflowCanvasSizeRatio)
self.overflowCanvas.frame = CGRect(
x: CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0),
y: CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0),
width: overflowCanvasSize.width,
height: overflowCanvasSize.height)
self.overflowCanvas.setNeedsDisplay()
}
func drawCall(_ color: UIColor) {}
class OverflowCanvas: UIView {
unowned var shape: Shape
init(shape: Shape) {
self.shape = shape
super.init(frame: CGRect.zero)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
//let csp = CGColorSpaceCreateDeviceRGB()
ctx!.saveGState()
let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2)
let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2)
ctx!.translateBy(x: xOffset, y: yOffset)
self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.black)
ctx!.restoreGState()
}
}
}
/////////////////////
// SHAPE FUNCTIONS //
/////////////////////
func getFactors(_ fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) {
let xSize = { () -> CGFloat in
let scaledSize = (fromSize.width / CGFloat(2))
if scaledSize > toRect.width {
return (toRect.width / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let ySize = { () -> CGFloat in
let scaledSize = (fromSize.height / CGFloat(2))
if scaledSize > toRect.height {
return (toRect.height / scaledSize) / CGFloat(2)
}
else {
return CGFloat(0.5)
}
}()
let actualSize = min(xSize, ySize)
return (actualSize, actualSize, actualSize, false, 0)
}
func centerShape(_ fromSize: CGSize, toRect: CGRect) {
let xOffset = (toRect.width - fromSize.width) / CGFloat(2)
let yOffset = (toRect.height - fromSize.height) / CGFloat(2)
let ctx = UIGraphicsGetCurrentContext()
ctx!.saveGState()
ctx!.translateBy(x: xOffset, y: yOffset)
}
func endCenter() {
let ctx = UIGraphicsGetCurrentContext()
ctx!.restoreGState()
}
func isIPad()->Bool{
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
}
func drawBackspace(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 44, height: 32), toRect: bounds)
let xScalingFactor = isIPad() ? CGFloat(0.65):CGFloat(0.35)//<<
let yScalingFactor = isIPad() ? CGFloat(0.65):CGFloat(0.35)//<<
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 44 * xScalingFactor, height: 32 * yScalingFactor), toRect: bounds)
let color = UIColor.white
let color2 = UIColor.red
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 26 * yScalingFactor), controlPoint1: CGPoint(x: 38 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 22 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 36 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 44 * xScalingFactor, y: 6 * yScalingFactor), controlPoint2: CGPoint(x: 44 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor), controlPoint1: CGPoint(x: 32 * xScalingFactor, y: 0 * yScalingFactor), controlPoint2: CGPoint(x: 16 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.close()
color.setFill()
bezierPath.fill()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 22 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 10 * yScalingFactor))
bezier2Path.close()
bezier2Path.fill()
color2.setStroke()
bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 34 * xScalingFactor, y: 10 * yScalingFactor))
bezier3Path.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 22 * yScalingFactor))
bezier3Path.close()
bezier3Path.fill()
color2.setStroke()
bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor
bezier3Path.stroke()
endCenter()
}
func drawShift(_ bounds: CGRect, color: UIColor, withRect: Bool) {
let factors = getFactors(CGSize(width: 38, height: (withRect ? 34 + 4 : 32)), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
//let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 38 * xScalingFactor, height: (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds)
//// Color Declarations
let color2 = color
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 28 * xScalingFactor, y: 48 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 38 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 19 * xScalingFactor, y: 0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 0 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 14 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 10 * xScalingFactor, y: 28 * yScalingFactor), controlPoint2: CGPoint(x: 10 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint1: CGPoint(x: 16 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 28 * yScalingFactor), controlPoint1: CGPoint(x: 24 * xScalingFactor, y: 32 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 32 * yScalingFactor))
bezierPath.addCurve(to: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor), controlPoint1: CGPoint(x: 28 * xScalingFactor, y: 26 * yScalingFactor), controlPoint2: CGPoint(x: 28 * xScalingFactor, y: 18 * yScalingFactor))
bezierPath.close()
color2.setFill()
bezierPath.fill()
if withRect {
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRect(x: 10 * xScalingFactor, y: 34 * yScalingFactor, width: 18 * xScalingFactor, height: 4 * yScalingFactor))
color2.setFill()
rectanglePath.fill()
}
endCenter()
}
func drawGlobe(_ bounds: CGRect, color: UIColor) {
let factors = getFactors(CGSize(width: 43, height: 43), toRect: bounds)
let xScalingFactor = factors.xScalingFactor
let yScalingFactor = factors.yScalingFactor
let lineWidthScalingFactor = factors.lineWidthScalingFactor
centerShape(CGSize(width: 43 * xScalingFactor, height: 43 * yScalingFactor), toRect: bounds)
//// Color Declarations
let color = color
//// Oval Drawing
let ovalPath = UIBezierPath(ovalIn: CGRect(x: 0 * xScalingFactor, y: 0 * yScalingFactor, width: 40 * xScalingFactor, height: 40 * yScalingFactor))
color.setStroke()
ovalPath.lineWidth = 1 * lineWidthScalingFactor
ovalPath.stroke()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: 40 * yScalingFactor))
bezierPath.addLine(to: CGPoint(x: 20 * xScalingFactor, y: -0 * yScalingFactor))
bezierPath.close()
color.setStroke()
bezierPath.lineWidth = 1 * lineWidthScalingFactor
bezierPath.stroke()
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 39.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.addLine(to: CGPoint(x: 0.5 * xScalingFactor, y: 19.5 * yScalingFactor))
bezier2Path.close()
color.setStroke()
bezier2Path.lineWidth = 1 * lineWidthScalingFactor
bezier2Path.stroke()
//// Bezier 3 Drawing
let bezier3Path = UIBezierPath()
bezier3Path.move(to: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor))
bezier3Path.addCurve(to: CGPoint(x: 21.63 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 21.63 * xScalingFactor, y: 0.42 * yScalingFactor), controlPoint2: CGPoint(x: 41 * xScalingFactor, y: 19 * yScalingFactor))
bezier3Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier3Path.lineWidth = 1 * lineWidthScalingFactor
bezier3Path.stroke()
//// Bezier 4 Drawing
let bezier4Path = UIBezierPath()
bezier4Path.move(to: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor))
bezier4Path.addCurve(to: CGPoint(x: 18.72 * xScalingFactor, y: 39.6 * yScalingFactor), controlPoint1: CGPoint(x: 17.76 * xScalingFactor, y: 0.74 * yScalingFactor), controlPoint2: CGPoint(x: -2.5 * xScalingFactor, y: 19.04 * yScalingFactor))
bezier4Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier4Path.lineWidth = 1 * lineWidthScalingFactor
bezier4Path.stroke()
//// Bezier 5 Drawing
let bezier5Path = UIBezierPath()
bezier5Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor))
bezier5Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 7 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 7 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 21 * yScalingFactor))
bezier5Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier5Path.lineWidth = 1 * lineWidthScalingFactor
bezier5Path.stroke()
//// Bezier 6 Drawing
let bezier6Path = UIBezierPath()
bezier6Path.move(to: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor))
bezier6Path.addCurve(to: CGPoint(x: 34 * xScalingFactor, y: 33 * yScalingFactor), controlPoint1: CGPoint(x: 6 * xScalingFactor, y: 33 * yScalingFactor), controlPoint2: CGPoint(x: 19 * xScalingFactor, y: 22 * yScalingFactor))
bezier6Path.lineCapStyle = CGLineCap.round;
color.setStroke()
bezier6Path.lineWidth = 1 * lineWidthScalingFactor
bezier6Path.stroke()
endCenter()
}
| apache-2.0 | 17178a311a602411c592df062ca0414b | 39.196532 | 244 | 0.653796 | 3.913337 | false | false | false | false |
y-hryk/ViewPager | Classes/MenuCell.swift | 1 | 4399 | //
// MenuCell.swift
// ViewPagerDemo
//
// Created by yamaguchi on 2016/09/01.
// Copyright © 2016年 h.yamaguchi. All rights reserved.
//
import UIKit
open class MenuCell: UICollectionViewCell {
open var label: UILabel!
open var indicator: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupViews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private
func setupViews() {
self.backgroundColor = UIColor.clear
self.indicator = UIView()
self.contentView.addSubview(self.indicator)
self.label = UILabel()
self.label.textColor = UIColor.black
self.label.textAlignment = .center
self.label.lineBreakMode = .byTruncatingTail
self.label.isUserInteractionEnabled = true
self.label.backgroundColor = UIColor.clear
self.contentView.addSubview(self.label)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([
NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier:1.0, constant: 0),
NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: self.contentView, attribute: .leading, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: self.contentView, attribute: .trailing, multiplier: 1.0, constant: 0),
NSLayoutConstraint(item: label, attribute: .bottom, relatedBy: .equal, toItem: self.contentView, attribute: .bottom, multiplier: 1.0, constant: 0)
])
}
// MARK: Public
func setRowData( datas: [String], indexPath: IndexPath, currentIndex: Int, option: ViewPagerOption) {
if datas.isEmpty { return }
let index = indexPath.row % datas.count
self.label.tag = indexPath.row
self.label.text = ""
self.label.font = option.menuItemFont
self.label.text = datas[index]
self.indicator.backgroundColor = option.menuItemIndicatorColor
let width = MenuCell.cellWidth(datas[index], option: option)
self.indicator.layer.cornerRadius = option.indicatorRadius
if option.indicatorType == .line {
self.indicator.frame = CGRect(x: 0, y: self.frame.size.height - 1.5, width: width, height: 1.5)
} else {
self.indicator.frame = CGRect(x: 0, y: 5, width: width, height: 30)
}
if currentIndex % datas.count == index {
self.label.textColor = option.menuItemSelectedFontColor
self.label.font = option.menuItemSelectedFont
self.indicator.isHidden = false
} else {
self.label.textColor = option.menuItemFontColor
self.label.font = option.menuItemFont
self.indicator.isHidden = true
}
}
static func cellWidth(_ text: String, option: ViewPagerOption) -> CGFloat {
// CGSize maxSize = CGSizeMake(CGFloat.max, 40);
let style = NSMutableParagraphStyle()
style.alignment = .center
style.lineBreakMode = .byWordWrapping
let attributes = [NSFontAttributeName : option.menuItemFont,
NSParagraphStyleAttributeName : style]
let options = unsafeBitCast(
NSStringDrawingOptions.usesLineFragmentOrigin.rawValue |
NSStringDrawingOptions.usesFontLeading.rawValue,
to: NSStringDrawingOptions.self)
let frame = text.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 40),
options: options,
attributes: attributes,
context: nil)
// let width = max(frame.width + 10 + 10,80)
// return frame.width + (5 * 2) + (5 * 2)
// return 100
if let itemWidth = option.menuItemWidth {
return itemWidth
} else {
return CGFloat(Int(frame.width) + (Int(option.menuItemMargin) * 2))
}
}
}
| mit | c14f3098cb0ba933b6cf0bd6d3a72110 | 37.226087 | 163 | 0.598271 | 4.90625 | false | false | false | false |
Boss-XP/ChatToolBar | BXPChatToolBar/BXPChatToolBar/Classes/BXPChat/BXPChatToolBar/BXPChatFaceView/BXPFaceItemModel.swift | 1 | 1129 | //
// BXPFaceItem.swift
// BXPChatToolBar
//
// Created by 向攀 on 17/1/13.
// Copyright © 2017年 Yunyun Network Technology Co,Ltd. All rights reserved.
//
import UIKit
class BXPFaceItemModel: NSObject {
var imageIndex: NSNumber = 0;
// func faceImage() -> UIImage? {
//
// var index = imageIndex.intValue//NSNumber() as! Integer
// index += 1
//
// let subPath = NSString(format: "%d.png", index)//imageIndex + ".png"
//
// let iamgePath = Bundle.main.path(forResource: subPath as String, ofType: nil)! as String
//
// let image = UIImage(contentsOfFile: iamgePath)
//
// return image
// }
lazy var faceImage: UIImage = {
var index = self.imageIndex.intValue//NSNumber() as! Integer
index += 1
let subPath = NSString(format: "%d.png", index)//imageIndex + ".png"
let imagePath = Bundle.main.path(forResource: subPath as String, ofType: nil)! as String
let tempImage = UIImage(contentsOfFile: imagePath)
return tempImage!
}()
}
| apache-2.0 | c488e3329d186cc95f6f9fb9a2ce0e7a | 26.365854 | 98 | 0.579323 | 3.909408 | false | false | false | false |
blitzagency/events | Events/TypedEventManagerHost/TypedEventManagerHost.swift | 1 | 2826 | //
// TypedEventManagerHost.swift
// Events
//
// Created by Adam Venturella on 7/22/16.
// Copyright © 2016 BLITZ. All rights reserved.
//
import Foundation
public protocol TypedEventManagerHost {
associatedtype EventType: RawRepresentable
var eventManager: TypedEventManager<EventType> {get}
}
extension TypedEventManagerHost{
public func trigger(_ event: EventType){
guard let value = event.rawValue as? String else{
fatalError("TypedEventManager<\(Event.self)> is not representable as a 'String'")
}
trigger(value)
}
public func trigger<Data>(_ event: EventType, data: Data){
guard let value = event.rawValue as? String else{
fatalError("TypedEventManager<\(Event.self)> is not representable as a 'String'")
}
trigger(value, data: data)
}
func trigger(_ event: String){
let event = buildEvent(event, publisher: self)
trigger(event)
}
func trigger<Data>(_ event: String, data: Data){
let event = buildEvent(event, publisher: self, data: data)
trigger(event)
}
/**
Stop listening to events triggered by the specified publisher
- Parameter publisher: The TypedEventManagerHost we would like to stop listening to.
- Parameter event: An optional `String RawRepresentable` of type `T` event to limit our removal scope
- Remark:
If no event is given, all events will be silenced from the specified publisher.
*/
public func stopListening<Event: RawRepresentable, Publisher: TypedEventManagerHost>(_ publisher: Publisher, event: Event?)
where Event == Publisher.EventType, Event.RawValue == String {
eventManager.stopListening(publisher.eventManager, event: event?.rawValue)
}
/**
Stop listening to events triggered by the specified publisher
- Parameter publisher: The TypedEventManageable we would like to stop listening to.
- Parameter event: An optional `String RawRepresentable` of type `T` event to limit our removal scope
- Remark:
If no event is given, all events will be silenced from the specified publisher.
*/
public func stopListening<Event: RawRepresentable, Publisher: TypedEventManageable>(_ publisher: Publisher, event: Event?)
where Event == Publisher.EventType, Event.RawValue == String {
eventManager.stopListening(publisher, event: event?.rawValue)
}
public func stopListening(){
eventManager.stopListening()
}
public func stopListening<Publisher: TypedEventManageable>(_ publisher: Publisher){
eventManager.stopListening(publisher)
}
public func stopListening<Publisher: TypedEventManagerHost>(_ publisher: Publisher){
eventManager.stopListening(publisher.eventManager)
}
}
| mit | 3c8b3f453c81fa7767312bf93a3d95e6 | 31.848837 | 127 | 0.692389 | 4.771959 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Site Creation/Wizard/SiteCreationWizardLauncher.swift | 1 | 1659 | /// Puts together the Site creation wizard, assembling steps.
final class SiteCreationWizardLauncher {
private lazy var creator: SiteCreator = {
return SiteCreator()
}()
private lazy var segmentsStep: WizardStep = {
let segmentsService = SiteCreationSegmentsService(managedObjectContext: ContextManager.sharedInstance().mainContext)
return SiteSegmentsStep(creator: self.creator, service: segmentsService)
}()
private lazy var designStep: WizardStep = {
return SiteDesignStep(creator: self.creator)
}()
private lazy var addressStep: WizardStep = {
let addressService = DomainsServiceAdapter(managedObjectContext: ContextManager.sharedInstance().mainContext)
return WebAddressStep(creator: self.creator, service: addressService)
}()
private lazy var siteAssemblyStep: WizardStep = {
let siteAssemblyService = EnhancedSiteCreationService(managedObjectContext: ContextManager.sharedInstance().mainContext)
return SiteAssemblyStep(creator: self.creator, service: siteAssemblyService)
}()
private lazy var steps: [WizardStep] = {
return [
self.designStep,
self.addressStep,
self.siteAssemblyStep
]
}()
private lazy var wizard: SiteCreationWizard = {
return SiteCreationWizard(steps: self.steps)
}()
lazy var ui: UIViewController? = {
guard let wizardContent = wizard.content else {
return nil
}
wizardContent.modalPresentationStyle = .pageSheet
wizardContent.isModalInPresentation = true
return wizardContent
}()
}
| gpl-2.0 | c5e7716bd6b68ff43bc659366a98ec27 | 33.5625 | 128 | 0.690175 | 5.317308 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressUITests/Screens/TabNavComponent.swift | 1 | 1826 | import UITestsFoundation
import XCTest
class TabNavComponent: BaseScreen {
let mySitesTabButton: XCUIElement
let readerTabButton: XCUIElement
let notificationsTabButton: XCUIElement
init() {
let tabBars = XCUIApplication().tabBars["Main Navigation"]
mySitesTabButton = tabBars.buttons["mySitesTabButton"]
readerTabButton = tabBars.buttons["readerTabButton"]
notificationsTabButton = tabBars.buttons["notificationsTabButton"]
super.init(element: mySitesTabButton)
}
func gotoMeScreen() throws -> MeTabScreen {
gotoMySiteScreen()
let meButton = app.navigationBars.buttons["meBarButton"]
meButton.tap()
return try MeTabScreen()
}
@discardableResult
func gotoMySiteScreen() -> MySiteScreen {
mySitesTabButton.tap()
return MySiteScreen()
}
func gotoAztecEditorScreen() -> AztecEditorScreen {
let mySiteScreen = gotoMySiteScreen()
let actionSheet = mySiteScreen.gotoCreateSheet()
actionSheet.gotoBlogPost()
return AztecEditorScreen(mode: .rich)
}
func gotoBlockEditorScreen() -> BlockEditorScreen {
let mySite = gotoMySiteScreen()
let actionSheet = mySite.gotoCreateSheet()
actionSheet.gotoBlogPost()
return BlockEditorScreen()
}
func gotoReaderScreen() -> ReaderScreen {
readerTabButton.tap()
return ReaderScreen()
}
func gotoNotificationsScreen() -> NotificationsScreen {
notificationsTabButton.tap()
return NotificationsScreen()
}
static func isLoaded() -> Bool {
return XCUIApplication().buttons["mySitesTabButton"].exists
}
static func isVisible() -> Bool {
return XCUIApplication().buttons["mySitesTabButton"].isHittable
}
}
| gpl-2.0 | 81c5783e269da708f6ec2c4124e39d22 | 27.53125 | 74 | 0.674151 | 4.948509 | false | true | false | false |
byu-oit/ios-byuSuite | byuSuite/Classes/ByuRequest/ByuRequest2.swift | 2 | 4746 | //
// ByuRequest.swift
// byuSuite
//
// Created by Nathan Johnson on 4/5/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import Foundation
//MARK: - Constants
private let AUTHORIZATION = "Authorization"
//TODO: inherits from NSObject to be accessible in Objective-C, not needed when Swift only
class ByuRequest2: NSObject {
//MARK: - Types
enum RequestMethod: String {
case GET
case POST
case PUT
case DELETE
}
enum AuthMethod {
case NO_AUTH
case OAUTH
}
enum MimeType: String {
case JSON = "application/json"
case XML = "application/xml"
}
//MARK: - Properties
private var request: URLRequest
var authMethod: AuthMethod
var pathToReadableError: String //Set this in order to catch and display readable errors from a service. Set this as a path that points to a readable error. For instance, if a service might return {"message": "Please add a class before continuing"}, then you would pass in "message". If a service might return {"response": {"error": {"code": 400", "message": "You have already registered for this class"}}}, then you would pass in "response.error.message"
var defaultReadableError: String? //Set this if you would like a default error message custom to your feature, other than the default readable error ByuError already sets
var retryCount: Int
//MARK: - Computed properties
var requestMethod: RequestMethod {
get {
guard let rawValue = request.httpMethod, let method = RequestMethod(rawValue: rawValue) else { return .GET }
return method
} set {
request.httpMethod = newValue.rawValue
}
}
var body: Data? {
get {
return request.httpBody
} set {
request.httpBody = newValue
}
}
var acceptType: MimeType? {
//Need to override the getter to make a setter
get {return nil}
set {
if let accept = newValue?.rawValue {
addRequestHeader("Accept", with: accept)
} else {
//If they set it to nil, remove the default value
request.setValue(nil, forHTTPHeaderField: "Accept")
}
}
}
var contentType: MimeType? {
//Need to override the getter to make a setter
get {return nil}
set {
if let content = newValue?.rawValue {
addRequestHeader("Content-Type", with: content)
}
}
}
override var description: String {
return "\(String(describing: request.url)) \(String(describing: request.httpMethod))\n\(String(describing: request.allHTTPHeaderFields))"
}
init(requestMethod: RequestMethod = .GET, url: URL, authMethod: AuthMethod = .OAUTH, acceptType: MimeType? = .JSON, contentType: MimeType? = nil, body: Data? = nil, retryCount: Int = 1, pathToReadableError: String = "", defaultReadableError: String? = nil) {
//Set all normal properties
self.request = URLRequest(url: url)
self.authMethod = authMethod
self.pathToReadableError = pathToReadableError
self.defaultReadableError = defaultReadableError
self.retryCount = retryCount
super.init()
//Set all computed properties
self.requestMethod = requestMethod
self.body = body
self.acceptType = acceptType
self.contentType = contentType
}
//MARK: - Methods
func addRequestHeader(_ header: String, with value: String) {
/*
This line will make it so that any headers already set will NOT be overwritten.
This is especially helpful if you need an Authorization or Accept header that is not built into the ByuRequest
*/
if request.value(forHTTPHeaderField: header) == nil {
request.addValue(value, forHTTPHeaderField: header)
}
}
func startAsynchronous(completionHandler: @escaping (ByuResponse2) -> Void) {
ByuNetworkActivityIndicator.incrementActivityCount()
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
ByuNetworkActivityIndicator.decrementActivityCount()
OperationQueue.main.addOperation {
let byuResponse = ByuResponse2(data: data, response: response as? HTTPURLResponse, error: error, pathToReadableError: self.pathToReadableError, defaultReadableError: self.defaultReadableError)
//If the reponse failed, and there was no readable message, look for retry policy
if byuResponse.failed {
//If the debug message is empty, that means it was an intelligible error, and we should not try again.
if byuResponse.error?.debugMessage != nil && self.retryCount > 0 {
print("Error: \(byuResponse.response?.statusCode ?? 0) \(byuResponse.getDataString() ?? "")")
print("Retrying \(self.retryCount) more time(s)...")
self.startAsynchronous(completionHandler: completionHandler)
self.retryCount -= 1
return
} else {
print("Error: \(byuResponse.error?.description ?? "")")
}
}
completionHandler(byuResponse)
}
}.resume()
}
}
| apache-2.0 | 3cabece55c5e8433f04348e3ff8d3a41 | 31.5 | 456 | 0.713804 | 3.960768 | false | false | false | false |
aleph7/BrainCore | Tests/SigmoidLayerTests.swift | 1 | 4488 | // Copyright © 2016 Venture Media Labs. All rights reserved.
//
// This file is part of BrainCore. The full BrainCore copyright notice,
// including terms governing use, modification, and redistribution, is
// contained in the file LICENSE at the root of the source code distribution
// tree.
import XCTest
import BrainCore
import Metal
import Upsurge
func sigmoid(_ x: Float) -> Float {
return 1.0 / (1.0 + exp(-x))
}
class SigmoidLayerTests: MetalTestCase {
func testForward() {
let device = self.device
let dataSize = 512 * 512
let batchSize = 1
let data = Blob(count: dataSize)
for i in 0..<dataSize {
data[i] = 2 * Float(arc4random()) / Float(UINT32_MAX) - 1.0
}
let dataLayer = Source(name: "input", data: data, batchSize: batchSize)
let layer = SigmoidLayer(size: dataSize, name: "layer")
let sinkLayer = Sink(name: "output", inputSize: dataSize, batchSize: batchSize)
let net = Net.build {
dataLayer => layer => sinkLayer
}
let expectation = self.expectation(description: "Net forward pass")
let evaluator = try! Evaluator(net: net, device: device)
evaluator.evaluate() { snapshot in
expectation.fulfill()
}
waitForExpectations(timeout: 5) { error in
let result = sinkLayer.data
for i in 0..<dataSize {
XCTAssertEqualWithAccuracy(result[i], sigmoid(data[i]), accuracy: 0.001)
}
}
}
func testBackward() {
let device = self.device
let dataSize = 1024 * 1024
let batchSize = 1
let input = Blob(count: dataSize)
for i in 0..<dataSize {
input[i] = 2 * Float(arc4random()) / Float(UINT32_MAX) - 1.0
}
let label = Blob(count: dataSize)
for i in 0..<dataSize {
label[i] = 2 * Float(arc4random()) / Float(UINT32_MAX) - 1.0
}
let dataLayer = Source(name: "input", data: input, batchSize: batchSize)
let labelLayer = Source(name: "label", data: label, batchSize: batchSize)
let layer = SigmoidLayer(size: dataSize, name: "layer")
let lossLayer = L2LossLayer(size: dataSize)
let sinkLayer = Sink(name: "sink", inputSize: 1, batchSize: 1)
let net = Net.build {
dataLayer => layer
[layer, labelLayer] => lossLayer => sinkLayer
}
let expectation = self.expectation(description: "Net backward pass")
let trainer = try! Trainer(net: net, device: device, batchSize: batchSize)
var inputDeltas = [Float]()
var outputDeltas = [Float]()
trainer.run() { snapshot in
inputDeltas = [Float](snapshot.inputDeltasOfLayer(layer)!)
outputDeltas = [Float](snapshot.outputDeltasOfLayer(layer)!)
expectation.fulfill()
}
waitForExpectations(timeout: 5) { error in
for i in 0..<dataSize {
XCTAssertEqualWithAccuracy(inputDeltas[i], outputDeltas[i] * sigmoid(input[i]) * (1 - sigmoid(input[i])), accuracy: 0.001)
}
}
}
func testForwardLargeBatchSize() {
let device = self.device
let dataSize = 2
let batchSize = 4
let data = Matrix<Float>(rows: batchSize, columns: dataSize)
for i in 0..<dataSize {
for j in 0..<batchSize {
data[j, i] = 2 * Float(arc4random()) / Float(UINT32_MAX) - 1.0
}
}
let dataLayer = Source(name: "input", data: data.elements, batchSize: batchSize)
let layer = SigmoidLayer(size: dataSize, name: "layer")
let sinkLayer = Sink(name: "output", inputSize: dataSize, batchSize: batchSize)
let net = Net.build {
dataLayer => layer => sinkLayer
}
let expectation = self.expectation(description: "Net forward pass")
var result = [Float]()
let trainer = try! Trainer(net: net, device: device, batchSize: batchSize)
trainer.run() { snapshot in
result = [Float](snapshot.outputOfLayer(layer)!)
expectation.fulfill()
}
waitForExpectations(timeout: 5) { error in
for i in 0..<dataSize {
for j in 0..<batchSize {
XCTAssertEqualWithAccuracy(result[j + i * batchSize], sigmoid(data[j, i]), accuracy: 0.001)
}
}
}
}
}
| mit | 634d84e9bbef293876c394dc9d3ae95b | 33.782946 | 138 | 0.58012 | 4.249053 | false | false | false | false |
pabloroca/PR2StudioSwift | Source/PR2ViewWaiting.swift | 1 | 2169 | //
// PR2ViewWaiting.swift
// PR2StudioSwift
//
// Created by Pablo Roca Rozas on 3/6/18.
// Copyright © 2018 PR2Studio. All rights reserved.
//
import UIKit
public final class PR2ViewWaiting: UIView {
public var message: String = "" {
didSet {
self.lblWaiting.text = message
}
}
private lazy var lblWaiting: UILabel = {
let label = UILabel()
label.textColor = UIColor.black
label.font = UIFont.boldSystemFont(ofSize: 15)
label.textAlignment = .center
return label
}()
private lazy var waitingIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.style = .gray
return activityIndicator
}()
public init(message: String = "Loading data ...") {
super.init(frame: .zero)
self.lblWaiting.text = message
configureUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureUI() {
backgroundColor = UIColor.white
isHidden = true
addSubview(waitingIndicator)
waitingIndicator.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
waitingIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
waitingIndicator.centerYAnchor.constraint(equalTo: centerYAnchor)
])
addSubview(lblWaiting)
lblWaiting.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
lblWaiting.topAnchor.constraint(equalTo: topAnchor),
lblWaiting.leadingAnchor.constraint(equalTo: leadingAnchor),
lblWaiting.trailingAnchor.constraint(equalTo: trailingAnchor),
lblWaiting.bottomAnchor.constraint(equalTo: waitingIndicator.topAnchor, constant: 15.0)
])
}
// MARK: - Custom methods
public func show() {
isHidden = false
waitingIndicator.startAnimating()
}
public func hide() {
waitingIndicator.stopAnimating()
isHidden = true
}
}
| mit | 80774b258a52bc5da46fa371e07b3942 | 27.906667 | 99 | 0.649446 | 5.199041 | false | false | false | false |
crspybits/SMSyncServer | iOS/iOSTests/Pods/SMCoreLib/SMCoreLib/Classes/MiscUI/SMUIMessages/v1/SMAcquireImage.swift | 3 | 4813 | //
// SMAcquireImage.swift
// SMCoreLib
//
// Created by Christopher Prince on 5/22/16.
// Copyright © 2016 Spastic Muffin, LLC. All rights reserved.
//
// Let a user acquire images from the camera or other sources.
// Note that this UI interacts with classes such as UITextView. E.g., it will cause the keyboard to be dismissed if present.
import Foundation
import UIKit
public protocol SMAcquireImageDelegate : class {
// Called before the image is acquired to obtain a URL for the image. A file shouldn't exist at this URL yet.
func smAcquireImageURLForNewImage(acquireImage:SMAcquireImage) -> SMRelativeLocalURL
// Called after the image is acquired.
func smAcquireImage(acquireImage:SMAcquireImage, newImageURL: SMRelativeLocalURL)
}
public class SMAcquireImage : NSObject {
public weak var delegate:SMAcquireImageDelegate!
public var acquiringImage:Bool {
return self._acquiringImage
}
// This should be a value between 0 and 1, with larger values giving higher quality, but larger files.
public var compressionQuality:CGFloat = 0.5
private weak var parentViewController:UIViewController!
private let imagePicker = UIImagePickerController()
public var _acquiringImage:Bool = false
// documentsDirectoryPath is the path within the Documents directory to store new image files.
public init(withParentViewController parentViewController:UIViewController) {
super.init()
self.parentViewController = parentViewController
self.imagePicker.delegate = self
}
public func showAlert(fromBarButton barButton:UIBarButtonItem) {
self._acquiringImage = true
let alert = UIAlertController(title: "Get an image?", message: nil, preferredStyle: .ActionSheet)
alert.popoverPresentationController?.barButtonItem = barButton
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel) { alert in
self._acquiringImage = false
})
if UIImagePickerController.isSourceTypeAvailable(
UIImagePickerControllerSourceType.Camera) {
alert.addAction(UIAlertAction(title: "Camera", style: .Default) { alert in
self.getImageUsing(.Camera)
})
}
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
alert.addAction(UIAlertAction(title: "Camera Roll", style: .Default) { alert in
self.getImageUsing(.SavedPhotosAlbum)
})
}
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
alert.addAction(UIAlertAction(title: "Photo Library", style: .Default) { alert in
self.getImageUsing(.PhotoLibrary)
})
}
self.parentViewController.presentViewController(alert, animated: true, completion: nil)
}
private func getImageUsing(sourceType:UIImagePickerControllerSourceType) {
self.imagePicker.sourceType = sourceType
self.imagePicker.allowsEditing = false
self.parentViewController.presentViewController(imagePicker, animated: true,
completion: nil)
}
}
extension SMAcquireImage : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
Log.msg("info: \(info)")
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
// Save image to album if you want; also considers video
// http://www.techotopia.com/index.php/Accessing_the_iOS_8_Camera_and_Photo_Library_in_Swift
let newFileURL = self.delegate?.smAcquireImageURLForNewImage(self)
Log.msg("newFileURL: \(newFileURL)")
var success:Bool = true
if let imageData = UIImageJPEGRepresentation(image, self.compressionQuality) {
do {
try imageData.writeToURL(newFileURL!, options: .AtomicWrite)
} catch (let error) {
Log.error("Error writing file: \(error)")
success = false
}
}
else {
Log.error("Couldn't convert image to JPEG!")
success = false
}
if success {
self.delegate.smAcquireImage(self, newImageURL: newFileURL!)
}
self._acquiringImage = false
picker.dismissViewControllerAnimated(true, completion: nil)
}
public func imagePickerControllerDidCancel(picker: UIImagePickerController) {
Log.msg("imagePickerControllerDidCancel")
self._acquiringImage = false
picker.dismissViewControllerAnimated(true, completion: nil)
}
} | gpl-3.0 | 52bebb0576afa2bb5150ffc4158f871e | 37.814516 | 130 | 0.673525 | 5.224756 | false | false | false | false |
moritzdietsche/mdnotificationview | MDNotificationViewTests/MDNotificationLayoutViewTests.swift | 1 | 2930 | //
// MDNotificationLayoutViewTests.swift
// MDNotificationView
//
// Copyright (c) 2017 Moritz Dietsche
//
// 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
@testable import MDNotificationView
class MDNotificationLayoutViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAddInvalidNib() {
let view = MDNotificationLayoutView()
view.addNib(named: "DoesNotExist")
XCTAssertEqual(0, view.subviews.count)
}
func testCompactLayoutView() {
let view = MDNotificationCompactLayoutView()
let notificationView = MDNotificationView(view: view)
XCTAssertEqual(view.frame.width, UIScreen.main.bounds.width)
XCTAssertEqual(view.frame.height, notificationView.frame.height - UIApplication.shared.statusBarFrame.height)
}
func testCompactButtonLayoutView() {
let view = MDNotificationCompactButtonLayoutView()
let notificationView = MDNotificationView(view: view)
XCTAssertEqual(view.frame.width, UIScreen.main.bounds.width)
XCTAssertEqual(view.frame.height, notificationView.frame.height - UIApplication.shared.statusBarFrame.height)
}
func testExpandedImageLayoutView() {
let view = MDNotificationExpandedImageLayoutView()
let notificationView = MDNotificationView(view: view)
XCTAssertEqual(view.frame.width, UIScreen.main.bounds.width)
XCTAssertEqual(view.frame.height, notificationView.frame.height - UIApplication.shared.statusBarFrame.height)
}
}
| mit | 9fe5d0fb928b5fe3b8650cb2a81904ad | 39.694444 | 117 | 0.720478 | 4.688 | false | true | false | false |
svetlanama/ASAutoResizingTextView | Example/Tests/Tests.swift | 1 | 1189 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ASAutoResizingTextView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | df883f9518474414ab1cd70249aae383 | 22.66 | 63 | 0.370245 | 5.476852 | false | false | false | false |
peterlafferty/LuasLife | LuasLife/StopPickerViewController.swift | 1 | 2970 | //
// StopPickerViewController.swift
// LuasLife
//
// Created by Peter Lafferty on 12/05/2016.
// Copyright © 2016 Peter Lafferty. All rights reserved.
//
import UIKit
import LuasLifeKit
class StopPickerViewController: UITableViewController {
var dataSource = StopPickerDataSource()
fileprivate static let fakeStop = Stop(id:14, name: "Central Park")
var route = Route(id: 0, origin: fakeStop, destination: fakeStop, stops: [])
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = dataSource
self.tableView.delegate = dataSource
dataSource.load(route, completionHandler: {
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showTramsSegue" {
if let indexPath = tableView.indexPathForSelectedRow {
if let vc = segue.destination as? RealTimeInfoViewController {
vc.stop = dataSource[indexPath]
}
}
}
}
}
class StopPickerDataSource: NSObject {
var stops = [Stop]()
let reuseIdentifier = "StopCell"
func load(_ route: Route, completionHandler: @escaping (Void) -> (Void)) {
let request = GetStopsRequest(route: route) { (result) -> Void in
let error: Error?
if case let .error(e) = result {
error = e
} else {
error = nil
}
if case let .success(s) = result {
self.stops = s
} else {
self.stops = [Stop]()
}
print(error ?? "no error")
completionHandler()
}
request.start()
}
/*
func stopAt(indexPath: NSIndexPath) -> Route {
return routes[indexPath.section].stops[indexPath.row]
}
subscript(index: Int) -> Route {
get {
return routes[0].stops[index]
}
} */
subscript(indexPath: IndexPath) -> Stop {
get {
return stops[indexPath.row]
}
}
}
extension StopPickerDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = stops[indexPath.row].name
return cell
}
}
extension StopPickerDataSource: UITableViewDelegate {
}
| mit | 2f10314801100f9a263b16d13cc6b5ed | 24.376068 | 100 | 0.594139 | 4.827642 | false | false | false | false |
morgz/SwiftGoal | SwiftGoal/ViewModels/MatchesViewModel.swift | 1 | 4741 | //
// MatchesViewModel.swift
// SwiftGoal
//
// Created by Martin Richter on 10/05/15.
// Copyright (c) 2015 Martin Richter. All rights reserved.
//
import ReactiveCocoa
class MatchesViewModel {
typealias MatchChangeset = Changeset<Match>
// Inputs
let active = MutableProperty(false)
let refreshObserver: Observer<Void, NoError>
// Outputs
let title: String
let contentChangesSignal: Signal<MatchChangeset, NoError>
let isLoading: MutableProperty<Bool>
let alertMessageSignal: Signal<String, NoError>
// Actions
// lazy var deleteAction: Action<NSIndexPath, Bool, NSError> = { [unowned self] in
// return Action({ indexPath in
// let match = self.matchAtIndexPath(indexPath)
// return self.store.deleteMatch(match)
// })
// }()
private let store: StoreType
private let contentChangesObserver: Observer<MatchChangeset, NoError>
private let alertMessageObserver: Observer<String, NoError>
private var matches: [Match]
// MARK: - Lifecycle
init(store: StoreType) {
self.title = "Matches"
self.store = store
self.matches = []
let (refreshSignal, refreshObserver) = SignalProducer<Void, NoError>.buffer()
self.refreshObserver = refreshObserver
let (contentChangesSignal, contentChangesObserver) = Signal<MatchChangeset, NoError>.pipe()
self.contentChangesSignal = contentChangesSignal
self.contentChangesObserver = contentChangesObserver
let isLoading = MutableProperty(false)
self.isLoading = isLoading
let (alertMessageSignal, alertMessageObserver) = Signal<String, NoError>.pipe()
self.alertMessageSignal = alertMessageSignal
self.alertMessageObserver = alertMessageObserver
// Trigger refresh when view becomes active
active.producer
.filter { $0 }
.map { _ in () }
.start(refreshObserver)
// Trigger refresh after deleting a match
// deleteAction.values
// .filter { $0 }
// .map { _ in () }
// .observe(refreshObserver)
refreshSignal
.on(next: { _ in isLoading.value = true })
.flatMap(.Latest) { _ in
return store.fetchMatches()
.flatMapError { error in
alertMessageObserver.sendNext(error.localizedDescription)
return SignalProducer(value: [])
}
}
.on(next: { _ in isLoading.value = false })
.combinePrevious([]) // Preserve history to calculate changeset
.startWithNext({ [weak self] (oldMatches, newMatches) in
self?.matches = newMatches
if let observer = self?.contentChangesObserver {
let changeset = Changeset(
oldItems: oldMatches,
newItems: newMatches,
contentMatches: Match.contentMatches
)
observer.sendNext(changeset)
}
})
// Feed deletion errors into alert message signal
// deleteAction.errors
// .map { $0.localizedDescription }
// .observe(alertMessageObserver)
}
// MARK: - Data Source
func numberOfSections() -> Int {
return 1
}
func numberOfMatchesInSection(section: Int) -> Int {
return matches.count
}
func homePlayersAtIndexPath(indexPath: NSIndexPath) -> String {
let match = matchAtIndexPath(indexPath)
return separatedNamesForPlayers(match.homePlayers)
}
func awayPlayersAtIndexPath(indexPath: NSIndexPath) -> String {
let match = matchAtIndexPath(indexPath)
return separatedNamesForPlayers(match.awayPlayers)
}
func resultAtIndexPath(indexPath: NSIndexPath) -> String {
let match = matchAtIndexPath(indexPath)
return "\(match.homeGoals) : \(match.awayGoals)"
}
// MARK: View Models
func editViewModelForNewMatch() -> EditMatchViewModel {
return EditMatchViewModel(store: store)
}
func editViewModelForMatchAtIndexPath(indexPath: NSIndexPath) -> EditMatchViewModel {
let match = matchAtIndexPath(indexPath)
return EditMatchViewModel(store: store, match: match)
}
// MARK: Internal Helpers
private func matchAtIndexPath(indexPath: NSIndexPath) -> Match {
return matches[indexPath.row]
}
private func separatedNamesForPlayers(players: [Player]) -> String {
let playerNames = players.map { player in player.name }
return playerNames.joinWithSeparator(", ")
}
}
| mit | a568b8c59d1bb33d797a2f6f7c7a538a | 31.472603 | 99 | 0.620755 | 5.059765 | false | false | false | false |
crazypoo/PTools | PooToolsSource/Base/PTDevFunction.swift | 1 | 5485 | //
// PTDevFunction.swift
// PooTools_Example
//
// Created by jax on 2022/10/11.
// Copyright © 2022 crazypoo. All rights reserved.
//
import UIKit
#if DEBUG
#if canImport(FLEX)
import FLEX
#endif
#if canImport(InAppViewDebugger)
import InAppViewDebugger
#endif
#endif
public typealias GoToAppDev = () -> Void
@objcMembers
public class PTDevFunction: NSObject {
public static let share = PTDevFunction()
public var mn_PFloatingButton : PFloatingButton?
public var goToAppDevVC:GoToAppDev?
public func createLabBtn()
{
if UIApplication.applicationEnvironment() != .appStore
{
UserDefaults.standard.set(true,forKey: LocalConsole.ConsoleDebug)
if self.mn_PFloatingButton == nil
{
mn_PFloatingButton = PFloatingButton.init(view: AppWindows as Any, frame: CGRect.init(x: 0, y: 200, width: 50, height: 50))
mn_PFloatingButton?.backgroundColor = .randomColor
let btnLabel = UILabel()
btnLabel.textColor = .randomColor
btnLabel.sizeToFit()
btnLabel.textAlignment = .center
btnLabel.font = .systemFont(ofSize: 13)
btnLabel.numberOfLines = 0
btnLabel.text = "实验室"
mn_PFloatingButton?.addSubview(btnLabel)
btnLabel.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
mn_PFloatingButton?.longPressBlock = { (sender) in
PTUtils.base_alertVC(msg:"调试框架",okBtns: ["取消","全部开启","FLEX","Log","FPS","全部关闭","调试功能界面","检测界面"],showIn: PTUtils.getCurrentVC()) { index, title in
if index == 0
{
}
else
{
if title == "全部开启"
{
PTDevFunction.GobalDevFunction_open()
}
else if title == "全部关闭"
{
PTDevFunction.GobalDevFunction_close()
}
else if title == "FLEX"
{
#if DEBUG
if FLEXManager.shared.isHidden
{
FLEXManager.shared.showExplorer()
}
else
{
FLEXManager.shared.hideExplorer()
}
#endif
}
else if title == "Log"
{
if PTLocalConsoleFunction.share.localconsole.terminal == nil
{
PTLocalConsoleFunction.share.localconsole.createSystemLogView()
}
else
{
PTLocalConsoleFunction.share.localconsole.cleanSystemLogView()
}
}
else if title == "FPS"
{
if PCheckAppStatus.shared.closed
{
PCheckAppStatus.shared.open()
}
else
{
PCheckAppStatus.shared.close()
}
}
else if title == "调试功能界面"
{
if self.goToAppDevVC != nil
{
self.goToAppDevVC!()
}
}
else if title == "检测界面"
{
#if DEBUG
InAppViewDebugger.present()
#endif
}
}
}
}
}
}
}
public class func GobalDevFunction_open()
{
if UIApplication.applicationEnvironment() != .appStore
{
#if DEBUG
FLEXManager.shared.showExplorer()
#endif
PTLocalConsoleFunction.share.localconsole.createSystemLogView()
PCheckAppStatus.shared.open()
}
}
public class func GobalDevFunction_close()
{
if UIApplication.shared.inferredEnvironment != .appStore
{
#if DEBUG
FLEXManager.shared.hideExplorer()
#endif
PTLocalConsoleFunction.share.localconsole.cleanSystemLogView()
PCheckAppStatus.shared.close()
}
}
public func lab_btn_release()
{
UserDefaults.standard.set(false,forKey: LocalConsole.ConsoleDebug)
self.mn_PFloatingButton?.removeFromSuperview()
self.mn_PFloatingButton = nil
}
}
| mit | 1c71da36c6e7097ef8b056d93f760490 | 34.254902 | 165 | 0.410641 | 5.882225 | false | false | false | false |
theMatys/myWatch | myWatch/Source/UI/Core/MWImageView.swift | 1 | 2383 | //
// MWImageView.swift
// myWatch
//
// Created by Máté on 2017. 05. 23..
// Copyright © 2017. theMatys. All rights reserved.
//
import UIKit
@IBDesignable
class MWImageView: UIImageView
{
@IBInspectable var tintingColor: UIColor = MWDefaults.Colors.defaultTintColor
{
didSet
{
if(!silent)
{
self.silently().image = tintedImage()
}
else
{
silent = false
}
}
}
@IBInspectable var gradientTinted: Bool = false
{
didSet
{
if(!silent)
{
self.silently().image = tintedImage()
}
else
{
silent = false
}
}
}
@IBInspectable var tintingGradient: MWGradient = MWDefaults.Gradients.defaultGradient
{
didSet
{
if(!silent)
{
self.silently().image = tintedImage()
}
else
{
silent = false
}
}
}
override var image: UIImage?
{
didSet
{
if(!silent)
{
self.silently().image = tintedImage()
}
else
{
silent = false
}
}
}
private var silent = false
override init(frame: CGRect)
{
super.init(frame: frame)
self.image = tintedImage()
}
override init(image: UIImage?)
{
super.init(image: image)
self.image = tintedImage()
}
override init(image: UIImage?, highlightedImage: UIImage?)
{
super.init(image: image, highlightedImage: highlightedImage)
self.image = tintedImage()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.image = tintedImage()
}
func silently() -> MWImageView
{
silent = true
return self
}
private func tintedImage() -> UIImage?
{
if(self.gradientTinted)
{
return self.image?.tinted(with: self.tintingGradient)
}
else
{
return self.image?.tinted(with: self.tintingColor)
}
}
}
| gpl-3.0 | cfc929e8c22c6407f76c0df962b94e8c | 18.669421 | 89 | 0.455882 | 5.042373 | false | false | false | false |
IT-Department-Projects/POP-II | iOS App/notesNearby_iOS_finalUITests/notesNearby_iOS_final/IQKeyboardManagerSwift/IQToolbar/IQTitleBarButtonItem.swift | 1 | 5737 | //
// IQTitleBarButtonItem.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
private var kIQBarTitleInvocationTarget = "kIQBarTitleInvocationTarget"
private var kIQBarTitleInvocationSelector = "kIQBarTitleInvocationSelector"
public class IQTitleBarButtonItem: IQBarButtonItem {
public var font : UIFont? {
didSet {
if let unwrappedFont = font {
_titleButton?.titleLabel?.font = unwrappedFont
} else {
_titleButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13)
}
}
}
override public var title: String? {
didSet {
_titleButton?.setTitle(title, for: UIControlState())
}
}
/**
selectableTextColor to be used for displaying button text when button is enabled.
*/
public var selectableTextColor : UIColor? {
didSet {
if let color = selectableTextColor {
_titleButton?.setTitleColor(color, for:UIControlState())
} else {
_titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState())
}
}
}
/**
Optional target & action to behave toolbar title button as clickable button
@param target Target object.
@param action Target Selector.
*/
public func setTitleTarget(_ target: AnyObject?, action: Selector?) {
titleInvocation = (target, action)
}
/**
Customized Invocation to be called on title button action. titleInvocation is internally created using setTitleTarget:action: method.
*/
public var titleInvocation : (target: AnyObject?, action: Selector?) {
get {
let target: AnyObject? = objc_getAssociatedObject(self, &kIQBarTitleInvocationTarget) as AnyObject?
var action : Selector?
if let selectorString = objc_getAssociatedObject(self, &kIQBarTitleInvocationSelector) as? String {
action = NSSelectorFromString(selectorString)
}
return (target: target, action: action)
}
set(newValue) {
objc_setAssociatedObject(self, &kIQBarTitleInvocationTarget, newValue.target, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if let unwrappedSelector = newValue.action {
objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, NSStringFromSelector(unwrappedSelector), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
} else {
objc_setAssociatedObject(self, &kIQBarTitleInvocationSelector, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
if (newValue.target == nil || newValue.action == nil)
{
self.isEnabled = false
_titleButton?.isEnabled = false
_titleButton?.removeTarget(nil, action: nil, for: .touchUpInside)
}
else
{
self.isEnabled = true
_titleButton?.isEnabled = true
_titleButton?.addTarget(newValue.target, action: newValue.action!, for: .touchUpInside)
}
}
}
private var _titleButton : UIButton?
private var _titleView : UIView?
override init() {
super.init()
}
init(title : String?) {
self.init(title: nil, style: UIBarButtonItemStyle.plain, target: nil, action: nil)
_titleView = UIView()
_titleView?.backgroundColor = UIColor.clear
_titleView?.autoresizingMask = [.flexibleWidth,.flexibleHeight]
_titleButton = UIButton(type: .system)
_titleButton?.isEnabled = false
_titleButton?.titleLabel?.numberOfLines = 3
_titleButton?.setTitleColor(UIColor.lightGray, for:.disabled)
_titleButton?.setTitleColor(UIColor.init(colorLiteralRed: 0.0, green: 0.5, blue: 1.0, alpha: 1), for:UIControlState())
_titleButton?.backgroundColor = UIColor.clear
_titleButton?.titleLabel?.textAlignment = .center
_titleButton?.setTitle(title, for: UIControlState())
_titleButton?.autoresizingMask = [.flexibleWidth,.flexibleHeight]
font = UIFont.systemFont(ofSize: 13.0)
_titleButton?.titleLabel?.font = self.font
_titleView?.addSubview(_titleButton!)
customView = _titleView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 43b0e9da5d08ed90b5dee75ecd6f440d | 38.840278 | 177 | 0.647725 | 5.041301 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Dynamic Programming/2维DP/221_Maximal Square.swift | 1 | 2717 | // 221_Maximal Square
// https://leetcode.com/problems/maximal-square/
//
// Created by Honghao Zhang on 9/20/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
//
//Example:
//
//Input:
//
//1 0 1 0 0
//1 0 1 1 1
//1 1 1 1 1
//1 0 0 1 0
//
//Output: 4
//
// 求一个matrix中最大的正方形
import Foundation
class Num221 {
// https://leetcode.com/problems/maximal-square/solution/
// MARK: - DP 2维
// DP standard with 4 steps
func maximalSquare(_ matrix: [[Character]]) -> Int {
// get matrix size
let m = matrix.count
guard m > 0 else { return 0 }
let n = matrix[0].count
guard n > 0 else { return 0 }
// 1) state: s[i][j] is the size of the largest square ends at [i][j]
// aka. [i][j] is the bottom right corner.
var s = Array(repeating: Array(repeating: 0, count: n), count: m)
// 2) initialize, edges are determined
for i in 0..<m {
for j in 0..<n {
if i == 0 || j == 0 {
s[i][j] = (matrix[i][j] == "0") ? 0 : 1
}
}
}
// 3) function: s[i][j] = min(s[i - 1][j - 1], s[i][j - 1], s[i - 1][j]) + 1
for i in 0..<m {
for j in 0..<n {
// skip edges
if i == 0 || j == 0 {
continue
}
if matrix[i][j] == "1" {
s[i][j] = min(s[i - 1][j - 1], s[i][j - 1], s[i - 1][j]) + 1
}
}
}
print(1, terminator: "")
// at this moment, s contains the largest size for any i and j
// 4) answer
var maxSize = 0
for i in 0..<m {
for j in 0..<n {
maxSize = max(maxSize, s[i][j])
}
}
return maxSize * maxSize
}
// DP optimized
func maximalSquare2(_ matrix: [[Character]]) -> Int {
// get matrix size
let m = matrix.count
guard m > 0 else { return 0 }
let n = matrix[0].count
guard n > 0 else { return 0 }
// state: s[i][j] is the size of the largest square ends at [i][j]
// aka. [i][j] is the bottom right corner.
var s = Array(repeating: Array(repeating: 0, count: n), count: m)
// answer
var maxSize = 0
for i in 0..<m {
for j in 0..<n {
// initialize: For edge
if i == 0 || j == 0 {
s[i][j] = (matrix[i][j] == "0") ? 0 : 1
maxSize = max(maxSize, s[i][j])
continue
}
if matrix[i][j] == "0" {
continue
}
else {
// function:
s[i][j] = min(s[i - 1][j - 1], s[i][j - 1], s[i - 1][j]) + 1
maxSize = max(maxSize, s[i][j])
}
}
}
return maxSize * maxSize
}
}
| mit | 9a954a16b8790e337493e01588336181 | 22.426087 | 117 | 0.495917 | 3.114451 | false | false | false | false |
davedufresne/SwiftParsec | Sources/SwiftParsec/SequenceAggregation.swift | 1 | 2310 | //==============================================================================
// SequenceAggregation.swift
// SwiftParsec
//
// Created by David Dufresne on 2015-09-14.
// Copyright © 2015 David Dufresne. All rights reserved.
//
// Sequence extension
//==============================================================================
//==============================================================================
// Extension containing aggregation methods.
extension Sequence {
/// Return a tuple containing the elements of `self`, in order, that satisfy
/// the predicate `includeElement`. The second array of the tuple contains
/// the remainder of the list.
///
/// - parameter includeElement: The predicate function used to split the
/// sequence.
/// - returns:
/// - included: The elements that satisfied the predicate.
/// - remainder: The remainder of `self`.
func part(
_ includeElement: (Self.Iterator.Element) throws -> Bool
) rethrows
-> (included: [Self.Iterator.Element], remainder: [Self.Iterator.Element]) {
var included: [Self.Iterator.Element] = []
var remainder: [Self.Iterator.Element] = []
for elem in self {
if (try includeElement(elem)) {
included.append(elem)
} else {
remainder.append(elem)
}
}
return (included, remainder)
}
}
//==============================================================================
// Extension containing aggregation methods when the `Sequence` contains
// elements that are `Equatable`.
extension Sequence where Iterator.Element: Equatable {
/// Return an array with the duplicate elements removed. In particular, it
/// keeps only the first occurrence of each element.
///
/// - returns: An array with the duplicate elements removed.
func removingDuplicates() -> [Self.Iterator.Element] {
return reduce([]) { (acc, elem) in
guard !acc.contains(elem) else { return acc }
return acc.appending(elem)
}
}
}
| bsd-2-clause | 963e8eaa8120377ff030ccff717ac4e7 | 30.630137 | 80 | 0.487224 | 5.743781 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/FontSizeSliderViewController.swift | 1 | 3667 | import UIKit
@objc(WMFFontSizeSliderViewController)
class FontSizeSliderViewController: UIViewController {
@IBOutlet fileprivate var slider: SWStepSlider!
@IBOutlet weak var tSmallImageView: UIImageView!
@IBOutlet weak var tLargeImageView: UIImageView!
fileprivate var maximumValue: Int?
fileprivate var currentValue: Int?
fileprivate var theme = Theme.standard
@objc static let WMFArticleFontSizeMultiplierKey = "WMFArticleFontSizeMultiplier"
@objc static let WMFArticleFontSizeUpdatedNotification = "WMFArticleFontSizeUpdatedNotification"
let fontSizeMultipliers = [WMFFontSizeMultiplier.extraSmall, WMFFontSizeMultiplier.small, WMFFontSizeMultiplier.medium, WMFFontSizeMultiplier.large, WMFFontSizeMultiplier.extraLarge, WMFFontSizeMultiplier.extraExtraLarge, WMFFontSizeMultiplier.extraExtraExtraLarge]
override func viewDidLoad() {
super.viewDidLoad()
if let max = maximumValue {
if let current = currentValue {
setValues(0, maximum: max, current: current)
maximumValue = nil
currentValue = nil
}
}
apply(theme: self.theme)
slider.isAccessibilityElement = true
slider.accessibilityTraits = UIAccessibilityTraits.adjustable
slider.accessibilityLabel = CommonStrings.textSizeSliderAccessibilityLabel
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setValuesWithSteps(fontSizeMultipliers.count, current: indexOfCurrentFontSize())
}
func setValuesWithSteps(_ steps: Int, current: Int) {
if self.isViewLoaded {
setValues(0, maximum: steps - 1, current: current)
} else {
maximumValue = steps - 1
currentValue = current
}
}
func setValues(_ minimum: Int, maximum: Int, current: Int) {
slider.minimumValue = minimum
slider.maximumValue = maximum
slider.value = current
}
@IBAction func fontSliderValueChanged(_ slider: SWStepSlider) {
if slider.value > fontSizeMultipliers.count {
return
}
let multiplier = fontSizeMultipliers[slider.value].rawValue
let userInfo = [FontSizeSliderViewController.WMFArticleFontSizeMultiplierKey: multiplier]
NotificationCenter.default.post(name: Notification.Name(FontSizeSliderViewController.WMFArticleFontSizeUpdatedNotification), object: nil, userInfo: userInfo)
setValuesWithSteps(fontSizeMultipliers.count, current: indexOfCurrentFontSize())
}
func indexOfCurrentFontSize() -> Int {
if let fontSize = UserDefaults.standard.wmf_articleFontSizeMultiplier() as? Int, let multiplier = WMFFontSizeMultiplier(rawValue: fontSize) {
return fontSizeMultipliers.firstIndex(of: multiplier)!
}
return fontSizeMultipliers.count / 2
}
}
extension FontSizeSliderViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.midBackground
slider.backgroundColor = theme.colors.midBackground
tSmallImageView.tintColor = theme.colors.secondaryText
tLargeImageView.tintColor = theme.colors.secondaryText
if self.parent is AppearanceSettingsViewController {
view.backgroundColor = theme.colors.paperBackground
slider.backgroundColor = theme.colors.paperBackground
}
}
}
| mit | db9c57e9fd933f39c08eff7e0bba1800 | 36.804124 | 269 | 0.682302 | 5.598473 | false | false | false | false |
BPForEveryone/BloodPressureForEveryone | BPApp/BPEveryone/BPEPatientDetailViewController.swift | 1 | 2218 | //
// BPEPatientDetailViewController.swift
// BPForEveryone
//
// Created by Chris Blackstone on 9/29/17.
// Copyright © 2017 BlackstoneBuilds. All rights reserved.
//
import UIKit
import os.log
class BPEPatientDetailViewController: UITableViewController {
@IBOutlet weak var dateOfBirthLabel: UILabel!
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var lastBPDateTimeLabel: UILabel!
@IBOutlet weak var lastBPMeasurmentLabel: UILabel!
@IBOutlet weak var lastBPPercentileLabel: UILabel!
var patientId: Int = 0
@IBAction func back(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
update()
}
public func update() {
let patient = Config.patients[patientId]
dateOfBirthLabel.text = BirthDay.format(date: patient.birthDate)
heightLabel.text = patient.height.description
if patient.bloodPressureMeasurements.count != 0 {
let measurement = patient.bloodPressureMeasurements[0]
lastBPDateTimeLabel.text = BirthDay.format(date: measurement.measurementDate)
lastBPPercentileLabel.text = String(describing: patient.percentile)
lastBPMeasurmentLabel.text = "\(patient.diastolic)/\(patient.systolic)"
} else {
lastBPDateTimeLabel.text = "N/A"
lastBPPercentileLabel.text = "N/A"
lastBPMeasurmentLabel.text = "N/A"
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let patient = Config.patients[patientId]
return "\(patient.firstName) \(patient.lastName)"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
// Blood pressure list also requires a patient id.
if (segue.identifier == "bloodPressureList") {
let controller = (segue.destination as! UINavigationController).topViewController as! BPEBPListViewController
controller.patientId = self.patientId
}
}
}
| mit | 89804bde36d065e6fd472a4d81d64e9a | 32.590909 | 121 | 0.649977 | 4.677215 | false | false | false | false |
presence-insights/pi-clientsdk-ios | IBMPIGeofence/PIGeofencingManager.swift | 1 | 17372 | /**
* IBMPIGeofence
* PIGeofencingManager.swift
*
* Performs all communication to the PI Rest API.
*
* © Copyright 2016 IBM Corp.
*
* Licensed under the Presence Insights Client iOS Framework License (the "License");
* you may not use this file except in compliance with the License. You may find
* a copy of the license in the license.txt file in this package.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import CoreLocation
import CoreData
import MapKit
import CocoaLumberjack
public let kGeofencingManagerDidSynchronize = "com.ibm.pi.GeofencingManagerDidSynchronize"
@objc(IBMPIGeofencingManagerDelegate)
public protocol PIGeofencingManagerDelegate:class {
/// The device enters into a geofence
func geofencingManager(manager: PIGeofencingManager, didEnterGeofence geofence: PIGeofence? )
/// The device exits a geofence
func geofencingManager(manager: PIGeofencingManager, didExitGeofence geofence: PIGeofence? )
optional func geofencingManager(manager: PIGeofencingManager, didStartDownload download: PIDownload)
optional func geofencingManager(manager: PIGeofencingManager, didReceiveDownload download: PIDownload)
}
/// `PIGeofencingManager` is your entry point to the PI Geofences.
/// Its responsability is to monitor the PI geofences.
/// When the user enters or exits a geofence, `PIGeofencingManager` notifies
/// the Presence Insights backend
@objc(IBMPIGeofencingManager)
public final class PIGeofencingManager:NSObject {
/// When `true`, the `PIGeofencingManager`does not post event against PIT backend
public var privacy = false
/// By default, `PIGeofencingManager` can monitore up to 15 regions simultaneously.
public static let DefaultMaxRegions = 15
let locationManager = CLLocationManager()
/// Maximum of consecutive retry for downloading geofence definitions from PI
/// We wait for one hour between each retry
public var maxDownloadRetry:Int {
set {
PIGeofencePreferences.maxDownloadRetry = newValue
}
get {
return PIGeofencePreferences.maxDownloadRetry
}
}
/// Number of days between each check against PI for downloading the geofence definitions
public var intervalBetweenDownloads = 1
var regions:[String:CLCircularRegion]?
/// The length of the sides of the bounding box used to find out
/// which fences should be monitored.
public let maxDistance:Int
/// Maximum number of regions which can be monitored simultaneously.
public let maxRegions:Int
lazy var dataController = PIGeofenceData.dataController
/// PI Service
let service:PIService
public weak var delegate:PIGeofencingManagerDelegate?
/// Create a `PIGeofencingManager` with the given PI connection parameters
/// This initializer must be called in the main thread
/// - parameter tenantCode: PI tenant
/// - parameter orgCode: PI organisation
/// - parameter baseURL: PI end point
/// - parameter username: PI username
/// - parameter password: PI password
/// - parameter maxDistance: When a significant change location is triggered,
/// `PIGeofencingManager` search for geofences within a square of side length
/// of maxDistance meters.
/// - parameter maxRegions: The maximum number of regions being monitored at any time. The system
/// limit is 20 regions per app. Default is 15
public init(tenantCode:String, orgCode:String?, baseURL:String, username:String, password:String,maxDistance:Int = 10_000, maxRegions:Int = DefaultMaxRegions ) {
self.maxDistance = maxDistance
if (1...20).contains(maxRegions) {
self.maxRegions = maxRegions
} else {
DDLogError("maxRegions \(maxRegions) is out of range",asynchronous:false)
self.maxRegions = self.dynamicType.DefaultMaxRegions
}
self.service = PIService(tenantCode:tenantCode,orgCode:orgCode,baseURL:baseURL,username:username,password:password)
super.init()
self.locationManager.delegate = self
self.service.delegate = self
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PIGeofencingManager.didBecomeActive(_:)),
name: UIApplicationWillEnterForegroundNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(PIGeofencingManager.willResignActive(_:)),
name: UIApplicationDidEnterBackgroundNotification,
object: nil)
}
/// Enables or disables the logging
/// - parameter enable: `true` to enable the logging
public static func enableLogging(enable:Bool) {
if enable {
DDLog.addLogger(DDTTYLogger.sharedInstance()) // TTY = Xcode console
DDLog.addLogger(DDASLLogger.sharedInstance()) // ASL = Apple System Logs
let documentsFileManager = DDLogFileManagerDefault(logsDirectory:PIGeofenceUtils.documentsDirectory.path,defaultFileProtectionLevel:NSFileProtectionNone)
let fileLogger: DDFileLogger = DDFileLogger(logFileManager: documentsFileManager) // File Logger
fileLogger.rollingFrequency = 60*60*24 // 24 hours
fileLogger.logFileManager.maximumNumberOfLogFiles = 7
DDLog.addLogger(fileLogger)
} else {
DDLog.removeAllLoggers()
}
}
/// Returns the pathes of the log files
public static func logFiles() -> [String] {
let documentsFileManager = DDLogFileManagerDefault(logsDirectory:PIGeofenceUtils.documentsDirectory.path)
return documentsFileManager.sortedLogFilePaths().map { String($0) }
}
/**
Ask the back end for the latest geofences to monitor
- parameter completionHandler: The closure called when the synchronisation is completed
*/
public func synchronize(completionHandler: ((Bool)-> Void)? = nil) {
let request = PIGeofenceFencesDownloadRequest(lastSyncDate:PIGeofencePreferences.lastSyncDate)
guard let response = service.executeDownload(request) else {
completionHandler?(false)
return
}
let moc = dataController.writerContext
moc.performBlock {
let download:PIDownload = moc.insertObject()
download.sessionIdentifier = response.backgroundSessionIdentifier
download.taskIdentifier = response.taskIdentifier
download.progressStatus = .InProgress
download.startDate = NSDate()
do {
try moc.save()
let downloadURI = download.objectID.URIRepresentation()
dispatch_async(dispatch_get_main_queue()) {
let download = self.dataController.managedObjectWithURI(downloadURI) as! PIDownload
self.delegate?.geofencingManager?(self, didStartDownload: download)
completionHandler?(true)
}
} catch {
DDLogError("Core Data Error \(error)",asynchronous:false)
completionHandler?(false)
}
}
}
/// Method to be called by the AppDelegate to handle the download of the geofence definitions
public func handleEventsForBackgroundURLSession(identifier: String, completionHandler: () -> Void) -> Bool {
DDLogInfo("PIGeofencingManager.handleEventsForBackgroundURLSession",asynchronous:false)
guard identifier.hasPrefix("com.ibm.PI") else {
DDLogInfo("Not a PIbackgroundURLSession",asynchronous:false)
return false
}
self.service.backgroundURLSessionCompletionHandler = completionHandler
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
let session = NSURLSession(configuration: config, delegate: self.service, delegateQueue: nil)
self.service.backgroundPendingSessions.insert(session)
return true
}
func didBecomeActive(notification:NSNotification) {
}
/**
Cancel all pending request when the app is going to background
*/
func willResignActive(notification:NSNotification) {
self.service.cancelAll()
}
///
/// - parameter code: The code of the geofence to remove
/// - parameter completionHandler: closure invoked on completion
///
func removeGeofence(code:String,completionHandler: ((Bool) -> Void)? = nil) {
let geofenceDeleteRequest = PIGeofenceDeleteRequest(geofenceCode: code) {
response in
switch response.result {
case .OK?:
DDLogInfo("PIGeofenceDeleteRequest OK",asynchronous:false)
let moc = self.dataController.writerContext
moc.performBlock {
do {
let fetchRequest = PIGeofence.fetchRequest
fetchRequest.predicate = NSPredicate(format: "code == %@",code)
guard let geofences = try moc.executeFetchRequest(fetchRequest) as? [PIGeofence] else {
DDLogError("Programming error",asynchronous:false)
fatalError("Programming error")
}
guard let geofence = geofences.first else {
DDLogError("Programming error",asynchronous:false)
fatalError("Programming error")
}
DDLogInfo("Delete fence \(geofence.name) \(geofence.code)",asynchronous:false)
moc.deleteObject(geofence)
try moc.save()
if let region = self.regions?[code] {
self.regions?.removeValueForKey(code)
self.locationManager.stopMonitoringForRegion(region)
DDLogVerbose("Stop monitoring \(region.identifier)",asynchronous:false)
}
self.updateMonitoredGeofencesWithMoc(moc)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(true)
}
} catch {
DDLogError("Core Data Error \(error)",asynchronous:false)
assertionFailure("Core Data Error \(error)")
}
}
case .Cancelled?:
DDLogVerbose("PIGeofenceDeleteRequest cancelled",asynchronous:false)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(false)
}
case let .Error(error)?:
DDLogError("PIGeofenceDeleteRequest error \(error)",asynchronous:false)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(false)
}
case let .Exception(error)?:
DDLogError("PIGeofenceDeleteRequest exception \(error)",asynchronous:false)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(false)
}
case let .HTTPStatus(status,_)?:
DDLogError("PIGeofenceDeleteRequest status \(status)",asynchronous:false)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(false)
}
case nil:
assertionFailure("Programming Error")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(false)
}
}
}
self.service.executeRequest(geofenceDeleteRequest)
}
/**
Add a `local` geofence, that is a geofence that is not defined by the backend
- parameter name: Name of the geofence
- parameter center: The position of the center of the fence
- parameter radius: The radius of the fence, should be larger than 200 m
- parameter completionHandler: Closure to be called when the fence has been added
*/
func addGeofence(name:String,center:CLLocationCoordinate2D,radius:Int,completionHandler: ((PIGeofence?) -> Void)? = nil) {
guard let _ = service.orgCode else {
DDLogError("No Organization Code",asynchronous:false)
completionHandler?(nil)
return
}
let geofenceCreateRequest = PIGeofenceCreateRequest(geofenceName: name, geofenceDescription: nil, geofenceRadius: radius, geofenceCoordinate: center) {
response in
switch response.result {
case .OK?:
DDLogVerbose("PIGeofenceCreateRequest OK \(response.geofenceCode)",asynchronous:false)
guard let geofenceCode = response.geofenceCode else {
DDLogError("PIGeofenceCreateRequest Missing fence Id")
completionHandler?(nil)
return
}
let moc = self.dataController.writerContext
moc.performBlock {
let geofence:PIGeofence = moc.insertObject()
geofence.name = name
geofence.radius = radius
geofence.code = geofenceCode
geofence.latitude = center.latitude
geofence.longitude = center.longitude
do {
try moc.save()
self.updateMonitoredGeofencesWithMoc(moc)
let geofenceURI = geofence.objectID.URIRepresentation()
dispatch_async(dispatch_get_main_queue()) {
let geofence = self.dataController.managedObjectWithURI(geofenceURI) as! PIGeofence
completionHandler?(geofence)
}
} catch {
DDLogError("Core Data Error \(error)")
assertionFailure("Core Data Error \(error)")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
}
}
case .Cancelled?:
DDLogVerbose("PIGeofenceCreateRequest Cancelled",asynchronous:false)
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
case let .Error(error)?:
DDLogError("PIGeofenceCreateRequest Error \(error)")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
case let .Exception(error)?:
DDLogError("PIGeofenceCreateRequest Exception \(error)")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
case let .HTTPStatus(status,_)?:
DDLogError("PIGeofenceCreateRequest Status \(status)")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
case nil:
assertionFailure("Programming Error")
dispatch_async(dispatch_get_main_queue()) {
completionHandler?(nil)
}
}
}
service.executeRequest(geofenceCreateRequest)
}
/// - returns: The list of all the fences
public func queryAllGeofences() -> [PIGeofence] {
let moc = self.dataController.mainContext
let fetchRequest = PIGeofence.fetchRequest
do {
guard let geofences = try moc.executeFetchRequest(fetchRequest) as? [PIGeofence] else {
DDLogError("Programming Error")
assertionFailure("Programming error")
return []
}
return geofences
} catch {
DDLogError("Core Data Error \(error)")
assertionFailure("Core Data Error \(error)")
return []
}
}
/// - parameter code: the code of the fence we are asking for
///
/// - returns: the geofence with the given code or nil if not found
public func queryGeofence(code:String) -> PIGeofence? {
let moc = self.dataController.mainContext
let fetchRequest = PIGeofence.fetchRequest
fetchRequest.predicate = NSPredicate(format: "code = %@", code)
do {
guard let geofences = try moc.executeFetchRequest(fetchRequest) as? [PIGeofence] else {
DDLogError("Programming Error",asynchronous:false)
assertionFailure("Programming error")
return nil
}
guard let geofence = geofences.first else {
return nil
}
return geofence
} catch {
DDLogError("Core Data Error \(error)")
assertionFailure("Core Data Error \(error)")
return nil
}
}
/**
- returns: `true` indicates that this is the first time this `GeofencingManager`is used
*/
public var firstTime:Bool {
return !dataController.isStorePresent
}
}
| epl-1.0 | bee2e03a924f2c453b3c1fb5ffc7ceb6 | 38.035955 | 165 | 0.623453 | 5.196231 | false | false | false | false |
abecker3/SeniorDesignGroup7 | ProvidenceWayfinding/ProvidenceWayfinding/DirectoryInformation.swift | 1 | 10994 | //
// DirectoryInformation.swift
// ProvidenceWayfinding
//
// Created by Ruth Manthey on 1/25/16.
// Copyright © 2016 GU. All rights reserved.
//
import Foundation
struct Directory
{
var name: String
var category: String
var floor: String
var hours: String
var ext: String //phone extension, named ext because extension is a keyword
var notes: String //any additional notes about each location, especially about entering restricted areas
}
/*let directory = [
Directory(name: "Adolescent Medicine", category: "Children's Hospital", floor: "L1 East", hours: "8AM to 5PM Mon-Fri", ext: 45445, notes: ""),
Directory(name: "Adult/Geriatric Psychiatry Unit East", category: "Children's Hospital", floor: "Main", hours: "", ext: 44784, notes: "Use phone to call reception"),
Directory(name: "Adult/Geriatric Psychiatry Unit West", category: "Children's Hospital", floor: "Main", hours: "", ext: 44863, notes: "Use phone to call reception"),
Directory(name: "Antepartum", category: "Women's Health Center", floor: "2 West", hours: "24-hour service", ext: 46470, notes: ""),
Directory(name: "BEST", category: "Children's Hospital", floor: "2", hours: "8:30AM to 4:30PM Mon-Fri", ext: 0, notes: ""),
Directory(name: "Birth Place", category: "Women's Health Center", floor: "2", hours: "24-hour service", ext: 46400, notes: ""),
Directory(name: "Cafeteria", category: "Main Tower", floor: "L3", hours: "6:30AM to 7PM", ext: 0, notes: ""),
Directory(name: "CARA", category: "Heart Institute", floor: "5", hours: "", ext: 0, notes: ""),
Directory(name: "Cardiac (6N)", category: "Main Tower", floor: "6", hours: "", ext: 44852, notes: ""),
Directory(name: "Cardiac (6S)", category: "Main Tower", floor: "6", hours: "", ext: 44850, notes: ""),
Directory(name: "Cardiac (8N)", category: "Main Tower", floor: "6", hours: "", ext: 44660, notes: ""),
Directory(name: "Cardiac (9N)", category: "Main Tower", floor: "6", hours: "", ext: 45400, notes: ""),
Directory(name: "Cardiac Intensive Care Unit", category: "Main Tower", floor: "2", hours: "", ext: 44610, notes: ""),
Directory(name: "Careshop", category: "Women's Health Center", floor: "Main West", hours: "9AM to 5PM Mon-Fri, 11AM to 3PM Sat", ext: 44040, notes: ""),
Directory(name: "Center of Gynecology/Robotics/Minimally Invasive Surgery", category: "Women's Health Center", floor: "Main West", hours: "8AM - 5PM Mon-Fri", ext: 47370, notes: ""),
Directory(name: "Child Life Specialists/Family Support Services", category: "Children's Hospital", floor: "4 East", hours: "", ext: 43049, notes: ""),
Directory(name: "Children's Hospital Administration", category: "Children's Hospital", floor: "4 East", hours: "", ext: 42800, notes: ""),
Directory(name: "Developmental Pediatrics", category: "Children's Hospital", floor: "4 East", hours: "8AM to 5PM Mon-Fri", ext: 42730, notes: ""),
Directory(name: "Doctors Building Information", category: "Doctors Building", floor: "Main", hours: "9AM to 5PM", ext: 44775, notes: ""),
Directory(name: "Emergency Department", category: "Main Tower", floor: "L1", hours: "24-hour service", ext: 43344, notes: ""),
Directory(name: "Gift Shop", category: "Main Tower", floor: "Main", hours: "9:30AM to 5:30PM Mon-Thurs, 7AM to7:30PM Fri, 10:30AM to 5PM Sat-Sun", ext: 43285, notes: ""),
Directory(name: "ICU Information", category: "Main Tower", floor: "2", hours: "", ext: 43310, notes: "No visitors under 18"),
Directory(name: "Labor & Delivery", category: "Women's Health Center", floor: "2", hours: "24-hour service", ext: 46460, notes: ""),
Directory(name: "Main Entrance Information", category: "Main Tower", floor: "Main", hours: "", ext: 43227, notes: ""),
Directory(name: "Main Floor Back Entrance Information", category: "Main Tower", floor: "1", hours: "", ext: 43226, notes: ""),
Directory(name: "Maternal-Fetal Medicine", category: "Women's Health Center", floor: "Main", hours: "8AM to 8PM Mon-Fri, 9AM to 6PM Sat-Sun", ext: 44060, notes: ""),
Directory(name: "Maternity Clinic", category: "Women's Health Center", floor: "Main", hours: "8:30AM to 5PM Mon-Thurs, 8:30AM to 12:30PM Fri", ext: 43170, notes: ""),
Directory(name: "Mother-Baby Unit", category: "Women's Health Center", floor: "2 East", hours: "6AM to 10PM", ext: 42400, notes: ""),
Directory(name: "Neonatal Intensive Care Unit", category: "Women's Health Center", floor: "3", hours: "24-hour service", ext: 46300, notes: "No visitors under 18"),
Directory(name: "Neurology", category: "Main Tower", floor: "8", hours: "8AM to 5PM Mon-Fri", ext: 44644, notes: ""),
Directory(name: "Northwest Heart and Lung", category: "Heart Institute", floor: "Main", hours: "8:30AM to 5PM Mon-Fri", ext: 4560262, notes: ""),
Directory(name: "Oncology", category: "Main Tower", floor: "7", hours: "", ext: 44940, notes: ""),
Directory(name: "Ortho/Bone and Joint", category: "Main Tower", floor: "4", hours: "9AM to 5PM", ext: 44684, notes: ""),
Directory(name: "PCCA", category: "Children's Hospital", floor: "2", hours: "", ext: 43213, notes: ""),
Directory(name: "Pediatrics", category: "Main Tower", floor: "3", hours: "", ext: 0, notes: ""),
Directory(name: "Pediatric Emergency", category: "Main Tower", floor: "L1", hours: "24-hour service", ext: 45690, notes: ""),
Directory(name: "Pediatric Endocrinology", category: "Children's Hospital", floor: "L1", hours: "8AM to 5PM Mon-Fri", ext: 42880, notes: ""),
Directory(name: "Pediatric Gastroenterology", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: 45437, notes: ""),
Directory(name: "Pediatric Intensive Care Unit", category: "Main Tower", floor: "3", hours: "24-hour service", ext: 45233, notes: "Use camera and button to check in"),
Directory(name: "Pediatric Nephrology", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: 3400930, notes: ""),
Directory(name: "Pediatric Neurology", category: "Children's Hospital", floor: "4 East", hours: "8AM to 5PM Mon-Fri", ext: 45440, notes: ""),
Directory(name: "Pediatric Oncology Inpatient", category: "Children's Hospital", floor: "3 East", hours: "", ext: 42700, notes: ""),
Directory(name: "Pediatric Oncology Outpatient", category: "Children's Hospital", floor: "3 East", hours: "8AM to 5PM Mon-Fri", ext: 42777, notes: ""),
Directory(name: "Pediatric Pulmonology", category: "Doctors Building", floor: "4", hours: "8AM to 5PM Mon-Fri", ext: 46960, notes: ""),
Directory(name: "Pediatric Surgeons", category: "Children's Hospital", floor: "L1", hours: "", ext: 45445, notes: ""),
Directory(name: "Pediatric Surgery Center", category: "Main Tower", floor: "L1", hours: "8AM to 5PM Mon-Fri", ext: 43112, notes: ""),
Directory(name: "Postpartum", category: "Women's Health Center", floor: "2", hours: "24-hour service", ext: 46480, notes: ""),
Directory(name: "Pre-admission Clinic", category: "Women's Health Center", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: 0, notes: ""),
Directory(name: "Providence Center for Congenital Heart Disease", category: "Children's Hospital", floor: "4 East", hours: "8AM to 5PM Mon-Fri", ext: 46707, notes: ""),
Directory(name: "Providence Center for Faith and Healing", category: "Faith and Healing", floor: "Main", hours: "", ext: 43008, notes: ""),
Directory(name: "Spokane Cardiology", category: "Heart Institute", floor: "4", hours: "8:30AM to 5PM Mon-Fri", ext: 4558820, notes: ""),
Directory(name: "Surgery", category: "Women's Health Center", floor: "Main", hours: "", ext: 44686, notes: ""),
Directory(name: "Thomas Hammer Coffee (Cafeteria)", category: "Main Tower", floor: "L3", hours: "", ext: 44809, notes: ""),
Directory(name: "Thomas Hammer Coffee (Emergency)", category: "Main Tower", floor: "L1", hours: "", ext: 45839, notes: ""),
Directory(name: "Thomas Hammer Coffee (Women's Building)", category: "Women's Health Center", floor: "Main", hours: "", ext: 43999, notes: ""),
Directory(name: "Transplant", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: 0, notes: ""),
Directory(name: "Valet Parking", category: "Women's Health Center", floor: "L2", hours: "24-hour service", ext: 0, notes: ""),
Directory(name: "Women's Health Center", category: "Women's Health Center", floor: "L2", hours: "", ext: 42400, notes: ""),
]*/
var directory = [Directory]();
func loadDirectory()
{
print("Entered Load")
let fileVertices = NSBundle.mainBundle().pathForResource("data/vertices", ofType: "csv")!
print(fileVertices)
let error: NSErrorPointer = nil
let tableVertices = CSV(contentsOfFile: fileVertices, error: error);
//Vertices
for row in tableVertices!.rows
{
let id = row["ID"]!;
let name = row["Name"]!;
let x = row["X"]!;
let y = row["Y"]!;
let building = row["Building"]!;
let floor = row["Floor"]!;
let category = row["Category"]!;
let hours = row["Hours"]!;
let ext = row["Ext"]!;
let notes = row["Notes"]!;
if(category != "")
{
directory.append(Directory(name: String(name), category: String(category), floor: String(floor), hours: String(hours), ext: String(ext), notes: String(notes)))
}
}
print(directory.count)
loadAdditional();
}
func loadAdditional()
{
directory.append(Directory(name: "Doctors Building Information", category: "Doctors Building", floor: "Main", hours: "9AM to 5PM", ext: "5094744775", notes: ""))
directory.append(Directory(name: "Pediatric Gastroenterology", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: "5094745437", notes: ""))
directory.append(Directory(name: "Pediatric Nephrology", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: "5093400930", notes: ""))
directory.append(Directory(name: "Pediatric Pulmonology", category: "Doctors Building", floor: "4", hours: "8AM to 5PM Mon-Fri", ext: "5094746960", notes: ""))
directory.append(Directory(name: "Transplant", category: "Doctors Building", floor: "Main", hours: "8AM to 5PM Mon-Fri", ext: "", notes: ""))
}
var directoryEntry: Directory!
var parkingEntry: Directory!
var parkingHistEntry: Directory!
var routeFromWhichScreen = 0
var flagForPlace = 0
var resetToRootView = 0
func prepParking(){
var building = [String()]
var floor = [String()]
let defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("buildingArray") != nil){
building = defaults.objectForKey("buildingArray")! as! NSArray as! [String]
floor = defaults.objectForKey("floorArray")! as! NSArray as! [String]
}
parkingEntry = Directory(name: building[0] + " Parking " + floor[0], category: "Parking", floor: floor[0], hours: "NA", ext: "", notes: "")
} | apache-2.0 | 15ec25306b86f664575c4a7efd80749d | 74.82069 | 186 | 0.657054 | 3.366922 | false | false | false | false |
yuhao-ios/DouYuTVForSwift | DouYuTVForSwift/DouYuTVForSwift/Main/Controller/BaseViewController.swift | 1 | 1634 | //
// BaseViewController.swift
// DouYuTVForSwift
//
// Created by t4 on 17/5/24.
// Copyright © 2017年 t4. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
//MARK: - 懒加载属性
lazy var annimaImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "img_loading_1")!,UIImage(named: "img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin]
return imageView
}()
var contentView : UIView?
//MARK: - 系统回调
override func viewDidLoad() {
super.viewDidLoad()
loadUI()
}
}
extension BaseViewController {
//布局
func loadUI(){
//1.隐藏内容视图
contentView?.isHidden = true
//2.添加执行动画的UIImageView
view.addSubview(annimaImageView)
//3.执行动画
annimaImageView.startAnimating()
// 4.设置view的背景颜色
view.backgroundColor = UIColor(r: 250, g: 250, b: 250, alpha: 1.0)
}
func showContentView(){
//0.隐藏动画视图
annimaImageView.isHidden = true
//1. 显示内容视图
contentView?.isHidden = false
//2.停止动画
annimaImageView.stopAnimating()
}
}
| mit | b5993725afd637edf53c9d85b1202419 | 20.236111 | 103 | 0.577502 | 4.537092 | false | false | false | false |
trill-lang/ClangSwift | Sources/Clang/Token.swift | 1 | 6290 | #if SWIFT_PACKAGE
import cclang
#endif
import Foundation
/// Represents a C, C++, or Objective-C token.
public protocol Token {
var clang: CXToken { get }
}
extension Token {
/// Determine the spelling of the given token.
/// The spelling of a token is the textual representation of that token,
/// e.g., the text of an identifier or keyword.
public func spelling(in translationUnit: TranslationUnit) -> String {
return clang_getTokenSpelling(translationUnit.clang, clang).asSwift()
}
/// Retrieve the source location of the given token.
/// - param translationUnit: The translation unit in which you're looking
/// for this token.
public func location(in translationUnit: TranslationUnit) -> SourceLocation {
return SourceLocation(clang: clang_getTokenLocation(translationUnit.clang,
clang))
}
/// Retrieve a source range that covers the given token.
/// - param translationUnit: The translation unit in which you're looking
/// for this token.
public func range(in translationUnit: TranslationUnit) -> SourceRange {
return SourceRange(clang: clang_getTokenExtent(translationUnit.clang,
clang))
}
/// Returns the underlying CXToken value.
public func asClang() -> CXToken {
return self.clang
}
}
/// A token that contains some kind of punctuation.
public struct PunctuationToken: Token {
public let clang: CXToken
}
/// A language keyword.
public struct KeywordToken: Token {
public let clang: CXToken
}
/// An identifier (that is not a keyword).
public struct IdentifierToken: Token {
public let clang: CXToken
}
/// A numeric, string, or character literal.
public struct LiteralToken: Token {
public let clang: CXToken
}
/// A comment.
public struct CommentToken: Token {
public let clang: CXToken
}
/// Converts a CXToken to a Token, returning `nil` if it was unsuccessful
func convertToken(_ clang: CXToken) -> Token {
switch clang_getTokenKind(clang) {
case CXToken_Punctuation: return PunctuationToken(clang: clang)
case CXToken_Keyword: return KeywordToken(clang: clang)
case CXToken_Identifier: return IdentifierToken(clang: clang)
case CXToken_Literal: return LiteralToken(clang: clang)
case CXToken_Comment: return CommentToken(clang: clang)
default: fatalError("invalid CXTokenKind \(clang)")
}
}
public struct SourceLocation {
let clang: CXSourceLocation
/// Creates a SourceLocation.
/// - parameter clang: A CXSourceLocation.
init(clang: CXSourceLocation) {
self.clang = clang
}
/// Creates a source location associated with a given file/line/column
/// in a particular translation unit
/// - parameters:
/// - translationUnit: The translation unit associated with the location
/// to extract.
/// - file: Source file.
/// - line: The line number in the source file.
/// - column: The column number in the source file.
public init(translationUnit: TranslationUnit,
file: File, line: Int, column: Int) {
self.clang = clang_getLocation(
translationUnit.clang, file.clang, UInt32(line), UInt32(column))
}
/// Creates a source location associated with a given character offset
/// in a particular translation unit
/// - parameters:
/// - translationUnit: The translation unit associated with the location
/// to extract.
/// - file: Source file.
/// - offset: character offset in the source file.
public init(translationUnit: TranslationUnit, file: File, offset: Int) {
self.clang = clang_getLocationForOffset(
translationUnit.clang, file.clang, UInt32(offset))
}
/// Retrieves all file, line, column, and offset attributes of the provided
/// source location.
internal var locations: (file: File, line: Int, column: Int, offset: Int) {
var l = 0 as UInt32
var c = 0 as UInt32
var o = 0 as UInt32
var f: CXFile?
clang_getFileLocation(clang, &f, &l, &c, &o)
return (file: File(clang: f!), line: Int(l), column: Int(c),
offset: Int(o))
}
public func cursor(in translationUnit: TranslationUnit) -> Cursor? {
return clang_getCursor(translationUnit.clang, clang)
}
/// The line to which the given source location points.
public var line: Int {
return locations.line
}
/// The column to which the given source location points.
public var column: Int {
return locations.column
}
/// The offset into the buffer to which the given source location points.
public var offset: Int {
return locations.offset
}
/// The file to which the given source location points.
public var file: File {
return locations.file
}
/// Returns if the given source location is in the main file of
/// the corresponding translation unit.
public var isFromMainFile: Bool {
return clang_Location_isFromMainFile(self.clang) != 0
}
/// Returns the underlying CXSourceLocation value.
public func asClang() -> CXSourceLocation {
return self.clang
}
}
/// Represents a half-open character range in the source code.
public struct SourceRange {
let clang: CXSourceRange
/// Creates a SourceRange.
/// - clang: A CXSourceRange.
init(clang: CXSourceRange) {
self.clang = clang
}
/// Creates a range from two locations.
/// - parameters:
/// - start: Location of the start of the range.
/// - end: Location of the end of the range.
/// - note: The range is half opened [start..<end]. That means that the end
/// location is not included.
public init(start: SourceLocation, end: SourceLocation) {
self.clang = clang_getRange(start.clang, end.clang)
}
/// Retrieve a source location representing the first character within a
/// source range.
public var start: SourceLocation {
return SourceLocation(clang: clang_getRangeStart(clang))
}
/// Retrieve a source location representing the last character within a
/// source range.
public var end: SourceLocation {
return SourceLocation(clang: clang_getRangeEnd(clang))
}
/// Returns the underlying CXSourceRange value.
public func asClang() -> CXSourceRange {
return self.clang
}
}
| mit | 1b325a34b1fa134fd36571f46748ebf2 | 30.60804 | 79 | 0.681081 | 4.284741 | false | false | false | false |
chschroeda/BlennyTV | BlennyTV/OverlayViewController.swift | 1 | 1166 | //
// OverlayViewController.swift
// BlennyTV
//
// Created by Christian Schroeder on 21.06.17.
// Copyright © 2017 Christian Schroeder. All rights reserved.
//
import Cocoa
import Foundation
class OverlayViewController: NSViewController {
@IBOutlet weak var channelLabel: NSTextField!
var channelLabelText: NSMutableAttributedString? = nil
override func viewDidLoad() {
super.viewDidLoad()
channelLabel.alphaValue = 0
NSAnimationContext.current().duration = 0
if let cltext = channelLabelText {
channelLabel.attributedStringValue = cltext
} else {
channelLabel.attributedStringValue = NSMutableAttributedString(string: "", attributes: [NSFontAttributeName:NSFont(name: "Helvetica-Bold",size: 64)!])
}
channelLabel.sizeToFit()
channelLabel.alphaValue = 0.8
NSAnimationContext.current().duration = 0
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 4.0
channelLabel.animator().alphaValue = 0
}, completionHandler: {
})
}
}
| mit | 14ba91bbaa5ccb4716031cceee0cf989 | 28.125 | 162 | 0.644635 | 5.154867 | false | false | false | false |
dvaughn1712/perfect-routing | PerfectLib/RWLockCache.swift | 2 | 4617 | //
// RWLockCache.swift
// PerfectLib
//
// Created by Kyle Jessup on 2015-12-01.
// Copyright © 2015 PerfectlySoft. All rights reserved.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Foundation
/*
NOTE: This class uses GCD and as such does not yet operate on Linux.
It is not included in the project for OS X but is left in the source directory for future consideration.
*/
/// This class implements a multi-reader single-writer thread-safe dictionary.
/// It provides a means for:
/// 1. Fetching a value given a key, with concurrent readers
/// 2. Setting the value for a key with one writer while all readers block
/// 3. Fetching a value for a key with a callback, which, if the key does NOT exist, will be called to generate the new value in a thread-safe manner.
/// 4. Fetching a value for a key with a callback, which, if the key DOES exist, will be called to validate the value. If the value does nto validate then it will be removed from the dictionary in a thread-safe manner.
/// 5. Iterating all key/value pairs in a thread-safe manner while the write lock is held.
/// 6. Retrieving all keys while the read lock is held.
/// 7. Executing arbitrary blocks while either the read or write lock is held.
///
/// Note that if the validator callback indicates that the value is not valid, it will be called a second time while the write lock is held to ensure that the value has not been re-validated by another thread.
public class RWLockCache<KeyT: Hashable, ValueT> {
public typealias KeyType = KeyT
public typealias ValueType = ValueT
public typealias ValueGenerator = () -> ValueType?
public typealias ValueValidator = (value: ValueType) -> Bool
private let queue = dispatch_queue_create("RWLockCache", DISPATCH_QUEUE_CONCURRENT)
private var cache = [KeyType : ValueType]()
public func valueForKey(key: KeyType) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
return value
}
public func valueForKey(key: KeyType, missCallback: ValueGenerator, validatorCallback: ValueValidator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value == nil {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value == nil {
value = missCallback()
if value != nil {
self.cache[key] = value
}
}
}
} else if !validatorCallback(value: value!) {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value != nil && !validatorCallback(value: value!) {
self.cache.removeValueForKey(key)
value = nil
}
}
}
return value
}
public func valueForKey(key: KeyType, validatorCallback: ValueValidator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value != nil && !validatorCallback(value: value!) {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value != nil && !validatorCallback(value: value!) {
self.cache.removeValueForKey(key)
value = nil
}
}
}
return value
}
public func valueForKey(key: KeyType, missCallback: ValueGenerator) -> ValueType? {
var value: ValueType?
dispatch_sync(self.queue) {
value = self.cache[key]
}
if value == nil {
dispatch_barrier_sync(self.queue) {
value = self.cache[key]
if value == nil {
value = missCallback()
if value != nil {
self.cache[key] = value
}
}
}
}
return value
}
public func setValueForKey(key: KeyType, value: ValueType) {
dispatch_barrier_async(self.queue) {
self.cache[key] = value
}
}
public func keys() -> [KeyType] {
var keys = [KeyType]()
dispatch_sync(self.queue) {
for key in self.cache.keys {
keys.append(key)
}
}
return keys
}
public func keysAndValues(callback: (KeyType, ValueType) -> ()) {
dispatch_barrier_sync(self.queue) {
for (key, value) in self.cache {
callback(key, value)
}
}
}
public func withReadLock(callback: () -> ()) {
dispatch_sync(self.queue) {
callback()
}
}
public func withWriteLock(callback: () -> ()) {
dispatch_barrier_sync(self.queue) {
callback()
}
}
}
| unlicense | f78df9288ae82bcbf421507a05d09624 | 26.313609 | 218 | 0.65338 | 3.620392 | false | false | false | false |
zixun/CocoaChinaPlus | Code/CocoaChinaPlus/Application/Business/Util/View/ZXCuteView/ZXCuteView.swift | 1 | 11264 | //
// ZXCuteView.swift
// CocoaChinaPlus
//
// Created by 子循 on 15/8/7.
// Copyright © 2015年 zixun. All rights reserved.
//
import UIKit
import RxSwift
import AppBaseKit
public class ZXCuteView: UIView {
// 父视图
public var containerView:UIView?
// 气泡上显示数字的label
public var bubbleImage:UIImageView?
//气泡的直径
public var bubbleWidth:CGFloat = 0.0
//气泡粘性系数,越大可以拉得越长
public var viscosity:CGFloat = 20.0
//气泡颜色
public var bubbleColor:UIColor = UIColor(hex:0x00B9FF) {
didSet {
self.frontView?.backgroundColor = self.bubbleColor
self.backView?.backgroundColor = self.bubbleColor
}
}
//需要隐藏气泡时候可以使用这个属性:self.frontView.hidden = YES;
public var frontView:UIView?//用户拖走的View
public var backView:UIView?//原地保留显示的View
public var tapCallBack:(()->Void)?
private var disposeBag = DisposeBag()
private var initialPoint:CGPoint!
private var shapeLayer:CAShapeLayer!
private var r1:CGFloat = 0.0 //backView的半径
private var r2:CGFloat = 0.0 //frontView的半径
private var x1:CGFloat = 0.0 //backView圆心x
private var y1:CGFloat = 0.0 //backView圆心y
private var x2:CGFloat = 0.0 //frontView圆心x
private var y2:CGFloat = 0.0 //frontView圆心y
private var centerDistance:CGFloat = 0.0
private var cosDigree:CGFloat = 0.0
private var sinDigree:CGFloat = 0.0
private var pointA:CGPoint = CGPoint.zero //A
private var pointB:CGPoint = CGPoint.zero //B
private var pointD:CGPoint = CGPoint.zero //D
private var pointC:CGPoint = CGPoint.zero //C
private var pointO:CGPoint = CGPoint.zero //O
private var pointP:CGPoint = CGPoint.zero //P
private var oldBackViewFrame:CGRect = CGRect.zero
private var oldBackViewCenter:CGPoint = CGPoint.zero
private var fillColorForCute:UIColor?
private var cutePath:UIBezierPath!
public convenience init(point:CGPoint,superView:UIView,bubbleWidth:CGFloat) {
self.init(frame:CGRect(x:point.x, y:point.y, width:bubbleWidth,height:bubbleWidth))
self.bubbleWidth = frame.size.width
self.initialPoint = point
self.containerView = superView
self.containerView!.addSubview(self)
self.setup()
}
deinit {
self.removeFromSuperview()
self.frontView?.removeFromSuperview()
self.backView?.removeFromSuperview()
self.shapeLayer.removeFromSuperlayer()
}
func setup() {
self.shapeLayer = CAShapeLayer()
self.backgroundColor = UIColor.clear
self.frontView = UIView(frame: CGRect(x:initialPoint.x,y:initialPoint.y, width:self.bubbleWidth,height: self.bubbleWidth))
//计算frontView半径
r2 = self.frontView!.bounds.size.width / 2.0
self.frontView!.layer.cornerRadius = r2
self.frontView!.backgroundColor = self.bubbleColor
self.backView = UIView(frame: self.frontView!.frame)
r1 = self.backView!.frame.size.width / 2.0
self.backView!.layer.cornerRadius = r1
self.backView!.backgroundColor = self.bubbleColor
self.bubbleImage = UIImageView()
self.bubbleImage!.frame = CGRect(x:0, y:0, width:self.frontView!.bounds.size.width, height:self.frontView!.bounds.size.height)
self.bubbleImage!.image = UIImage(named: "top")
self.frontView!.insertSubview(self.bubbleImage!, at: 0)
self.containerView!.addSubview(backView!)
self.containerView!.addSubview(self.frontView!)
x1 = self.backView!.center.x;
y1 = self.backView!.center.y;
x2 = self.frontView!.center.x;
y2 = self.frontView!.center.y;
self.pointA = CGPoint(x:x1-r1,y:y1); // A
self.pointB = CGPoint(x:x1+r1,y:y1); // B
self.pointD = CGPoint(x:x2-r2,y:y2); // D
self.pointC = CGPoint(x:x2+r2,y:y2); // C
self.pointO = CGPoint(x:x1-r1,y:y1); // O
self.pointP = CGPoint(x:x2+r2,y:y2); // P
self.oldBackViewFrame = self.backView!.frame
self.oldBackViewCenter = self.backView!.center
self.backView!.isHidden = true //为了看到frontView的气泡晃动效果,需要展示隐藏backView
self.addAniamtionLikeGameCenterBubble()
let pan = UIPanGestureRecognizer()
self.frontView!.addGestureRecognizer(pan)
pan.rx.event.bindNext { [unowned self] (ges:UIPanGestureRecognizer) in
self.dragMe(ges:ges)
}.addDisposableTo(self.disposeBag)
let tap = UITapGestureRecognizer()
self.frontView!.addGestureRecognizer(tap)
tap.rx.event.bindNext { (ges:UITapGestureRecognizer) in
self.tapMe(tap: ges)
}.addDisposableTo(self.disposeBag)
}
func tapMe(tap:UITapGestureRecognizer) {
guard self.tapCallBack != nil else {
return
}
self.tapCallBack!()
}
func dragMe(ges:UIPanGestureRecognizer) {
let dragPoint = ges.location(in: self.containerView)
if ges.state == .began {
self.backView?.isHidden = false
self.fillColorForCute = self.bubbleColor
self.removeAniamtionLikeGameCenterBubble()
}else if(ges.state == .changed) {
self.frontView?.center = dragPoint
if r1 <= 6 {
self.fillColorForCute = UIColor.clear
self.backView?.isHidden = true
self.shapeLayer.removeFromSuperlayer()
}
}else if (ges.state == .ended || ges.state == .cancelled || ges.state == .failed) {
self.backView?.isHidden = true
self.fillColorForCute = UIColor.clear
self.shapeLayer.removeFromSuperlayer()
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: { () -> Void in
self.frontView?.center = self.oldBackViewCenter
}, completion: { (finished) -> Void in
if finished == true {
self.addAniamtionLikeGameCenterBubble()
}
})
}
self.displayLinkAction()
}
private func displayLinkAction() {
x1 = self.backView!.center.x
y1 = self.backView!.center.y
x2 = self.frontView!.center.x
y2 = self.frontView!.center.y
self.centerDistance = CGFloat(sqrtf( Float( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ) ))
if centerDistance == 0 {
self.cosDigree = 1.0
self.sinDigree = 0
}else {
self.cosDigree = (y2-y1)/centerDistance;
self.sinDigree = (x2-x1)/centerDistance;
}
r1 = self.oldBackViewFrame.size.width / 2 - centerDistance/self.viscosity
pointA = CGPoint(x:x1-r1*cosDigree, y:y1+r1*sinDigree); // A
pointB = CGPoint(x:x1+r1*cosDigree, y:y1-r1*sinDigree); // B
pointD = CGPoint(x:x2-r2*cosDigree, y:y2+r2*sinDigree); // D
pointC = CGPoint(x:x2+r2*cosDigree, y:y2-r2*sinDigree);// C
pointO = CGPoint(x:pointA.x + (centerDistance / 2)*sinDigree, y:pointA.y + (centerDistance / 2)*cosDigree);
pointP = CGPoint(x:pointB.x + (centerDistance / 2)*sinDigree, y:pointB.y + (centerDistance / 2)*cosDigree);
self.drawRect()
}
func drawRect() {
self.backView!.center = oldBackViewCenter;
self.backView!.bounds = CGRect(x:0, y:0, width:r1*2, height:r1*2);
self.backView!.layer.cornerRadius = r1;
self.cutePath = UIBezierPath()
self.cutePath.move(to: pointA)
self.cutePath.addQuadCurve(to: pointD, controlPoint: pointO)
self.cutePath.addLine(to: pointC)
self.cutePath.addQuadCurve(to: pointB, controlPoint: pointP)
self.cutePath.move(to: pointA)
if (self.backView!.isHidden == false) {
self.shapeLayer.path = cutePath.cgPath
self.shapeLayer.fillColor = fillColorForCute?.cgColor
self.containerView?.layer.insertSublayer(shapeLayer, below: self.frontView?.layer)
}
}
public func addAniamtionLikeGameCenterBubble() {
self.addPositionAnimation()
self.addScaleAnimation()
}
public func removeAniamtionLikeGameCenterBubble() {
self.removePositionAnimation()
self.removeScaleAnimation()
}
private func addPositionAnimation() {
let pathAnimation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position")
pathAnimation.calculationMode = kCAAnimationPaced
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.isRemovedOnCompletion = false
pathAnimation.repeatCount = Float.infinity
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
pathAnimation.duration = 5.0;
let curvedPath:CGMutablePath = CGMutablePath()
let circleContainer:CGRect = self.frontView!.frame.insetBy(dx: self.frontView!.bounds.size.width / 2 - 3, dy: self.frontView!.bounds.size.width / 2 - 3)
curvedPath.addEllipse(in: circleContainer)
pathAnimation.path = curvedPath
// CGPathRelease(curvedPath) http://stackoverflow.com/questions/24900595/swift-cgpathrelease-and-arc
self.frontView!.layer.add(pathAnimation, forKey: "myCircleAnimation")
}
private func addScaleAnimation() {
let scaleX:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale.x")
scaleX.duration = 1
scaleX.values = [1.0, 1.1, 1.0];
scaleX.keyTimes = [0.0, 0.5, 1.0];
scaleX.repeatCount = Float.infinity;
scaleX.autoreverses = true;
scaleX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.frontView!.layer.add(scaleX, forKey: "scaleXAnimation")
let scaleY:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.scale.y")
scaleY.duration = 1.5;
scaleY.values = [1.0, 1.1, 1.0];
scaleY.keyTimes = [0.0, 0.5, 1.0];
scaleY.repeatCount = Float.infinity;
scaleY.autoreverses = true;
scaleX.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.frontView!.layer.add(scaleY, forKey: "scaleYAnimation")
}
private func removeScaleAnimation() {
self.frontView?.layer.removeAnimation(forKey: "scaleXAnimation")
self.frontView?.layer.removeAnimation(forKey: "scaleYAnimation")
}
private func removePositionAnimation() {
self.frontView?.layer.removeAnimation(forKey: "myCircleAnimation")
}
}
| mit | bead7c8eaed9ac2fa87be56416b85ec2 | 35.856667 | 190 | 0.62214 | 4.127286 | false | false | false | false |
KyleGoddard/KGFloatingDrawer | Pod/Classes/KGDrawerView.swift | 2 | 12181 | //
// KGDrawerView.swift
// KGDrawerViewController
//
// Created by Kyle Goddard on 2015-02-11.
// Copyright (c) 2015 Kyle Goddard. All rights reserved.
//
import UIKit
open class KGDrawerView: UIView {
let kKGCenterViewContainerCornerRadius: CGFloat = 5.0
let kKGDefaultViewContainerWidth: CGFloat = 280.0
// MARK: Initialization
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(backgroundImageView)
self.addSubview(centerViewContainer)
self.addSubview(leftViewContainer)
self.addSubview(rightViewContainer)
self.addConstraints(backgroundViewConstraints)
self.addConstraints(centerViewConstraints)
self.addConstraints(leftViewConstraints)
self.addConstraints(rightViewConstraints)
}
override open func willMove(toSuperview newSuperview: UIView?) {
self.bringSubview(toFront: self.centerViewContainer)
}
override open func layoutSubviews() {
updateShadowPath()
}
// MARK: Background Image
fileprivate var _backgroundImageView: UIImageView?
var backgroundImageView: UIImageView {
get {
if let imageView = _backgroundImageView {
return imageView
}
let imageView = UIImageView(frame: self.frame)
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
_backgroundImageView = imageView
return imageView
}
}
fileprivate var _backgroundViewConstraints: [NSLayoutConstraint]?
fileprivate var backgroundViewConstraints: [NSLayoutConstraint] {
get {
if let constraints = _backgroundViewConstraints {
return constraints
}
let constraints = [
NSLayoutConstraint(item: self.backgroundImageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.backgroundImageView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.backgroundImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0)
]
_backgroundViewConstraints = constraints
return constraints
}
}
// MARK: Left view container
fileprivate var _leftViewContainer: UIView?
var leftViewContainer: UIView {
get {
if let container = _leftViewContainer {
return container
}
let container = UIView(frame: self.frame)
container.translatesAutoresizingMaskIntoConstraints = false
_leftViewContainer = container
return container
}
}
fileprivate var _leftViewConstraints: [NSLayoutConstraint]?
fileprivate var leftViewConstraints: [NSLayoutConstraint] {
if let constraints = _leftViewConstraints {
return constraints
}
let constraints = [
NSLayoutConstraint(item: self.leftViewContainer, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.leftViewContainer, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.leftViewContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
self.leftViewWidthConstraint
]
_leftViewConstraints = constraints
return constraints
}
fileprivate var _leftViewWidthConstraint: NSLayoutConstraint?
fileprivate var leftViewWidthConstraint: NSLayoutConstraint {
get {
if let retVal = _leftViewWidthConstraint {
return retVal
}
let retVal = NSLayoutConstraint(item: self.leftViewContainer, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: self.kKGDefaultViewContainerWidth)
_leftViewWidthConstraint = retVal
return retVal
}
}
// MARK: Right view container
fileprivate var _rightViewContainer: UIView?
var rightViewContainer: UIView {
get {
if let retVal = _rightViewContainer {
return retVal
}
let retVal = UIView(frame: self.frame)
retVal.translatesAutoresizingMaskIntoConstraints = false
_rightViewContainer = retVal
return retVal
}
}
fileprivate var _rightViewConstraints: [NSLayoutConstraint]?
fileprivate var rightViewConstraints: [NSLayoutConstraint] {
get {
if let constraints = _rightViewConstraints {
return constraints
}
let constraints = [
NSLayoutConstraint(item: self.rightViewContainer, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.rightViewContainer, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.rightViewContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
self.rightViewWidthConstraint
]
_rightViewConstraints = constraints
return constraints
}
}
fileprivate var _rightViewWidthConstraint: NSLayoutConstraint?
fileprivate var rightViewWidthConstraint: NSLayoutConstraint {
get {
if let constraint = _rightViewWidthConstraint {
return constraint
}
let constraint = NSLayoutConstraint(item: self.rightViewContainer, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: self.kKGDefaultViewContainerWidth)
_rightViewWidthConstraint = constraint
return constraint
}
}
// MARK: Center view container
fileprivate var _centerViewContainer: UIView?
var centerViewContainer: UIView {
get {
if let container = _centerViewContainer {
return container
}
let container = UIView(frame: self.frame)
container.translatesAutoresizingMaskIntoConstraints = false
_centerViewContainer = container
return container
}
}
fileprivate var _centerViewConstraints: [NSLayoutConstraint]?
fileprivate var centerViewConstraints: [NSLayoutConstraint] {
if let constraints = _centerViewConstraints {
return constraints
}
let constraints = [
NSLayoutConstraint(item: self.centerViewContainer, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.centerViewContainer, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.centerViewContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: self.centerViewContainer, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0)
]
_centerViewConstraints = constraints
return constraints
}
// MARK: Reveal Widths
var leftViewContainerWidth: CGFloat {
get {
return self.leftViewWidthConstraint.constant
}
set {
self.leftViewWidthConstraint.constant = newValue
}
}
var rightViewContainerWidth: CGFloat {
get {
return self.rightViewWidthConstraint.constant
}
set {
self.rightViewWidthConstraint.constant = newValue
}
}
// TODO: Make the various properties here configurable by the user.
fileprivate var _shouldRadiusCenterViewController: Bool = false
var shouldRadiusCenterViewController: Bool {
get {
return _shouldRadiusCenterViewController
}
set {
if let view = self.centerViewContainer.subviews.first {
if (newValue) {
view.layer.borderColor = UIColor(white: 1.0, alpha: 0.15).cgColor
view.layer.borderWidth = 1.0
view.layer.masksToBounds = true
view.layer.cornerRadius = kKGCenterViewContainerCornerRadius
} else {
view.layer.borderColor = UIColor.clear.cgColor
view.layer.borderWidth = 0.0
view.layer.masksToBounds = false
view.layer.cornerRadius = 0.0
}
}
_shouldRadiusCenterViewController = newValue
}
}
// TODO: Make the various properties here configurable by the user.
fileprivate var _shouldShadowCenterViewContainer: Bool?
var shouldShadowCenterViewContainer: Bool {
get {
if let retVal = _shouldShadowCenterViewContainer {
return retVal
}
_shouldShadowCenterViewContainer = false
return false
}
set {
let layer = self.centerViewContainer.layer
if (newValue) {
layer.shadowRadius = 20.0
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.4
layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
layer.masksToBounds = false
self.updateShadowPath()
} else {
layer.shadowRadius = 0.0
layer.shadowColor = UIColor.clear.cgColor
layer.shadowOpacity = 0.0
layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
layer.masksToBounds = true
}
_shouldShadowCenterViewContainer = newValue
}
}
// MARK: Helpers
func updateShadowPath() {
let layer = self.centerViewContainer.layer
let increase = layer.shadowRadius
var rect = self.centerViewContainer.bounds
rect.origin.x -= increase
rect.origin.y -= increase
rect.size.width += increase * 2.0
rect.size.height += increase * 2.0
layer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: kKGCenterViewContainerCornerRadius).cgPath
}
func viewContainerForDrawerSide(_ drawerSide: KGDrawerSide) -> UIView? {
var viewContainer: UIView?
switch drawerSide {
case .left:
viewContainer = self.leftViewContainer
case .right:
viewContainer = self.rightViewContainer
case .none:
viewContainer = nil
}
return viewContainer
}
// MARK: Event Handling
func willOpenDrawer(_ viewController: KGDrawerViewController) {
self.shouldRadiusCenterViewController = true
self.shouldShadowCenterViewContainer = true
}
func willCloseDrawer(_ viewController: KGDrawerViewController) {
self.shouldRadiusCenterViewController = false
self.shouldShadowCenterViewContainer = false
}
}
| mit | 8fa69b20a4a14eb97a8d66c0daefc781 | 39.069079 | 220 | 0.620228 | 5.387439 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Helpers/TextTransform/TransformLabel.swift | 1 | 1652 | //
// 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 UIKit
/**
* A label that can automatically transform the text it presents.
*/
final class TransformLabel: UILabel {
override var accessibilityValue: String? {
get {
return attributedText?.string ?? text
}
set {
super.accessibilityValue = newValue
}
}
/// The transform to apply to the text.
var textTransform: TextTransform = .none {
didSet {
attributedText = attributedText?.applying(transform: textTransform)
}
}
override var text: String? {
get {
return super.text
}
set {
super.text = newValue?.applying(transform: textTransform)
}
}
override var attributedText: NSAttributedString? {
get {
return super.attributedText
}
set {
super.attributedText = newValue?.applying(transform: textTransform)
}
}
}
| gpl-3.0 | e119bb53993bc08d97a3a8841e9451b8 | 25.645161 | 79 | 0.640436 | 4.72 | false | false | false | false |
zendobk/SwiftUtils | Sources/Extensions/Int.swift | 1 | 1694 | //
// Int.swift
// SwiftUtils
//
// Created by DaoNV on 10/7/15.
// Copyright © 2016 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
extension Int {
public func loop(_ block: () -> Void) {
for _ in 0 ..< self {
block()
}
}
public var isEven: Bool {
return (self % 2) == 0
}
public var isOdd: Bool {
return (self % 2) == 1
}
public func clamp(_ range: Range<Int>) -> Int {
return clamp(range.lowerBound, range.upperBound - 1)
}
public func clamp(_ min: Int, _ max: Int) -> Int {
return Swift.max(min, Swift.min(max, self))
}
public var digits: [Int] {
var result = [Int]()
for char in String(self) {
let string = String(char)
if let toInt = Int(string) {
result.append(toInt)
}
}
return result
}
public var abs: Int {
return Swift.abs(self)
}
public func gcd(_ num: Int) -> Int {
return num == 0 ? self : num.gcd(self % num)
}
public func lcm(_ num: Int) -> Int {
return (self * num).abs / gcd(num)
}
public var factorial: Int {
return self == 0 ? 1 : self * (self - 1).factorial
}
public var ordinal: String {
let suffix: [String] = ["th", "st", "nd", "rd", "th"]
var index = 0
if self < 11 || self > 13 {
index = Swift.min(suffix.count - 1, self % 10)
}
return String(format: "%zd%@", self, suffix[index])
}
public static func random(min: Int = 0, max: Int) -> Int {
return Int(arc4random_uniform(UInt32((max - min) + 1))) + min
}
}
| apache-2.0 | 4ad0696ceea579776b00288f352fcad8 | 22.191781 | 69 | 0.501477 | 3.625268 | false | false | false | false |
StefanKruger/WiLibrary | Pod/Classes/ImageLoader/Core/ImageManagerExtensions.swift | 2 | 1297 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
// MARK: - ImageManager (Convenience)
public extension ImageManager {
func taskWithURL(URL: NSURL, completion: ImageTaskCompletion? = nil) -> ImageTask {
return self.taskWithRequest(ImageRequest(URL: URL), completion: completion)
}
func taskWithRequest(request: ImageRequest, completion: ImageTaskCompletion?) -> ImageTask {
let task = self.taskWithRequest(request)
if completion != nil { task.completion(completion!) }
return task
}
}
// MARK: - ImageManager (Shared)
public extension ImageManager {
private static var sharedManagerIvar: ImageManager = ImageManager(configuration: ImageManagerConfiguration(dataLoader: ImageDataLoader()))
private static var lock = OS_SPINLOCK_INIT
private static var token: dispatch_once_t = 0
public class var shared: ImageManager {
set {
OSSpinLockLock(&lock)
sharedManagerIvar = newValue
OSSpinLockUnlock(&lock)
}
get {
var manager: ImageManager
OSSpinLockLock(&lock)
manager = sharedManagerIvar
OSSpinLockUnlock(&lock)
return manager
}
}
}
| mit | 3842c5efae3bbebc82f6619fdbc88a2c | 29.880952 | 142 | 0.656901 | 5.066406 | false | false | false | false |
tomokitakahashi/ParallaxPagingViewController | ParallaxPagingViewController/Sources/ParallaxView.swift | 1 | 1462 | //
// ParallaxView.swift
// ParallaxPagingViewController
//
// Created by takahashi tomoki on 2017/07/06.
// Copyright © 2017年 TomokiTakahashi. All rights reserved.
//
import UIKit
@IBDesignable
open class ParallaxView: UIView {
open let backgroundImageView = UIImageView()
@IBInspectable
open var parallaxImage: UIImage? {
didSet {
backgroundImageView.image = parallaxImage
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
open override func layoutSubviews() {
super.layoutSubviews()
backgroundImageView.frame = bounds
}
fileprivate func initialize() {
clipsToBounds = true
autoresizingMask = [.flexibleWidth,.flexibleHeight]
backgroundImageView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
addSubview(backgroundImageView)
}
internal func parallaxAnimate(_ space: CGFloat, rate: CGFloat, position: PagePosition) {
let originX: CGFloat
switch position {
case .after:
originX = -space*rate - space
case .before:
originX = -space*rate + space
case .current:
originX = -space*rate
}
backgroundImageView.frame.origin.x = originX
}
}
| mit | 2d329ddd0e2675bbade69822c8c5584a | 24.155172 | 92 | 0.620288 | 5.013746 | false | false | false | false |
LongPF/FaceTube | FaceTube/Tool/Capture/FTMovieWriter.swift | 1 | 8399 | //
// FTMovieWriter.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/10.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
protocol FTMovieWriterDelegate {
func didWriteMovieAtURL(outputURL: NSURL);
}
fileprivate let FTVideoFileName: String = "movie.mov"
class FTMovieWriter: NSObject {
public var delegate: FTMovieWriterDelegate?
public private(set) var isWriting: Bool!
fileprivate var assetWriter: AVAssetWriter?
fileprivate var assetWriterVideoInput: AVAssetWriterInput?
fileprivate var assetWriterAudioInput: AVAssetWriterInput?
fileprivate var assetWriterInputPixelBufferAdaptor: AVAssetWriterInputPixelBufferAdaptor?
fileprivate var colorSpace: CGColorSpace!
fileprivate var videoSettings: [AnyHashable : Any]
fileprivate var audioSettings: [AnyHashable : Any]
fileprivate var dispatchQueue: DispatchQueue
fileprivate weak var ciContext: CIContext!
/// 生命周期内执行一次的标记
fileprivate var onceToken_lifeCycle: Bool!
fileprivate var firstSample: Bool!
init(videoSettings: [AnyHashable : Any], audioSettings: [AnyHashable : Any], dispatchQueue: DispatchQueue){
self.videoSettings = videoSettings
self.audioSettings = audioSettings
self.dispatchQueue = dispatchQueue
self.isWriting = false
self.ciContext = FTContextManager.shared.ciContext
self.colorSpace = CGColorSpaceCreateDeviceRGB()
self.onceToken_lifeCycle = true
self.firstSample = true
}
deinit {
if !onceToken_lifeCycle{
NotificationCenter.default.removeObserver(self)
}
}
//MARK: ************************ interface methods ***************
public func startWriting() {
self.dispatchQueue.async {
do {
let fileType = AVFileTypeQuickTimeMovie
try self.assetWriter = AVAssetWriter.init(outputURL: self.outputURL() as URL, fileType: fileType)
}catch let error{
print(error)
return
}
self.assetWriterVideoInput = AVAssetWriterInput.init(mediaType: AVMediaTypeVideo, outputSettings: self.videoSettings as? [String : Any])
self.assetWriterVideoInput?.expectsMediaDataInRealTime = true //是否将输入处理成RealTime
// self.assetWriterVideoInput?.transform = transformForDeviceOrientation(orientation: UIDevice.current.orientation)
self.assetWriterVideoInput?.transform = transformWithDevice(devicePosition: .front)
let attributes: [String : Any] = [
kCVPixelBufferPixelFormatTypeKey as String : kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey as String : self.videoSettings[AVVideoWidthKey]!,
kCVPixelBufferHeightKey as String : self.videoSettings[AVVideoHeightKey]!,
kCVPixelFormatOpenGLESCompatibility as String : kCFBooleanTrue
]
self.assetWriterInputPixelBufferAdaptor = AVAssetWriterInputPixelBufferAdaptor.init(assetWriterInput: self.assetWriterVideoInput!, sourcePixelBufferAttributes: attributes)
if (self.assetWriter?.canAdd(self.assetWriterVideoInput!))!{
self.assetWriter?.add(self.assetWriterVideoInput!)
}else{
print("unable to add video input.")
return
}
self.assetWriterAudioInput = AVAssetWriterInput.init(mediaType: AVMediaTypeAudio, outputSettings: self.audioSettings as? [String : Any])
self.assetWriterAudioInput?.expectsMediaDataInRealTime = true
if (self.assetWriter?.canAdd(self.assetWriterAudioInput!))!{
self.assetWriter?.add(self.assetWriterAudioInput!)
}else{
print("unable to add audio input")
}
self.isWriting = true
self.firstSample = true
}
}
public func processSampleBuffer(sampleBuffer: CMSampleBuffer){
if !self.isWriting{
return
}
let formatDesc = CMSampleBufferGetFormatDescription(sampleBuffer)
let mediaType = CMFormatDescriptionGetMediaType(formatDesc!)
if mediaType == kCMMediaType_Video {
//获取最近一次的 timestamp
let timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
if self.firstSample{
if (self.assetWriter?.startWriting())!{
self.assetWriter?.startSession(atSourceTime: timestamp)
}else{
print("failed to start writing.")
}
self.firstSample = false
}
var outputRenderBuffer: CVPixelBuffer? = nil
//buffer重用池
let pixelBufferPool: CVPixelBufferPool? = self.assetWriterInputPixelBufferAdaptor?.pixelBufferPool
let err: OSStatus = CVPixelBufferPoolCreatePixelBuffer(nil, pixelBufferPool!, &outputRenderBuffer)
if err != 0 {
print("unable to obtain a pixel buffer from the pool")
return
}
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let sourceImage = CIImage.init(cvPixelBuffer: imageBuffer!)
FTPhotoFilters.shared.selectedFilter.setValue(sourceImage, forKey: kCIInputImageKey)
var filteredImage = FTPhotoFilters.shared.selectedFilter.outputImage
if filteredImage == nil {
filteredImage = sourceImage;
}
self.ciContext.render(filteredImage!, to: outputRenderBuffer!, bounds: (filteredImage?.extent)!, colorSpace: self.colorSpace)
if (self.assetWriterVideoInput?.isReadyForMoreMediaData)!{
if !(self.assetWriterInputPixelBufferAdaptor?.append(outputRenderBuffer!, withPresentationTime: timestamp))!{
print("error appending pixel buffer.")
}
}
//swift core foundation 自动管理内存
//CVPixelBufferRelease(outputRenderBuffer)
}
else if (!self.firstSample && mediaType == kCMMediaType_Audio){
if (self.assetWriterAudioInput?.isReadyForMoreMediaData)! {
if !(self.assetWriterAudioInput?.append(sampleBuffer))! {
print("error appending audio sample buffer")
}
}
}
}
public func stopWriting() {
self.isWriting = false
self.dispatchQueue.async {
self.assetWriter?.finishWriting {
if self.assetWriter?.status == AVAssetWriterStatus.completed{
DispatchQueue.main.async {
let fileURL = self.assetWriter?.outputURL
if self.delegate != nil {
self.delegate?.didWriteMovieAtURL(outputURL: fileURL! as NSURL)
}
}
}
else{
print("fail to write movie"+(self.assetWriter?.error.debugDescription)!)
}
}
}
}
//MARK: ************************ private methods *****************
private func outputURL() -> NSURL{
let filePath = NSTemporaryDirectory().appendingFormat("/%@", FTVideoFileName)
let url = NSURL.fileURL(withPath: filePath)
if FileManager.default.fileExists(atPath: filePath) {
do{
try FileManager.default.removeItem(at: url)
}catch{}
}
return url as NSURL
}
}
| mit | 3cd8024ec715766235d33f70bf5ffdb9 | 35.968889 | 183 | 0.568286 | 6.202834 | false | false | false | false |
tuxmonteiro/tsuru | misc/git-hooks/pre-receive.swift | 7 | 2104 | #!/bin/bash -el
# This script generates a git archive from the provided commit, uploads it to
# Swift, sends the URL to Tsuru and then delete the archive in from the
# container.
#
# It depends on the "swift" command line (it can be installed with pip).
#
# It also depends on the following environment variables:
#
# - AUTH_PARAMS: the parameters used in authentication (for example:
# "-A https://yourswift.com -K yourkey -U youruser")
# - CDN_URL: the URL of the CDN that serves content from your container (for
# example: something.cf5.rackcdn.com).
# - CONTAINER_NAME: name of the container where the script will store the
# archives
# - TSURU_HOST: URL to the Tsuru API (for example: http://yourtsuru:8080)
# - TSURU_TOKEN: the token to communicate with the API (generated with
# `tsurud token`, in the server).
while read oldrev newrev refname
do
set +e
echo $refname | grep -q /master$
status=$?
set -e
if [ $status = 0 ]
then
COMMIT=${newrev}
fi
done
if [ -z ${COMMIT} ]
then
echo "ERROR: please push to master"
exit 3
fi
APP_DIR=${PWD##*/}
APP_NAME=${APP_DIR/.git/}
UUID=`python -c 'import uuid; print uuid.uuid4().hex'`
ARCHIVE_FILE_NAME=${APP_NAME}_${COMMIT}_${UUID}.tar.gz
git archive --format=tar.gz -o /tmp/$ARCHIVE_FILE_NAME $COMMIT
swift -q $AUTH_PARAMS upload $CONTAINER_NAME /tmp/$ARCHIVE_FILE_NAME --object-name $ARCHIVE_FILE_NAME
swift -q $AUTH_PARAMS post -r ".r:*" $CONTAINER_NAME
rm /tmp/$ARCHIVE_FILE_NAME
if [ -z "${CDN_URL}" ]
then
ARCHIVE_URL=`swift $AUTH_PARAMS stat -v $CONTAINER_NAME $ARCHIVE_FILE_NAME | grep URL | awk -F': ' '{print $2}'`
else
ARCHIVE_URL=${CDN_URL}/${ARCHIVE_FILE_NAME}
fi
URL="${TSURU_HOST}/apps/${APP_NAME}/deploy"
curl -H "Authorization: bearer ${TSURU_TOKEN}" -d "archive-url=${ARCHIVE_URL}&commit=${COMMIT}&user=${TSURU_USER}" -s -N $URL | tee /tmp/deploy-${APP_NAME}.log
swift -q $AUTH_PARAMS delete $CONTAINER_NAME $ARCHIVE_FILE_NAME
tail -1 /tmp/deploy-${APP_NAME}.log | grep -q "^OK$"
| bsd-3-clause | b57c058fa3094b048687732cd398558c | 36.571429 | 159 | 0.649715 | 3.121662 | false | false | false | false |
ericyanush/Plex-TVOS | Pods/Swifter/Common/DemoServer.swift | 1 | 3201 | //
// DemoServer.swift
// Swifter
// Copyright (c) 2014 Damian Kołakowski. All rights reserved.
//
import Foundation
func demoServer(publicDir: String?) -> HttpServer {
let server = HttpServer()
if let publicDir = publicDir {
server["/resources/(.+)"] = HttpHandlers.directory(publicDir)
}
server["/files(.+)"] = HttpHandlers.directoryBrowser("~/")
server["/magic"] = { .OK(.HTML("You asked for " + $0.url)) }
server["/test"] = { request in
var headersInfo = ""
for (name, value) in request.headers {
headersInfo += "\(name) : \(value)<br>"
}
var queryParamsInfo = ""
for (name, value) in request.urlParams {
queryParamsInfo += "\(name) : \(value)<br>"
}
return .OK(.HTML("<h3>Address: \(request.address)</h3><h3>Url:</h3> \(request.url)<h3>Method: \(request.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)"))
}
server["/params/(.+)/(.+)"] = { request in
var capturedGroups = ""
for (index, group) in request.capturedUrlGroups.enumerate() {
capturedGroups += "Expression group \(index) : \(group)<br>"
}
return .OK(.HTML("Url: \(request.url)<br>Method: \(request.method)<br>\(capturedGroups)"))
}
server["/json"] = { request in
return .OK(.JSON(["posts" : [[ "id" : 1, "message" : "hello world"],[ "id" : 2, "message" : "sample message"]], "new_updates" : false]))
}
server["/redirect"] = { request in
return .MovedPermanently("http://www.google.com")
}
server["/long"] = { request in
var longResponse = ""
for k in 0..<1000 { longResponse += "(\(k)),->" }
return .OK(.HTML(longResponse))
}
server["/demo"] = { request in
return .OK(.HTML("<center><h2>Hello Swift</h2>" +
"<img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br>" +
"</center>"))
}
server["/login"] = { request in
switch request.method.uppercaseString {
case "GET":
if let rootDir = publicDir {
if let html = NSData(contentsOfFile:"\(rootDir)/login.html") {
return HttpResponse.RAW(200, "OK", nil, html)
} else {
return .NotFound
}
}
break;
case "POST":
if let body = request.body {
return .OK(.HTML(body))
} else {
return .OK(.HTML("No POST params."))
}
default:
return .NotFound
}
return .NotFound
}
server["/raw"] = { request in
return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], "Sample Response".dataUsingEncoding(NSUTF8StringEncoding)!)
}
server["/"] = { request in
var listPage = "Available services:<br><ul>"
for item in server.routes() {
listPage += "<li><a href=\"\(item)\">\(item)</a></li>"
}
listPage += "</ul>"
return .OK(.HTML(listPage))
}
return server
} | mit | dae4acf6d61c83e8aea54e4b63d4bd43 | 36.658824 | 191 | 0.515938 | 4.055767 | false | false | false | false |
Joachimdj/JobResume | Apps/Forum17/2017/Forum/Views/LectureListView.swift | 1 | 12764 | //
// LectureList.swift
// Forum
//
// Created by Joachim Dittman on 13/08/2017.
// Copyright © 2017 Joachim Dittman. All rights reserved.
//
import UIKit
import FirebaseAuth
import pop
var loadedFirst = false
var loggedIn = false
var tableLoaded = false
class LectureListView: UIViewController,UITableViewDelegate,UITableViewDataSource {
var ll = LectureController()
var uc = UserController()
var ac = AuctionController()
var tableView = UITableView()
var container = [Lecture]()
let typeImagesArray = ["cirkel_workshop","cirkel_social","Cirkel_debat","cirkel_firehose","cirkel_3roundBurst","cirkel_talk"]
var line = UIView(frame:CGRect(x:5,y:55, width:UIScreen.main.bounds.width - 10,height:1))
var titleLabel = UILabel(frame:CGRect(x:10,y:27, width:UIScreen.main.bounds.width - 20,height:20))
var blurEffectView = UIVisualEffectView()
let items = ["Fredag", "Lørdag", "Søndag"]
var daySC = UISegmentedControl()
var day = 0
var dataLoaded = false
var loadingImage = UIImageView()
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
if(defaults.object(forKey:"newDownload") == nil)
{
uc.logOut(completion: { (Bool) in
self.defaults.set(true, forKey: "newDownload")
})
}
titleLabel.text = "Programmet".uppercased()
titleLabel.font = UIFont (name: "HelveticaNeue-Bold", size: 25)
titleLabel.textAlignment = .center
self.view.addSubview(titleLabel)
line.backgroundColor = .black
self.view.addSubview(line)
loadingImage.image = UIImage(named: "bifrostLogo")
loadingImage.frame = CGRect(x: (UIScreen.main.bounds.width/2) - 37.5, y:(UIScreen.main.bounds.height/2) - 37.5, width:75, height: 75)
daySC = UISegmentedControl(items: items)
daySC.selectedSegmentIndex = 0
let frame = UIScreen.main.bounds
daySC.frame = CGRect(x:-2, y:55, width: frame.width + 4,height: 30)
daySC.addTarget(self, action: #selector(changeColor(sender:)), for: .valueChanged)
daySC.tintColor = .black
self.view.addSubview(daySC)
tableView.frame = CGRect(x:0,y:85, width:self.view.frame.width,height:self.view.frame.height - 132);
tableView.delegate = self
tableView.dataSource = self
tableView.register(LectureCell.self, forCellReuseIdentifier: "cell")
tableView.backgroundColor = UIColor.clear
tableView.rowHeight = 75
tableView.separatorColor = .clear
self.view.addSubview(tableView)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
UIView.animate(withDuration: 0.5) {
self.blurEffectView.alpha = 1.0
self.pulsate(object: self.loadingImage)
}
self.view.addSubview(blurEffectView)
self.blurEffectView.addSubview(loadingImage)
}
override func viewDidAppear(_ animated: Bool) {
print("users\(uc.uc.userContainer.count)")
if(uc.uc.userContainer.count > 0)
{
loggedIn = true
}
if(loadedFirst == false)
{
print("loadedFirst")
uc.checkUsersLoginStatus(test: false, completion: { (result) in
if(result == true)
{
print("loadedIN")
self.ll.loadLectures(test: false) { (result) in
self.container = result[0]!
//Loading auction items
_ = self.uc.getFavoriteLectures(test: false, completion: { (result) in
self.tableView.reloadData()
self.dataLoaded = true
UIView.animate(withDuration: 0.5) {
self.blurEffectView.alpha = 0.0
}
loggedIn = true
})
}
self.ac.loadAuctionItems { (result) in
_ = self.uc.getFavoriteAuctionItems(test: false, completion: { (result) in
})
}
loadedFirst = true
}
else
{
print("usercheck failed")
let vc = LoginView()
self.present(vc, animated: false, completion: nil)
}
})
}
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.applicationIconBadgeNumber = 0
if(dataLoaded == true)
{
ll.lecturesFromLocalMemory(day: day) { (result) in
self.container = result
self.tableView.reloadData()
}
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 0.0
}, completion: nil)
}
}
func changeColor(sender: UISegmentedControl) {
day = sender.selectedSegmentIndex
ll.lecturesFromLocalMemory(day: day, completion: { (result) in
container = result
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return container.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var index = section
if(section - 1 < 0)
{
index = 0
}
if(index > 0)
{
if("\(String(describing: container[section].startTime))\(container[section].endTime!)" != "\(String(describing: container[section - 1].startTime))\(container[section - 1].endTime!)")
{
return"\(String(describing: container[section].startTime!)) - \(container[section].endTime!)"
}
else
{
return ""
}
}
else
{
return "\(String(describing: container[section].startTime!)) - \(container[section].endTime!)"
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:LectureCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LectureCell
let item = container[indexPath.section]
cell.typeImage.image = UIImage(named: typeImagesArray[Int(item.type!)!])
cell.titleLabel.text = item.name?.uppercased()
cell.placeLabel.text = item.place
cell.alpha = 0.0
var duration = 0
var delay = 0.0
if(tableLoaded == false)
{
duration = 1
delay = Double(0.25)
}
UIView.animate(withDuration: TimeInterval(duration), delay: delay * Double(indexPath.section),options: UIViewAnimationOptions.curveEaseIn,animations: {
if(loggedIn == false)
{
cell.alpha = 0.0
}
else
{
cell.alpha = 1.0
}
})
if((User.favoriteLectures[day]?.filter{$0.id == item.id}.count)! > 0)
{ container[indexPath.section].favorit = true
cell.favorite.setImage(UIImage(named:"heartDark"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(addFavorite(_:)), for: UIControlEvents.touchUpInside)
cell.favorite.tag = indexPath.section
}
else
{
container[indexPath.section].favorit = false
cell.favorite.setImage(UIImage(named:"heart"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(addFavorite(_:)), for: UIControlEvents.touchUpInside)
cell.favorite.tag = indexPath.section
}
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.alpha = 0.0
var duration = 0
var delay = 0.0
if(tableLoaded == false)
{
duration = 1
delay = Double(0.25)
}
UIView.animate(withDuration: TimeInterval(duration), delay: delay * Double(section),options: UIViewAnimationOptions.curveEaseIn,animations: {
view.alpha = 1.0
})
if(section == container.count - 1)
{
print("tableLoaded")
tableLoaded = true
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 1.0
}, completion: nil)
let vc = LectureItemView()
let item = container[indexPath.section]
vc.lc = [item]
self.present(vc, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let favorite = UITableViewRowAction(style: .normal, title: "RET") { action, index in
print("favorite button tapped")
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 1.0
}, completion: nil)
let vc = EditView()
let item = self.container[editActionsForRowAt.section]
vc.lc = [item]
vc.day = self.day
vc.row = editActionsForRowAt.section
self.present(vc, animated: true, completion: nil)
}
favorite.backgroundColor = .lightGray
return [favorite]
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if(uc.uc.userContainer.count > 0 && uc.uc.userContainer[0].admin == 1)
{
return true
}
else
{
return false
}
}
func addFavorite(_ sender:AnyObject)
{
let item = container[sender.tag]
if(item.favorit == false)
{
print("addFavorite")
container[sender.tag].favorit = true
_ = uc.addToFavoritList(type: "lecture", lecture: item, auctionItem:nil)
}
else
{
print("removeFavorite")
container[sender.tag].favorit = false
_ = uc.removeFromFavoritList(type: "lecture", lecture: item, auctionItem: nil)
}
let indexPath = IndexPath(item: 0, section: sender.tag)
self.tableView.reloadRows(at: [indexPath], with: .fade)
}
func add(sender:AnyObject)
{
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 1.0
}, completion: nil)
let vc = EditView()
let item = Lecture(JSON: ["id" : "","title":"","endTime":"10:00","startTime":"12:00","place":"","type":"1","headerImage":"","lecturer":["":["":""]],"description":""])!
item.day = day
vc.lc = [item]
vc.day = self.day
self.present(vc, animated: true, completion: nil)
}
func pulsate(object: UIImageView) {
let pulsateAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
object.layer.pop_add(pulsateAnim, forKey: "layerScaleSpringAnimation")
pulsateAnim?.velocity = CGPoint(x:0.1, y:0.1)
pulsateAnim?.toValue = CGPoint(x:1.2, y:1.2)
pulsateAnim?.springBounciness = 40
pulsateAnim?.dynamicsFriction = 20
pulsateAnim?.springSpeed = 5.0
}
}
| mit | 1778bd949fb9def4d594b129f9b9eeb6 | 33.86612 | 190 | 0.564924 | 4.684655 | false | false | false | false |
normand1/DNFlyingBadge | Example/DNFlyingBadges/FeelingsViewController.swift | 1 | 1570 | //
// FeelingsViewController.swift
// DNFlyingBadges
//
// Created by David Norman on 6/8/15.
// Copyright (c) 2015 David Norman. All rights reserved.
//
import UIKit
import DNFlyingBadges
class FeelingsViewController: UIViewController {
@IBOutlet weak var targetLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Actions
@IBAction func evilAction(sender: UIButton) {
var flyingBadgeView = DNFlyingBadgesView(frame: CGRectMake(0, 0, 100, 100))
flyingBadgeView.color = UIColor.redColor()
flyingBadgeView.defaultImageName = DNFlyingBadgesView.Image.Evil
flyingBadgeView.rotateAndAnimateFlyingBadgeFromTopInView(self.view, toPoint: targetLabel.frame.origin, rotation: M_PI, continuousRotation: true, forTime:4) {
//animation finished
}
}
@IBAction func goodAction(sender: UIButton) {
var flyingBadgeView = DNFlyingBadgesView(frame: CGRectMake(0, 0, 100, 100))
flyingBadgeView.color = UIColor.blueColor()
flyingBadgeView.defaultImageName = DNFlyingBadgesView.Image.Smile
flyingBadgeView.rotateAndAnimateFlyingBadgeFromTopInView(self.view, toPoint: targetLabel.frame.origin, rotation: M_PI, continuousRotation: true, forTime:4) {
//animation finished
}
}
}
| mit | 11b8bdb7e6ff4f7f56e982b1a8ed4f03 | 29.192308 | 165 | 0.691083 | 4.361111 | false | false | false | false |
LuisPalacios/lupa | lupa/Controllers/LupaSearchWinCtrl.swift | 1 | 43094 | //
// LupaSearchWinCtrl.swift
// lupa
//
// Created by Luis Palacios on 20/9/15.
// Copyright © 2015 Luis Palacios. All rights reserved.
//
import Cocoa
import Foundation
let ikWINDOW_MIN_HEIGHT : CGFloat = 77.0
class LupaSearchWinCtrl: NSWindowController, NSWindowDelegate, NSSearchFieldDelegate, NSTableViewDataSource, NSTableViewDelegate, LupaSearchTableviewDelegate, LupaPopoverDetailViewDelegate {
/// --------------------------------------------------------------------------------
// MARK: Attributes
/// --------------------------------------------------------------------------------
// For the following attributes I'm using Implicitly Unwrapped Optional (!) so
// they are optionals and do not need to initialize them here, will do later.
@IBOutlet weak var searchField: LupaSearchField!
@IBOutlet weak var searchFieldCell: NSSearchFieldCell!
@IBOutlet weak var spinningLDAP: NSProgressIndicator!
@IBOutlet weak var msgStackView: NSStackView!
@IBOutlet var msgTextView: NSTextView!
var timerHideAlert : Timer! //!< Timer that the alert to be hidden
@IBOutlet weak var ldapResultStackView: NSStackView!
@IBOutlet weak var mainStackView: NSStackView!
@IBOutlet weak var searchStackView: NSStackView!
// TableView
@IBOutlet weak var ldapResultTableView: LupaSearchTableview! // Tableview for the Search results
var ldapResultCellViewHeight : CGFloat = 17.0 // Tableview's cell height (notice it'll be calculated)
// Popover with ldap result detail (right click)
@IBOutlet var popoverDetail: NSPopover!
@IBOutlet var lupaPopoverDetailView: LupaPopoverDetailView!
// In order to work with the user defaults, stored under:
// /Users/<your_user>/Library/Preferences/parchis.org.lupa.plist
// $ defaults read parchis.org.lupa.plist
let userDefaults : UserDefaults = UserDefaults.standard
// Class attributes
var stringToSearch = ""
@objc dynamic var ldapSearchResults = ""
var observableKeys_LDAPSearchResults = [ "self.ldapSearchHasFinished" ]
@objc dynamic var ldapSearchHasFinished : Bool = false
@objc dynamic var users = [LPLdapUser]()
@objc dynamic var tmpUsers = [LPLdapUser]()
@objc dynamic var popoverSelectedUser : LPLdapUser!
var tmpErrors : [String] = []
// More attributes
var textDidChangeInterval : TimeInterval = 0.0 //!< Time interval to calculate text did change trigger action
var previousSearchString : String = "" //!< Control if I'm asked to search the same string as before
var timerTextDidChange : Timer! //!< Timer that triggers action after text did change
var browserSearchIsRunning : Bool = false
var ldapSearchIsRunning : Bool = false
var postfix_searchString = ""
var minHeight = ikWINDOW_MIN_HEIGHT
// Commander
let cmd = LPCommand()
var timerCmdTerminate : Timer! //!< Ldap terminate timer
/// --------------------------------------------------------------------------------
// MARK: Main
/// --------------------------------------------------------------------------------
/// Sent after the window owned by the receiver has been loaded.
///
override func windowDidLoad() {
super.windowDidLoad()
// Register the Cell View nib file so that the ldapResultTableView
// can use it to render cells,
if let nib = NSNib(nibNamed: NSNib.Name(rawValue: Constants.SearchCtrl.SearchCellViewID), bundle: Bundle.main) {
// Change searchField UX
self.searchField.appearance = NSAppearance(named: NSAppearance.Name.aqua)
// Register the Cell
self.ldapResultTableView.register(nib, forIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.SearchCtrl.SearchCellViewID))
// Find out TableView's cell height
var optViewArray: NSArray? = nil
if nib.instantiate(withOwner: self, topLevelObjects: &optViewArray) {
if let viewArray = optViewArray {
for view in viewArray {
if view is LupaSearchCellView {
if let frame = (view as AnyObject).frame {
self.ldapResultCellViewHeight = frame.height
}
}
}
}
}
}
// Register as delegate to capture right click on ldap results
self.ldapResultTableView.lupaSearchTableviewDelegate = self
// Register as delegate so I can exit detail ldap view when clicked
self.lupaPopoverDetailView.lupaPopoverDetailViewDelegate = self
// Setup the window class
if let letMyWindow = self.window {
let myWindow = letMyWindow
myWindow.isOpaque = false
myWindow.hasShadow = true
myWindow.backgroundColor = NSColor.clear
}
// Calc the minimum Height possible for the
// search window. It's exactly without the
// message and ldap results stackviews
if let window = self.window {
self.minHeight = window.frame.size.height - self.mainStackView.frame.size.height + self.searchStackView.frame.size.height
}
// Now I can hide both msg/ldap stackviews
self.msgStackView.isHidden = true
self.ldapResultStackView.isHidden = true
self.updateWindowFrame()
// Subscribe myself so I'll receive(Get) Notifications
NotificationCenter.default.addObserver(self,
selector: #selector(LupaSearchWinCtrl.handleWindowDidBecomeActiveNotification(_:)),
name: NSWindow.didBecomeKeyNotification,
object: nil)
// Hide spinning
self.spinningLDAP.isHidden = true
}
/// awakeFromNib()
//
// Prepares the receiver for service after it has been loaded from
// an Interface Builder archive, or nib file. It is guaranteed to
// have all its outlet instance variables set.
//
override func awakeFromNib() {
// print("awakeFromNib()")
// Remove the "cancel button" from the Search Field
// so I keep the focus on the search field "always"
self.searchFieldCell.cancelButtonCell = nil
}
// What to do when the Window is shown, well... select the whole nssearchfield :)
// so the user can start typing a new search text (deleting the old one)
//
@objc func handleWindowDidBecomeActiveNotification (_ note : Notification) {
// Everytime I do appear select the text
self.searchField.selectText(self)
}
/// --------------------------------------------------------------------------------
// MARK: TableView NSSearchFieldDelegate, NSTableViewDataSource
/// --------------------------------------------------------------------------------
func numberOfRows(in tableView: NSTableView) -> Int {
return self.users.count
}
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return self.ldapResultCellViewHeight
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: Constants.SearchCtrl.SearchCellViewID), owner: self) as? LupaSearchCellView else {
return nil
}
let user = self.users[row]
cell.itemName.stringValue = user.desc
cell.itemUID.stringValue = user.cn
cell.itemMobile.stringValue = user.voicemob
cell.itemJobTitle.stringValue = user.title
cell.itemImage.image = nil
// Reason for using main thread:
// Updating UI on a thread other than the main thread is a common mistake
// that can result in missed UI updates, visual defects, data corruptions, and crashes
let mainQueue = LPQueue.Main
mainQueue.async { () -> () in
if let url = user.picturlMini {
cell.itemImage.image = NSImage(contentsOf: url)
}
}
return cell
}
/// --------------------------------------------------------------------------------
// MARK: UI
/// --------------------------------------------------------------------------------
// Show the ldap results stack view
//
func showLdapResultsStackView() {
self.ldapResultStackView.isHidden = false
self.updateWindowFrame()
}
// Hide the ldap results stack view
//
func hideLdapResultsStackView() {
self.ldapResultStackView.isHidden = true
self.updateWindowFrame()
}
// Show Alert stack view
func showMessage(_ msg: String) {
self.msgTextView.string = msg
self.msgStackView.isHidden = false
self.startTimerHideAlert()
}
func hideMessage() {
self.msgStackView.isHidden = true
self.updateWindowFrame()
}
// Start a timer that will hide the Alert information
//
func startTimerHideAlert() {
self.stopTimerHideAlert()
self.timerHideAlert = Timer.scheduledTimer(timeInterval: 4,
target: self,
selector: #selector(LupaSearchWinCtrl.actionTimerHideAlert),
userInfo: nil,
repeats: false)
}
// Stop the timer that will hide the Alert information
//
func stopTimerHideAlert() {
if ( timerHideAlert != nil ) {
if ( self.timerHideAlert.isValid ) {
self.timerHideAlert.invalidate()
}
self.timerHideAlert = nil
}
}
// Action to execute when the timer finishes
//
@objc func actionTimerHideAlert() {
self.hideMessage()
}
// Update the Window Frame, basically resize
// its height based on what I'm showing...
func updateWindowFrame() {
if ( self.ldapResultStackView.isHidden == true ) {
// LDAP RESULT's VIEW INACTIVE
if let window = self.window {
var newSize = window.frame.size
newSize.height = self.minHeight
window.setContentSize(newSize) // Only available under 10.10
}
} else {
// LDAP RESULT's VIEW ACTIVE
var windowHeight = self.minHeight
if ( self.users.count != 0 ) {
var max : CGFloat = 5.0
if ( self.users.count < 5 ) {
max = CGFloat ( self.users.count )
}
windowHeight = self.minHeight + ( (self.ldapResultCellViewHeight + 2.0) * max ) + 12.0
}
if let window = self.window {
var newSize = window.frame.size
newSize.height = windowHeight
window.setContentSize(newSize) // Only available under 10.10
}
}
lpStatusItem.updateFrameStatusItemWindow()
}
/// --------------------------------------------------------------------------------
// MARK: Actions when user modifies searchField or presses Enter
/// --------------------------------------------------------------------------------
// Bound to the NSSearchField. Called every time the search field content is modified.
//
@IBAction func searchFieldModified(_ sender: AnyObject) {
self.textDidChangeInterval = 0.0
self.startTimerTextDidChange()
}
// Handle ESCAPE Key when focus is on an object differnt to the NSSearchField
//
override func cancelOperation(_ sender: Any?) {
// Close the Window
lpStatusItem.dismissStatusItemWindow()
}
// Bound thanks to NSSearchFieldDelegate
//
// From IB connect NSSearchField with File's Owner->Delegate
//
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
// If I return false then the default will happen,
// searchFieldModified() will be called
var retValue : Bool = false //
switch commandSelector {
case #selector(NSResponder.insertNewline(_:)):
// BROWSER Search -
//
self.stringToSearch = searchField.stringValue.trim()
if !self.stringToSearch.isEmptyOrWhitespace() {
self.postfix_searchString = self.stringToSearch
self.startBrowserSearch()
} else {
// print ("Search string empty, ignore it...")
}
self.previousSearchString=self.stringToSearch
// retval = true causes Apple to NOT fire the default enter action
// so if true, searchFieldModified() will NOT be called
retValue = true
case #selector(NSResponder.cancelOperation(_:)):
// Handle ESCAPE Key when pressed from the NSSearchField
//
lpStatusItem.dismissStatusItemWindow()
// retval = true causes Apple to NOT fire the default enter action
// so if true, searchFieldModified() will NOT be called
retValue = true
default:
//Swift.print("Llegó otro comando y lo ignoro: \(commandSelector)")
break
}
// Return
return retValue
}
/// --------------------------------------------------------------------------------
// MARK: Browser search
/// --------------------------------------------------------------------------------
// Call default browser with full URL from the prefix + search_field
//
func startBrowserSearch() {
//print("startBrowserSearch()")
// Cancel the automated LDAP search if pending...
self.stopTimerTextDidChange()
// Read userDefaults (String) and convert into NSURL
if let letURLString = self.userDefaults.object(forKey: LUPADefaults.lupa_URLPrefix) as? String {
// print("lupa_URLPrefix: \(letURLString)")
if !letURLString.isEmpty {
// I spect self.postfix_searchString with the string
// to be added at the end of the url
var searchString = self.postfix_searchString
if let letSearchSeparatorEnabled = self.userDefaults.object(forKey: LUPADefaults.lupa_SearchSeparatorEnabled) as? Bool {
let searchSeparatorEnabled = letSearchSeparatorEnabled
if ( searchSeparatorEnabled ) {
if let letSearchSeparator = self.userDefaults.object(forKey: LUPADefaults.lupa_SearchSeparator) as? String {
let searchSeparator = letSearchSeparator
searchString = self.stringToSearch.replacingOccurrences(of: " ", with: searchSeparator, options: NSString.CompareOptions.literal, range: nil)
}
}
}
// Setup the final string
let searchURLString : String = letURLString + searchString
// print("searchURLString: \(searchURLString)")
// Let's go rock and roll
//
// Note: I'm leaving here a way to activate a "Testing" mode logging into screen instead
// of launching the default browser. To activate it though, needs to be done from Terminal:
//
// $ defaults write parchis.org.lupa lupa_TestMode -bool YES
//
var testMode: Bool = false
if let letTestMode = self.userDefaults.object(forKey: LUPADefaults.lupa_TestMode) as? Bool {
testMode = letTestMode
}
// Let's go for it
browserSearchIsRunning = true
if ( testMode ) {
print("TEST MODE - Browser URL: \(searchURLString)")
} else {
// Production mode, fix spaces
let myUrlString : String = searchURLString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let theURL : URL? = URL (string: myUrlString)
// print("theURL: \(theURL?.path)")
NSWorkspace.shared.open(theURL!)
}
browserSearchIsRunning = false
} else {
// print ("URL Prefix is empty, you should set something like doDefaults...")
// statusbarController.showPreferences()
}
} else {
// print("Prefix is not an string object, ignore it....")
}
// Close the Window
lpStatusItem.dismissStatusItemWindow()
}
// Try to stop the Browser search
func stopBrowserSearch() {
// print("stopBrowserSearch(): ToDo")
// Send a signal indicating that search was cancel
browserSearchIsRunning = false
// ToDo
}
// A row from the search ldap search results has been selected so
// I have to go for the browser thing...
@IBAction func rowSelected(_ sender: AnyObject) {
let selectedRow = self.ldapResultTableView.selectedRow
if ( selectedRow != -1 && selectedRow < self.users.count ) {
let user = self.users[selectedRow]
if !user.cn.isEmpty {
self.postfix_searchString = user.cn
self.startBrowserSearch()
} else {
print ("ERROR: user cn is empty")
}
}
}
/// --------------------------------------------------------------------------------
// MARK: TableView LupaSearchTableviewDelegate (POPOVER with detail)
/// --------------------------------------------------------------------------------
// Right Clicked a row to show details
//
func tableView(_ tableview: NSTableView, clickedRow: NSInteger, clickedColumn: NSInteger, clickedPoint: NSPoint, clickedRect: NSRect) {
self.popoverSelectedUser = nil
self.popoverDetail.show(relativeTo: clickedRect, of: tableview, preferredEdge: NSRectEdge.minY)
let mainQueue = LPQueue.Main
mainQueue.async { () -> () in
self.popoverSelectedUser = self.users[clickedRow]
}
}
/// --------------------------------------------------------------------------------
// MARK: LupaPopoverDetailViewDelegate
/// --------------------------------------------------------------------------------
// Mouse left click on top of the Popover Detail View
//
func popoverDetailViewClicked() {
// Rule is: Dismiss and Browse the user
self.popoverDetail.close()
let user = self.popoverSelectedUser
if !(user?.cn.isEmpty)! {
self.postfix_searchString = (user?.cn)!
self.startBrowserSearch()
} else {
print ("ERROR: user cn is empty")
}
}
// Mouse right click on top of the Popover Detail View
//
func popoverDetailViewRightClicked() {
// Rule is: Dismiss the view
self.popoverDetail.close()
}
/// --------------------------------------------------------------------------------
// MARK: LDAP search
/// --------------------------------------------------------------------------------
// Start the ldap search
// Prepare the command....
//
func ldapsearchStart(_ timeout : Int) {
// search string
let searchString : String = self.stringToSearch
let searchWords = searchString.components(separatedBy: CharacterSet.whitespaces)
// Continue analysing each of the arguments...
var commandString : String = ""
// CLI Command (LDAPTLS_REQCERT=allow /usr/bin/ldapsearch)
//
guard let letLDAP_Command = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Command) as? String else {
self.showMessage("ERROR: Missing LDAP command")
return
}
commandString = letLDAP_Command
// Host and port URL (-H ldap[s]://myhost.domain.com:636)
//
guard let letLDAP_Host = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Host) as? String else {
self.showMessage("ERROR: Missing Host")
return
}
// Get the default LDAP Port and SSL status
var letLDAP_URI = "ldap"
if let active = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_SSL) as? Bool {
if active == true {
letLDAP_URI = "ldaps"
}
}
var letLDAP_Port = "389"
var intLDAP_Port = 389
if let letLDAP_Bind_Port = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Port) as? String {
letLDAP_Port = letLDAP_Bind_Port
}
if let num = Int(letLDAP_Port) {
intLDAP_Port = num
}
commandString = commandString + " -H " + letLDAP_URI + "://" + letLDAP_Host + ":" + letLDAP_Port
// Limit search (-z 'n')
//
var limitResults = 20
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Limit_Results) as? String {
if ( !letTheString.isEmpty ) {
if let theLimit = Int(letTheString) {
limitResults = theLimit
commandString = commandString + " -z \(limitResults)"
}
}
}
// Binding information -D user,usrestore -w Password
//
if let letLDAP_Bind_User = self.userDefaults.object(forKey: LUPADefaults.lupa_BIND_User) as? String {
var bindUser = letLDAP_Bind_User
guard let letLDAP_Bind_UserStore = self.userDefaults.object(forKey: LUPADefaults.lupa_BIND_UserStore) as? String else {
self.showMessage("ERROR: Missing User store")
return
}
bindUser = "CN=" + bindUser + "," + letLDAP_Bind_UserStore
commandString = commandString + " -D \"" + bindUser + "\""
guard let letLDAP_Bind_Password = internetPasswordForServer(letLDAP_Host, account: letLDAP_Bind_User, port: intLDAP_Port, secProtocol: SecProtocolType.LDAPS) else {
self.showMessage("ERROR: Password is missing")
return
}
commandString = commandString + " -w \"" + letLDAP_Bind_Password + "\""
}
// Search base (-x -b basedn)
//
guard let letLDAP_BaseDN = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_BaseDN) as? String else {
self.showMessage("ERROR: Base DN is missing")
return
}
commandString = commandString + " -x -b \"" + letLDAP_BaseDN + "\""
// Here we go...
self.ldapSearchIsRunning = true
// Prepare the Filters
//
// ( | (description=*W1*W2*W3*...*Wn*) (cn=*W1*W2*W3*...*Wn*) )
//
var gotFilter = false
var wordRegex = "*"
for word in searchWords {
if ( word.lengthOfBytes(using: String.Encoding.utf8) > 0 ) {
wordRegex = wordRegex + "\(word)*"
}
}
let search_CN = self.userDefaults.bool(forKey: LUPADefaults.lupa_LDAP_Search_CN)
let search_Desc = self.userDefaults.bool(forKey: LUPADefaults.lupa_LDAP_Search_Desc)
let search_VoiceLin = self.userDefaults.bool(forKey: LUPADefaults.lupa_LDAP_Search_VoiceLin)
let search_VoiceInt = self.userDefaults.bool(forKey: LUPADefaults.lupa_LDAP_Search_VoiceInt)
let search_VoiceMob = self.userDefaults.bool(forKey: LUPADefaults.lupa_LDAP_Search_VoiceMob)
var filter = "( |"
if search_CN {
if let str = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_CN) as? String {
filter = filter + " (\(str)=\(wordRegex))"
gotFilter=true
}
}
if search_Desc {
if let str = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Desc) as? String {
filter = filter + " (\(str)=\(wordRegex))"
gotFilter=true
}
}
if search_VoiceLin {
if let str = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceLin) as? String {
filter = filter + " (\(str)=\(wordRegex))"
gotFilter=true
}
}
if search_VoiceInt {
if let str = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceInt) as? String {
filter = filter + " (\(str)=\(wordRegex))"
gotFilter=true
}
}
if search_VoiceMob {
if let str = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceMob) as? String {
filter = filter + " (\(str)=\(wordRegex))"
gotFilter=true
}
}
filter = filter + " )"
if ( gotFilter == true ) {
commandString = commandString + " '" + filter as String + "'"
}
// Prepare the attributes to fetch
//
commandString = commandString + " dn cn uid "
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_City) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Title) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Desc) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceLin) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceInt) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Country) as? String {
commandString = commandString + letTheString + " "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceMob) as? String {
commandString = commandString + letTheString
}
// Start the spinning...
let mainQueue = LPQueue.Main
mainQueue.async { () -> () in
self.startUI_LDAPsearchInProgress()
}
// Launch the ldapsearch, will be an async thread
self.execCmdAndParse(commandString)
// Launch ldapsearch execution timeout. If program doesn't return
// after timeout seconds, send him a terminate signal
if ( timeout != 0 ) {
self.startTimerCmdTerminate(timeout)
}
}
// Command execution timer --------------------------------------------------
//
func startTimerCmdTerminate(_ timeout : Int) {
self.stopTimerCmdTerminate()
let dTimeout = Double(timeout)
self.timerCmdTerminate = Timer.scheduledTimer(timeInterval: dTimeout,
target: self,
selector: #selector(LupaSearchWinCtrl.actionTimerCmdTerminate),
userInfo: nil,
repeats: false)
}
func stopTimerCmdTerminate() {
if ( timerCmdTerminate != nil ) {
if ( self.timerCmdTerminate.isValid ) {
self.timerCmdTerminate.invalidate()
}
self.timerCmdTerminate = nil
}
}
@objc func actionTimerCmdTerminate() {
// Ask current cmd to stop
self.showMessage("'ldapsearch' or network timeout!")
self.cmd.terminate()
}
// --------------------------------------------------------------------------
// search has Finished
//
func ldapsearchFinished(_ exit: Int) {
// Stop timers and visual UI
self.stopTimerCmdTerminate()
self.stopUI_LDAPsearchInProgress()
// Go for it...
if ( exit == 0 && tmpErrors.count == 0 ) {
// Get the new list of users
self.users = self.tmpUsers
// Show (or hide) the results view
if ( self.users.count != 0 ) {
self.showLdapResultsStackView()
} else {
self.hideLdapResultsStackView()
}
// Post process the list of users
print("ldapsearchFinished. Found \(self.users.count) users.\n")
for user in self.users {
if let pict = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_PictureURLMini) as? String {
let mutableString = NSMutableString(string: pict)
let regex = try! NSRegularExpression(pattern: "<CN>",
options: [.caseInsensitive])
regex.replaceMatches(in: mutableString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, mutableString.length), withTemplate: user.cn)
let mySwiftString = mutableString as String
// if let mySwiftString : String = mutableString as String {
if let letURL = URL(string: mySwiftString) {
user.picturlMini = letURL
}
// }
}
if let pict = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_PictureURLZoom) as? String {
let mutableString = NSMutableString(string: pict)
let regex = try! NSRegularExpression(pattern: "<CN>",
options: [.caseInsensitive])
regex.replaceMatches(in: mutableString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, mutableString.length), withTemplate: user.cn)
let mySwiftString = mutableString as String
// if let mySwiftString : String = mutableString as String {
if let letURL = URL(string: mySwiftString) {
user.picturlZoom = letURL
}
// }
}
}
self.ldapResultTableView.reloadData()
} else {
// print("ldapsearchFinished didn't succeed. Exit: \(exit)\nErrors: \(self.tmpErrors)")
if ( self.tmpErrors.count > 0 ) {
self.showMessage(self.tmpErrors[0])
}
self.hideLdapResultsStackView()
}
// Send a signal indicating that search was cancel
self.ldapSearchIsRunning = false
}
// Stop the search
//
func ldapsearchStop() {
// Stop timers and visual UI
self.stopTimerCmdTerminate()
self.stopUI_LDAPsearchInProgress()
// Ask current cmd to stop
self.cmd.terminate()
// Search has been cancel
self.ldapSearchIsRunning = false
}
/** @brief Gestión del Spinning wheel que indica que Abaco está trabajando
*
*/
func startUI_LDAPsearchInProgress () {
// self.spinningLDAP.lay
self.spinningLDAP.startAnimation(self)
self.spinningLDAP.isHidden = false
}
func stopUI_LDAPsearchInProgress () {
self.spinningLDAP.stopAnimation(self)
self.spinningLDAP.isHidden = true
}
//[[[self out_SpinningCAView] progressIndicatorLayer] setColor:[NSColor blackColor]];
/// --------------------------------------------------------------------------------
// MARK: Execute command from shell
/// --------------------------------------------------------------------------------
// Execute a cli command
//
func execCmdAndParse(_ commandString: String) {
var newUser: Bool = false
var user : LPLdapUser!
// I'll use userDefaults, however I'm setting even more defaults :)
var cn: String = "cn: "
var description: String = "description: "
var country: String = "c: "
var city: String = "city: "
var voicelin: String = "telephoneNumber: "
var voiceint: String = "telephoneInternal: "
var voicemob: String = "mobile: "
var title: String = "title: "
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Desc) as? String {
description = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_CN) as? String {
cn = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Country) as? String {
country = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_City) as? String {
city = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceLin) as? String {
voicelin = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceInt) as? String {
voiceint = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_VoiceMob) as? String {
voicemob = letTheString + ": "
}
if let letTheString = userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Attr_Title) as? String {
title = letTheString + ": "
}
let myAttributes = [cn, "uid: ", description, country, city, voicelin, voicemob, voiceint, title]
// Clean start
self.tmpUsers.removeAll()
// Got a command, lets log it. Notice that I REMOVE THE PASSWORD
// print("Command: \(commandString)")
// ToDO - investigate: if someone is looking at the process list (difficult I know)...
// they will see the password while the command is being executed
var logString = ""
if let rangeBeforePassword = commandString.range(of: "-w", options: .backwards) {
let index = rangeBeforePassword.lowerBound
// let stringBeforePassword = commandString.substring(to: index) // swift 3
let stringBeforePassword = String(commandString[..<index]) // swift 4
logString = stringBeforePassword
}
logString = logString + "-w \"PASSWORD_HIDDEN\" "
if let rangeAfterPassword = commandString.range(of: "-x", options: .backwards) {
let index = rangeAfterPassword.lowerBound
// let stringAfterPassword = commandString.substring(from: index) // swift 3
let stringAfterPassword = String(commandString[index...]) // swift 4
logString = logString + stringAfterPassword
}
print("Command: \(logString)")
// DELETE ME !!!!
// let cmdDebugString = "/usr/local/duermeyhabla.sh"
// print("Command: \(cmdDebugString)")
// Ahí que vamos...
self.cmd.run(commandString) { (exit, stdout, stderr) -> Void in
// Just for Logging
// print("---------------------------------- STANDARD OUTPUT -------- STAR")
// for line in stdout {
// print(line)
// }
// print("---------------------------------- STANDARD OUTPUT -------- END")
// print("---------------------------------- STANDARD ERROR -------- START")
// for line in stderr {
// print(line)
// }
// print("---------------------------------- STANDARD ERROR -------- END")
// print("exit: \(exit)")
// print("")
// Clean up future buffers
self.tmpErrors.removeAll()
// Let's see if we end up without errors
if ( exit == 0 && stderr.count == 0 ) {
// Work the lines
for line in stdout {
// print("completionHandler - LINE: \(line)")
// Do something with each line
if !line.hasPrefix("#") {
// DN
if line.hasPrefix("dn: ") {
newUser = true
var token = line.components(separatedBy: "dn: ")
user = LPLdapUser()
user.dn = token[1]
self.tmpUsers.append(user)
} else {
if ( newUser ) {
for attr in myAttributes {
if line.hasPrefix(attr) {
var token = line.components(separatedBy: attr)
switch attr {
case cn:
user.cn = token[1]
break
case "uid: ":
user.uid = token[1]
break
case description:
user.desc = token[1]
break
case country:
user.country = token[1]
break
case city:
user.city = token[1]
break
case voicelin:
user.voicetel = token[1]
break
case voiceint:
user.voiceint = token[1]
break
case voicemob:
user.voicemob = token[1]
break
case title:
user.title = token[1]
break
default:
break
}
}
}
}
}
}
}
} else {
for line in stderr {
self.tmpErrors.append(line)
}
}
// Say it, we finished
// print("TERMINÓ EL COMANDO, cambio self.ldapSearchHasFinished = true ")
let mainQueue = LPQueue.Main
mainQueue.async { () -> () in
self.ldapsearchFinished(exit)
}
}
}
/// --------------------------------------------------------------------------------
// MARK: Timer when search text changes
/// --------------------------------------------------------------------------------
// Start a timer when text changes in the search box
//
func startTimerTextDidChange() {
self.stringToSearch = searchField.stringValue.trim()
// Always cancel any pending search
self.stopTimerTextDidChange()
// Check if we've got something decent to search
if self.stringToSearch.isEmptyOrWhitespace() {
self.hideLdapResultsStackView()
} else {
timerTextDidChange = Timer.scheduledTimer(timeInterval: 0.6,
target: self,
selector: #selector(LupaSearchWinCtrl.actionTimerTextDidChange),
userInfo: nil,
repeats: false)
}
}
// Stop the timer
//
func stopTimerTextDidChange() {
if ( timerTextDidChange != nil ) {
if ( timerTextDidChange.isValid ) {
timerTextDidChange.invalidate()
}
if ( self.ldapSearchIsRunning ) {
self.ldapsearchStop()
}
timerTextDidChange = nil
}
}
// Action to execute when the timer finishes
//
@objc func actionTimerTextDidChange() {
if let ldapSupport = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Support) as? Bool {
if ldapSupport {
// Prepare the ldapsearch command timeout
var timeout = 10
if let str = self.userDefaults.object(forKey: LUPADefaults.lupa_LDAP_Timeout) as? String {
if ( !str.isEmpty ) {
if let theTimeout = Int(str) {
timeout = theTimeout
}
}
}
// Call command
self.ldapsearchStart(timeout)
}
}
self.previousSearchString=self.stringToSearch
}
}
| mit | f45fa2d8a21b8302dfc15223391e4686 | 38.675875 | 190 | 0.511975 | 5.180091 | false | false | false | false |
yonaskolb/SwagGen | Sources/Swagger/Schema/Schema.swift | 1 | 2799 | import JSONUtilities
public struct Schema {
public let metadata: Metadata
public let type: SchemaType
public init(metadata: Metadata, type: SchemaType) {
self.metadata = metadata
self.type = type
}
}
public enum SchemaType {
indirect case reference(Reference<Schema>)
indirect case object(ObjectSchema)
indirect case array(ArraySchema)
indirect case group(GroupSchema)
case boolean
case string(StringSchema)
case number(NumberSchema)
case integer(IntegerSchema)
case any
public var object: ObjectSchema? {
switch self {
case let .object(schema): return schema
default: return nil
}
}
public var reference: Reference<Schema>? {
switch self {
case let .reference(reference): return reference
default: return nil
}
}
public var isPrimitive: Bool {
switch self {
case .boolean, .string, .number, .integer: return true
case .reference, .object, .array, .group, .any: return false
}
}
}
extension Schema: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
metadata = try Metadata(jsonDictionary: jsonDictionary)
type = try SchemaType(jsonDictionary: jsonDictionary)
}
}
extension SchemaType: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
if jsonDictionary["$ref"] != nil {
self = .reference(try Reference(jsonDictionary: jsonDictionary))
} else if jsonDictionary["allOf"] != nil {
let group = try GroupSchema(jsonDictionary: jsonDictionary, type: .all)
self = .group(group)
} else if jsonDictionary["anyOf"] != nil {
let group = try GroupSchema(jsonDictionary: jsonDictionary, type: .any)
self = .group(group)
} else if jsonDictionary["oneOf"] != nil {
let group = try GroupSchema(jsonDictionary: jsonDictionary, type: .one)
self = .group(group)
} else if let dataType = DataType(jsonDictionary: jsonDictionary){
switch dataType {
case .array:
self = .array(try ArraySchema(jsonDictionary: jsonDictionary))
case .object:
self = .object(try ObjectSchema(jsonDictionary: jsonDictionary))
case .string:
self = .string(StringSchema(jsonDictionary: jsonDictionary))
case .number:
self = .number(NumberSchema(jsonDictionary: jsonDictionary))
case .integer:
self = .integer(IntegerSchema(jsonDictionary: jsonDictionary))
case .boolean:
self = .boolean
}
} else {
self = .any
}
}
}
| mit | 606ac80a9a8c3f1294c99e381bfa3329 | 31.172414 | 83 | 0.614148 | 5.016129 | false | false | false | false |
jnutting/TextShooter | TextShooter/ProductSpecFetcher.swift | 1 | 4592 | //
// ProductSpecFetcher.swift
// TextShooter
//
// Created by JN on 2017-4-19.
// Copyright © 2017 Apress. All rights reserved.
//
import Foundation
@objc protocol ProductSpecFetcherDelegate {
func productSpecFetcher(_ fetcher: ProductSpecFetcher, fetchedSpecsToUrl: URL)
func productSpecFetcher(_ fetcher: ProductSpecFetcher, failedWithError: Error)
}
class ProductSpecFetcher: NSObject {
weak var delegate: ProductSpecFetcherDelegate?
let filename: String
let remoteURL: URL
init(with delegate: ProductSpecFetcherDelegate?, filename: String, remoteURL: URL) {
self.filename = filename
self.remoteURL = remoteURL
super.init()
self.delegate = delegate
startFetching()
}
func filePathForLocalProductSpecs() -> URL {
let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentPath = searchPaths[0]
var documentUrl = URL(fileURLWithPath: documentPath)
documentUrl.appendPathComponent("\(filename).json")
return documentUrl
}
func productClusters() -> [TBTProductCluster]? {
guard let urls = productSpecUrls() else { return nil }
return productClustersFromFirstValidOfUrls(urls)
}
func productClustersFromFirstValidOfUrls(_ urls: [URL]) -> [TBTProductCluster]? {
for url in urls {
do {
let data = try Data.init(contentsOf: url)
let productSpecs = try productSpecsFromData(data)
if let productClusters = TBTProductCluster.productClusters(fromSpecs: productSpecs) as? [TBTProductCluster] {
return productClusters
}
} catch {
continue
}
}
return nil
}
func productSpecUrls() -> [URL]? {
let bundledUrl = Bundle.main.url(forResource: filename, withExtension: "json")!
let downloadedUrl = filePathForLocalProductSpecs()
let fm = FileManager.default
if !fm.isReadableFile(atPath: downloadedUrl.path) {
return [bundledUrl]
}
let downloadedAttrs: [FileAttributeKey : Any]
do {
downloadedAttrs = try fm.attributesOfItem(atPath: downloadedUrl.path)
} catch {
return [bundledUrl]
}
let bundledAttrs: [FileAttributeKey : Any]
do {
bundledAttrs = try fm.attributesOfItem(atPath: bundledUrl.path)
} catch {
return nil
}
if (bundledAttrs[FileAttributeKey.modificationDate] as! Date) < (downloadedAttrs[FileAttributeKey.modificationDate] as! Date) {
return [downloadedUrl, bundledUrl]
} else {
return [bundledUrl, downloadedUrl]
}
}
}
enum ProductSpecError: Error {
case dataIsNotDictionary
case dictionaryContainsNoProductSpecs
}
func productSpecsFromData(_ data: Data) throws -> [NSDictionary] {
do {
guard let dict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary else { throw ProductSpecError.dataIsNotDictionary }
guard let specs = dict["productSpecs"] as? [NSDictionary] else { throw ProductSpecError.dictionaryContainsNoProductSpecs }
return specs
} catch {
print("failed to find correct data: \(error)")
throw error
}
}
fileprivate extension ProductSpecFetcher {
func startFetching() {
let request = URLRequest(url: remoteURL)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) { [weak self] (response, data, error) in
guard let strongSelf = self else { return }
if let error = error {
print("fetch failed, error \(error)")
strongSelf.delegate?.productSpecFetcher(strongSelf, failedWithError: error)
return
} else if let data = data {
let savedUrl = strongSelf.filePathForLocalProductSpecs()
do {
// sanity check to make sure we got back something useful
let _ = try productSpecsFromData(data)
try data.write(to: savedUrl)
} catch {
print("Error dealing with remote JSON: \(error)")
strongSelf.delegate?.productSpecFetcher(strongSelf, failedWithError: error)
return
}
strongSelf.delegate?.productSpecFetcher(strongSelf, fetchedSpecsToUrl: savedUrl)
}
}
}
}
| mit | 869c33132782c55a4b37e9811c02276a | 33.518797 | 151 | 0.625572 | 4.925966 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/NaturalLanguageUnderstandingV1/Models/EntitiesOptions.swift | 1 | 3131 | /**
* (C) Copyright IBM Corp. 2017, 2020.
*
* 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
/**
Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types
and
subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types).
Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic,
Chinese, and Dutch are supported only through custom models.
*/
public struct EntitiesOptions: Codable, Equatable {
/**
Maximum number of entities to return.
*/
public var limit: Int?
/**
Set this to `true` to return locations of entity mentions.
*/
public var mentions: Bool?
/**
Enter a [custom
model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
ID to override the standard entity detection model.
*/
public var model: String?
/**
Set this to `true` to return sentiment information for detected entities.
*/
public var sentiment: Bool?
/**
Set this to `true` to analyze emotion for detected keywords.
*/
public var emotion: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case limit = "limit"
case mentions = "mentions"
case model = "model"
case sentiment = "sentiment"
case emotion = "emotion"
}
/**
Initialize a `EntitiesOptions` with member variables.
- parameter limit: Maximum number of entities to return.
- parameter mentions: Set this to `true` to return locations of entity mentions.
- parameter model: Enter a [custom
model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
ID to override the standard entity detection model.
- parameter sentiment: Set this to `true` to return sentiment information for detected entities.
- parameter emotion: Set this to `true` to analyze emotion for detected keywords.
- returns: An initialized `EntitiesOptions`.
*/
public init(
limit: Int? = nil,
mentions: Bool? = nil,
model: String? = nil,
sentiment: Bool? = nil,
emotion: Bool? = nil
)
{
self.limit = limit
self.mentions = mentions
self.model = model
self.sentiment = sentiment
self.emotion = emotion
}
}
| apache-2.0 | 461909d199a1a09599391c365a60053f | 33.032609 | 122 | 0.679974 | 4.472857 | false | false | false | false |
JoeLago/MHGDB-iOS | Pods/GRDB.swift/GRDB/Migration/DatabaseMigrator.swift | 2 | 8521 | /// A DatabaseMigrator registers and applies database migrations.
///
/// Migrations are named blocks of SQL statements that are guaranteed to be
/// applied in order, once and only once.
///
/// When a user upgrades your application, only non-applied migration are run.
///
/// Usage:
///
/// var migrator = DatabaseMigrator()
///
/// // v1.0 database
/// migrator.registerMigration("createAuthors") { db in
/// try db.execute("""
/// CREATE TABLE authors (
/// id INTEGER PRIMARY KEY,
/// creationDate TEXT,
/// name TEXT NOT NULL
/// )
/// """)
/// }
///
/// migrator.registerMigration("createBooks") { db in
/// try db.execute("""
/// CREATE TABLE books (
/// uuid TEXT PRIMARY KEY,
/// authorID INTEGER NOT NULL
/// REFERENCES authors(id)
/// ON DELETE CASCADE ON UPDATE CASCADE,
/// title TEXT NOT NULL
/// )
/// """)
/// }
///
/// // v2.0 database
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
/// }
///
/// try migrator.migrate(dbQueue)
public struct DatabaseMigrator {
/// A new migrator.
public init() {
}
/// Registers a migration.
///
/// migrator.registerMigration("createPlayers") { db in
/// try db.execute("""
/// CREATE TABLE players (
/// id INTEGER PRIMARY KEY,
/// creationDate TEXT,
/// name TEXT NOT NULL
/// )
/// """)
/// }
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, migrate: migrate))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.execute("""
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
/// INSERT INTO new_players SELECT * FROM players;
/// DROP TABLE players;
/// ALTER TABLE new_players RENAME TO players;
/// """)
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#else
@available(iOS 8.2, OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.execute("""
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
/// INSERT INTO new_players SELECT * FROM players;
/// DROP TABLE players;
/// ALTER TABLE new_players RENAME TO players;
/// """)
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#endif
/// Iterate migrations in the same order as they were registered. If a
/// migration has not yet been applied, its block is executed in
/// a transaction.
///
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ writer: DatabaseWriter) throws {
try writer.write { db in
try setupMigrations(db)
try runMigrations(db)
}
}
/// Iterate migrations in the same order as they were registered, up to the
/// provided target. If a migration has not yet been applied, its block is
/// executed in a transaction.
///
/// - parameter db: A DatabaseWriter (DatabaseQueue or DatabasePool) where
/// migrations should apply.
/// - targetIdentifier: The identifier of a registered migration.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
try writer.write { db in
try setupMigrations(db)
try runMigrations(db, upTo: targetIdentifier)
}
}
// MARK: - Non public
private var migrations: [Migration] = []
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))")
migrations.append(migration)
}
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func appliedIdentifiers(_ db: Database) throws -> Set<String> {
return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations"))
}
private func runMigrations(_ db: Database) throws {
let appliedIdentifiers = try self.appliedIdentifiers(db)
for migration in migrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
}
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
var prefixMigrations: [Migration] = []
for migration in migrations {
prefixMigrations.append(migration)
if migration.identifier == targetIdentifier {
break
}
}
// targetIdentifier must refer to a registered migration
GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))")
// Subsequent migration must not be applied
let appliedIdentifiers = try self.appliedIdentifiers(db)
if prefixMigrations.count < migrations.count {
let nextIdentifier = migrations[prefixMigrations.count].identifier
GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
try migration.run(db)
}
}
}
| mit | f2701bc491c6eb63e4deb8530a3cab76 | 42.253807 | 168 | 0.601221 | 5.021214 | false | false | false | false |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift语法/main.swift | 1 | 4337 | //
// main.swift
// Swift语法
//
// Created by ST on 16/4/29.
// Copyright © 2016年 shentian. All rights reserved.
import Foundation
print("Hello, World!")
//1 数组中的每个元素乘以2
//let array0 = [1,9,34]
let array0 = (1...4)
let array1 = array0.map{$0 * 2}
print("\(__FUNCTION__) \(array0)")
print("\(__FUNCTION__) \(array1)")
print("\(__FUNCTION__) \("--------------------------------")")
//2 数组中的元素求和
let arrayString = ["s", "z", "l"]
let sumString = arrayString.reduce("st", combine: +)
print("\(__FUNCTION__) \(sumString)")
let sum = array0.reduce(5, combine: *)
print("\(__FUNCTION__) \(sum)")
print("\(__FUNCTION__) \("--------------------------------")")
//3 验证在字符串中是否存在指定单词
let words = ["Swift","iOS","cocoa","OSX","tvOS"]
let tweet = "This is an example tweet larking about Swift"
let valid = !words.filter({tweet.containsString($0)}).isEmpty
let valid0 = words.contains(tweet.containsString)
let valid1 = tweet.characters.split(" ").lazy.map(String.init).contains(Set(words).contains)
print("\(__FUNCTION__) \(valid)")
print("\(__FUNCTION__) \(valid0)")
print("\(__FUNCTION__) \(valid1)")
print("\(__FUNCTION__) \("--------------------------------")")
//5 祝你生日快乐!
let name = "uraimo"
let string = (0...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear \(name)":"to You"))}
print("\(__FUNCTION__) \(string)")
print("\(__FUNCTION__) \("--------------------------------")")
//6 过滤数组中的数字
extension SequenceType{
typealias Element = Self.Generator.Element
func partitionBy(fu: (Element)->Bool) -> ([Element],[Element]){
var first=[Element]()
var second=[Element]()
for el in self {
if fu(el) {
first.append(el)
}else{
second.append(el)
}
}
return (first,second)
}
}
let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60}
print("\(__FUNCTION__) \(part)")
extension SequenceType{
func anotherPartitionBy(fu: (Self.Generator.Element)->Bool)->([Self.Generator.Element],[Self.Generator.Element]){
return (self.filter(fu),self.filter({!fu($0)}))
}
}
let part2 = [82, 58, 76, 49, 88, 90].anotherPartitionBy{$0 < 60}
print("\(__FUNCTION__) \(part2)")
//???
var part3 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), combine: {
(a:([Int],[Int]),n:Int) -> ([Int],[Int]) in
(n<60) ? (a.0+[n],a.1) : (a.0,a.1+[n])
})
print("\(__FUNCTION__) \(part3)")
print("\(__FUNCTION__) \("--------------------------------")")
//Find the minimum of an array of Ints
print( [10,-22,753,55,137,-1,-279,1034,77].sort().first! )
print( [10,-22,753,55,137,-1,-279,1034,77].reduce(Int.max, combine: min) )
print( [10,-22,753,55,137,-1,-279,1034,77].minElement()! )
//Find the maximum of an array of Ints
print( [10,-22,753,55,137,-1,-279,1034,77].sort().last! )
print( [10,-22,753,55,137,-1,-279,1034,77].reduce(Int.min, combine: max) )
print( [10,-22,753,55,137,-1,-279,1034,77].maxElement()! )
//9 并行处理
//某些语言允许用一种简单和透明的方式启用数组对功能,例如map和flatMap的并行处理,以加快顺序和独立操作的执行。
//
//此功能Swift中还不可用,但可以使用GCD构建:http://moreindirection.blogspot.it/2015/07/gcd-and-parallel-collections-in-swift.html
//
//10 找质数
NSLog("%s", __FUNCTION__)
//2016-04-29 11:47:12.991
//2016-04-29 11:47:13.031
var n = 15
var primes = Set(2...n)
(2...Int(sqrt(Double(n)))).forEach{primes.subtractInPlace((2*$0).stride(through:n, by:$0))}
//primes.sort()
NSLog("%s", __FUNCTION__)
print("\(__FUNCTION__) \(primes.sort())")
NSLog("%s", __FUNCTION__)
var sameprimes = Set(2...n)
sameprimes.subtractInPlace((2...Int(sqrt(Double(n))))
.flatMap{ (2*$0).stride(through:n, by:$0)})
//sameprimes.sort()
print("\(__FUNCTION__) \(sameprimes.sort())")
//11 其他:通过解构元组交换
var a="asdfasdfa",b="f345345342"
//a = a^b
//b = a^b
//a = a^b
//
//a = a + b
//b = a - b
//a = a - b
var array = [a , b];
//array.replaceRange(<#T##subRange: Range<Int>##Range<Int>#>, with: <#T##CollectionType#>)
print("\(__FUNCTION__) \(a)")
print("\(__FUNCTION__) \(b)")
(a,b) = (b,a)
//a //2
//b //1
print("\(__FUNCTION__) \(a)")
print("\(__FUNCTION__) \(b)")
| mit | 9b9994f062fb4b5a21f1f33754b70e37 | 21.726257 | 117 | 0.561455 | 2.956395 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Voip/Views/Fragments/PausedCallOrConferenceView.swift | 1 | 2629 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import SnapKit
import linphonesw
class PausedCallOrConferenceView: UIView {
// Layout constants
let icon_size = 200
let icon_padding = 80.0
let title_margin_top = 20
var icon : UIImageView? = nil
let title = StyledLabel(VoipTheme.call_or_conference_title)
let subtitle = StyledLabel(VoipTheme.call_or_conference_subtitle)
var onClickAction : (()->Void)? = nil
required init?(coder: NSCoder) {
super.init(coder: coder)
}
init (iconName:String, titleText:String, subTitleText:String? = nil, onClickAction : (()->Void)? = nil) {
super.init(frame: .zero)
backgroundColor = VoipTheme.voip_translucent_popup_background
accessibilityIdentifier = "paused_call_view"
accessibilityViewIsModal = true
let centeredView = UIView()
icon = UIImageView(image: UIImage(named:iconName)?.withPadding(padding: icon_padding))
icon!.backgroundColor = VoipTheme.primary_color
icon!.layer.cornerRadius = CGFloat(icon_size/2)
icon!.clipsToBounds = true
icon!.contentMode = .scaleAspectFit
centeredView.addSubview(icon!)
icon!.square(icon_size).centerX().done()
icon?.accessibilityIdentifier = "paused_call_view_icon"
title.numberOfLines = 0
centeredView.addSubview(title)
title.alignUnder(view:icon!, withMargin:title_margin_top).matchParentSideBorders().done()
title.text = titleText
subtitle.numberOfLines = 0
centeredView.addSubview(subtitle)
subtitle.alignUnder(view: title).matchParentSideBorders().done()
subtitle.text = subTitleText
self.addSubview(centeredView)
centeredView.center().matchParentSideBorders().wrapContentY().done()
self.onClickAction = onClickAction
icon!.onClick {
self.onClickAction?()
}
self.onClickAction = onClickAction
icon!.onClick {
self.onClickAction?()
}
}
}
| gpl-3.0 | 3c1a5053da3a6f7a2fc1d1af4b65fe26 | 29.929412 | 107 | 0.723849 | 3.883309 | false | false | false | false |
assist-group/assist-mcommerce-sdk-ios | AssistMobileTest/AssistMobile/ApplePayService.swift | 1 | 4737 | //
// ApplePayService.swift
// AssistMobileTest
//
// Created by Sergey Kulikov on 27.12.16.
// Copyright © 2016 Assist. All rights reserved.
//
import Foundation
import PassKit
class ApplePayService: NSObject, URLSessionDelegate {
fileprivate var data: PayData
fileprivate var delegate: AssistPayDelegate
fileprivate var completion: (PKPaymentAuthorizationStatus) -> Void
init(requestData: PayData, delegate: AssistPayDelegate, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
data = requestData
self.delegate = delegate
self.completion = completion
}
func start() {
run(data)
}
func getUrl(byOrder: Bool) -> String {
let servicePath = byOrder ? AssistLinks.ApplePayByOrderService : AssistLinks.ApplePayService
return AssistLinks.currentHost + servicePath
}
fileprivate func run(_ request: PayData) {
let byOrder = !((request.link ?? "").isEmpty)
let requestData = request.buldRequest(URL(string: getUrl(byOrder: byOrder))!)
//print("\(requestData.httpMethod ?? "") \(requestData.url)")
//let str = String(decoding: requestData.httpBody!, as: UTF8.self)
//print("BODY \n \(str)")
//print("HEADERS \n \(requestData.allHTTPHeaderFields)")
let sessionConfiguration = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: requestData) { sessionData, response, error in
do {
guard let sessionData = sessionData, error == nil else {
DispatchQueue.main.async {
self.completion(PKPaymentAuthorizationStatus.failure)
self.delegate.payFinished("", status: "Unknown", message: error as! String?)
}
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
DispatchQueue.main.async {
self.delegate.payFinished("", status: "Unknown", message: "Bad status code: \(httpStatus.statusCode)")
self.completion(PKPaymentAuthorizationStatus.failure)
}
}
//let da = String(data: sessionData, encoding: .utf8)
//print("full response is \(da)")
var status = PKPaymentAuthorizationStatus.failure
var paymentStatus = "Unknown"
var message = "Can not get result"
var billnumber = ""
if let json = try JSONSerialization.jsonObject(with: sessionData) as? [String:Any] {
//print("response is \(json)")
if let orders = json["order"] as? [Any] {
if let order = orders[0] as? [String:Any] {
if let operations = order["operations"] as? [Any] {
if let operation = operations[0] as? [String:Any] {
message = operation["message"] as? String ?? ""
}
}
paymentStatus = order["orderstate"] as? String ?? "Unknown"
billnumber = order["billnumber"] as? String ?? ""
}
} else {
if let firstcode = json["firstcode"] as? Int {
let secondcode = json["secondcode"] as? Int
message = "firstcode: \(firstcode), secondcode: \(String(describing: secondcode))"
}
}
}
if paymentStatus == "Approved" {
status = PKPaymentAuthorizationStatus.success
}
DispatchQueue.main.async {
self.completion(status)
self.delegate.payFinished(billnumber, status: paymentStatus, message: message)
}
} catch let error {
print (error.localizedDescription)
}
}
task.resume()
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
}
| apache-2.0 | f90bf7b277beb3cb252fb640402a3d65 | 42.851852 | 186 | 0.542019 | 5.611374 | false | false | false | false |
iOS-mamu/SS | P/Potatso/HomeVC.swift | 1 | 9916 | //
// IndexViewController.swift
// Potatso
//
// Created by LEI on 5/27/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import PotatsoLibrary
import PotatsoModel
import Eureka
import ICDMaterialActivityIndicatorView
import Cartography
private let kFormName = "name"
private let kFormDNS = "dns"
private let kFormProxies = "proxies"
private let kFormDefaultToProxy = "defaultToProxy"
class HomeVC: FormViewController, UINavigationControllerDelegate, HomePresenterProtocol, UITextFieldDelegate {
let presenter = HomePresenter()
var ruleSetSection: Section!
var status: VPNStatus {
didSet(o) {
updateConnectButton()
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self.status = .off
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
presenter.bindToVC(self)
presenter.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Fix a UI stuck bug
navigationController?.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.titleView = titleButton
// Post an empty message so we could attach to packet tunnel process
Manager.sharedManager.postMessage()
handleRefreshUI()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: "List".templateImage, style: .plain, target: presenter, action: #selector(HomePresenter.chooseConfigGroups))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: presenter, action: #selector(HomePresenter.showAddConfigGroup))
}
// MARK: - HomePresenter Protocol
func handleRefreshUI() {
if presenter.group.isDefault {
status = Manager.sharedManager.vpnStatus
}else {
status = .off
}
updateTitle()
updateForm()
}
func updateTitle() {
titleButton.setTitle(presenter.group.name, for: .normal)
titleButton.sizeToFit()
}
func updateForm() {
form.delegate = nil
form.removeAll()
form +++ generateProxySection()
form +++ generateRuleSetSection()
form.delegate = self
tableView?.reloadData()
}
func updateConnectButton() {
connectButton.isEnabled = [VPNStatus.on, VPNStatus.off].contains(status)
connectButton.setTitleColor(UIColor.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: UIControlState())
switch status {
case .connecting, .disconnecting:
connectButton.animating = true
default:
connectButton.setTitle(status.hintDescription, for: .normal)
connectButton.animating = false
}
connectButton.backgroundColor = status.color
}
// MARK: - Form
func generateProxySection() -> Section {
let proxySection = Section()
if let proxy = presenter.proxy {
proxySection <<< ProxyRow(kFormProxies) {
$0.value = proxy
}.cellSetup({ (cell, row) -> () in
cell.accessoryType = .disclosureIndicator
cell.selectionStyle = .default
}).onCellSelection({ [unowned self](cell, row) -> () in
cell.setSelected(false, animated: true)
self.presenter.chooseProxy()
})
}else {
proxySection <<< LabelRow() {
$0.title = "Proxy".localized()
$0.value = "None".localized()
}.cellSetup({ (cell, row) -> () in
cell.accessoryType = .disclosureIndicator
cell.selectionStyle = .default
}).onCellSelection({ [unowned self](cell, row) -> () in
cell.setSelected(false, animated: true)
self.presenter.chooseProxy()
})
}
proxySection <<< SwitchRow(kFormDefaultToProxy) {
$0.title = "Default To Proxy".localized()
$0.value = presenter.group.defaultToProxy
$0.hidden = Condition.function([kFormProxies]) { [unowned self] form in
return self.presenter.proxy == nil
}
}.onChange({ [unowned self] (row) in
do {
try defaultRealm.write {
self.presenter.group.defaultToProxy = row.value ?? true
}
}catch {
self.showTextHUD("\("Fail to modify default to proxy".localized()): \((error as NSError).localizedDescription)", dismissAfterDelay: 1.5)
}
})
<<< TextRow(kFormDNS) {
$0.title = "DNS".localized()
$0.value = presenter.group.dns
}.cellSetup { cell, row in
cell.textField.placeholder = "System DNS".localized()
cell.textField.autocorrectionType = .no
cell.textField.autocapitalizationType = .none
}
return proxySection
}
func generateRuleSetSection() -> Section {
ruleSetSection = Section("Rule Set".localized())
for ruleSet in presenter.group.ruleSets {
ruleSetSection
<<< LabelRow () {
$0.title = "\(ruleSet.name)"
var count = 0
if ruleSet.ruleCount > 0 {
count = ruleSet.ruleCount
}else {
count = ruleSet.rules.count
}
if count > 1 {
$0.value = String(format: "%d rules".localized(), count)
}else {
$0.value = String(format: "%d rule".localized(), count)
}
}.cellSetup({ (cell, row) -> () in
cell.selectionStyle = .none
})
}
ruleSetSection <<< BaseButtonRow () {
$0.title = "Add Rule Set".localized()
}.onCellSelection({ [unowned self] (cell, row) -> () in
self.presenter.addRuleSet()
})
return ruleSetSection
}
// MARK: - Private Actions
func handleConnectButtonPressed() {
if status == .on {
status = .disconnecting
}else {
status = .connecting
}
presenter.switchVPN()
}
func handleTitleButtonPressed() {
presenter.changeGroupName()
}
// MARK: - TableView
func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool {
if indexPath.section == ruleSetSection.index && indexPath.row < presenter.group.ruleSets.count {
return true
}
return false
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
if editingStyle == .delete {
do {
try defaultRealm.write {
presenter.group.ruleSets.remove(at: indexPath.row)
}
form[indexPath].hidden = true
form[indexPath].evaluateHidden()
}catch {
self.showTextHUD("\("Fail to delete item".localized()): \((error as NSError).localizedDescription)", dismissAfterDelay: 1.5)
}
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAtIndexPath indexPath: IndexPath) -> UITableViewCellEditingStyle {
return .delete
}
// MARK: - TextRow
override func textInputDidEndEditing<T>(_ textInput: UITextInput, cell: Cell<T>) {
guard let textField = textInput as? UITextField, let dnsString = textField.text, cell.row.tag == kFormDNS else {
return
}
presenter.updateDNS(dnsString)
textField.text = presenter.group.dns
}
// MARK: - View Setup
fileprivate let connectButtonHeight: CGFloat = 48
override func loadView() {
super.loadView()
view.backgroundColor = Color.Background
view.addSubview(connectButton)
setupLayout()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.bringSubview(toFront: connectButton)
tableView?.contentInset = UIEdgeInsetsMake(0, 0, connectButtonHeight, 0)
}
func setupLayout() {
constrain(connectButton, view) { connectButton, view in
connectButton.trailing == view.trailing
connectButton.leading == view.leading
connectButton.height == connectButtonHeight
connectButton.bottom == view.bottom
}
}
lazy var connectButton: FlatButton = {
let v = FlatButton(frame: CGRect.zero)
v.addTarget(self, action: #selector(HomeVC.handleConnectButtonPressed), for: .touchUpInside)
return v
}()
lazy var titleButton: UIButton = {
let b = UIButton(type: .custom)
b.setTitleColor(UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0), for: UIControlState())
b.addTarget(self, action: #selector(HomeVC.handleTitleButtonPressed), for: .touchUpInside)
if let titleLabel = b.titleLabel {
titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)
}
return b
}()
}
extension VPNStatus {
var color: UIColor {
switch self {
case .on, .disconnecting:
return Color.StatusOn
case .off, .connecting:
return Color.StatusOff
}
}
var hintDescription: String {
switch self {
case .on, .disconnecting:
return "Disconnect".localized()
case .off, .connecting:
return "Connect".localized()
}
}
}
| mit | 72b764385e9781f061295d22b605fc1a | 32.383838 | 174 | 0.587191 | 4.950075 | false | false | false | false |
mapsme/omim | iphone/Maps/Classes/CarPlay/Template Builders/MapTemplateBuilder.swift | 6 | 8759 | import CarPlay
@available(iOS 12.0, *)
final class MapTemplateBuilder {
enum MapButtonType {
case startPanning
case zoomIn
case zoomOut
}
enum BarButtonType {
case dismissPaning
case destination
case recenter
case settings
case mute
case unmute
case redirectRoute
case endRoute
}
// MARK: - CPMapTemplate builders
class func buildBaseTemplate(positionMode: MWMMyPositionMode) -> CPMapTemplate {
let mapTemplate = CPMapTemplate()
mapTemplate.hidesButtonsWithNavigationBar = false
configureBaseUI(mapTemplate: mapTemplate)
if positionMode == .pendingPosition {
mapTemplate.leadingNavigationBarButtons = []
} else if positionMode == .follow || positionMode == .followAndRotate {
setupDestinationButton(mapTemplate: mapTemplate)
} else {
setupRecenterButton(mapTemplate: mapTemplate)
}
return mapTemplate
}
class func buildNavigationTemplate() -> CPMapTemplate {
let mapTemplate = CPMapTemplate()
mapTemplate.hidesButtonsWithNavigationBar = false
configureNavigationUI(mapTemplate: mapTemplate)
return mapTemplate
}
class func buildTripPreviewTemplate(forTrips trips: [CPTrip]) -> CPMapTemplate {
let mapTemplate = CPMapTemplate()
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.preview, trips: trips)
mapTemplate.mapButtons = []
mapTemplate.leadingNavigationBarButtons = []
let settingsButton = buildBarButton(type: .settings) { _ in
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.previewSettings)
let gridTemplate = SettingsTemplateBuilder.buildGridTemplate()
CarPlayService.shared.pushTemplate(gridTemplate, animated: true)
Statistics.logEvent(kStatCarplaySettingsOpen, withParameters: [kStatFrom : kStatOverview])
}
mapTemplate.trailingNavigationBarButtons = [settingsButton]
return mapTemplate
}
// MARK: - MapTemplate UI configs
class func configureBaseUI(mapTemplate: CPMapTemplate) {
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.main)
let panningButton = buildMapButton(type: .startPanning) { _ in
mapTemplate.showPanningInterface(animated: true)
}
let zoomInButton = buildMapButton(type: .zoomIn) { _ in
FrameworkHelper.zoomMap(.in)
Alohalytics.logEvent(kStatCarplayZoom, with: [kStatIsZoomIn : true,
kStatIsPanActivated: false])
}
let zoomOutButton = buildMapButton(type: .zoomOut) { _ in
FrameworkHelper.zoomMap(.out)
Alohalytics.logEvent(kStatCarplayZoom, with: [kStatIsZoomIn : false,
kStatIsPanActivated: false])
}
mapTemplate.mapButtons = [panningButton, zoomInButton, zoomOutButton]
let settingsButton = buildBarButton(type: .settings) { _ in
let gridTemplate = SettingsTemplateBuilder.buildGridTemplate()
CarPlayService.shared.pushTemplate(gridTemplate, animated: true)
Statistics.logEvent(kStatCarplaySettingsOpen, withParameters: [kStatFrom : kStatMap])
}
mapTemplate.trailingNavigationBarButtons = [settingsButton]
}
class func configurePanUI(mapTemplate: CPMapTemplate) {
let zoomInButton = buildMapButton(type: .zoomIn) { _ in
FrameworkHelper.zoomMap(.in)
Alohalytics.logEvent(kStatCarplayZoom, with: [kStatIsZoomIn : true,
kStatIsPanActivated: true])
}
let zoomOutButton = buildMapButton(type: .zoomOut) { _ in
FrameworkHelper.zoomMap(.out)
Alohalytics.logEvent(kStatCarplayZoom, with: [kStatIsZoomIn : false,
kStatIsPanActivated: true])
}
mapTemplate.mapButtons = [zoomInButton, zoomOutButton]
let doneButton = buildBarButton(type: .dismissPaning) { _ in
mapTemplate.dismissPanningInterface(animated: true)
Alohalytics.logEvent(kStatCarplayPanDeactivated, with: [kStatUsedButtons: CarPlayService.shared.isUserPanMap])
}
mapTemplate.leadingNavigationBarButtons = []
mapTemplate.trailingNavigationBarButtons = [doneButton]
Alohalytics.logEvent(kStatCarplayPanActivated)
}
class func configureNavigationUI(mapTemplate: CPMapTemplate) {
mapTemplate.userInfo = MapInfo(type: CPConstants.TemplateType.navigation)
let panningButton = buildMapButton(type: .startPanning) { _ in
mapTemplate.showPanningInterface(animated: true)
}
mapTemplate.mapButtons = [panningButton]
setupMuteAndRedirectButtons(template: mapTemplate)
let endButton = buildBarButton(type: .endRoute) { _ in
CarPlayService.shared.cancelCurrentTrip()
}
mapTemplate.trailingNavigationBarButtons = [endButton]
}
// MARK: - Conditional navigation buttons
class func setupDestinationButton(mapTemplate: CPMapTemplate) {
let destinationButton = buildBarButton(type: .destination) { _ in
let listTemplate = ListTemplateBuilder.buildListTemplate(for: .history)
CarPlayService.shared.pushTemplate(listTemplate, animated: true)
Statistics.logEvent(kStatCarplayDestinationsOpen, withParameters: [kStatFrom : kStatMap])
}
mapTemplate.leadingNavigationBarButtons = [destinationButton]
}
class func setupRecenterButton(mapTemplate: CPMapTemplate) {
let recenterButton = buildBarButton(type: .recenter) { _ in
FrameworkHelper.switchMyPositionMode()
Alohalytics.logEvent(kStatCarplayRecenter)
}
mapTemplate.leadingNavigationBarButtons = [recenterButton]
}
private class func setupMuteAndRedirectButtons(template: CPMapTemplate) {
let muteButton = buildBarButton(type: .mute) { _ in
MWMTextToSpeech.setTTSEnabled(false)
setupUnmuteAndRedirectButtons(template: template)
}
let redirectButton = buildBarButton(type: .redirectRoute) { _ in
let listTemplate = ListTemplateBuilder.buildListTemplate(for: .history)
CarPlayService.shared.pushTemplate(listTemplate, animated: true)
Statistics.logEvent(kStatCarplayDestinationsOpen, withParameters: [kStatFrom : kStatNavigation])
}
template.leadingNavigationBarButtons = [muteButton, redirectButton]
}
private class func setupUnmuteAndRedirectButtons(template: CPMapTemplate) {
let unmuteButton = buildBarButton(type: .unmute) { _ in
MWMTextToSpeech.setTTSEnabled(true)
setupMuteAndRedirectButtons(template: template)
}
let redirectButton = buildBarButton(type: .redirectRoute) { _ in
let listTemplate = ListTemplateBuilder.buildListTemplate(for: .history)
CarPlayService.shared.pushTemplate(listTemplate, animated: true)
Statistics.logEvent(kStatCarplayDestinationsOpen, withParameters: [kStatFrom : kStatNavigation])
}
template.leadingNavigationBarButtons = [unmuteButton, redirectButton]
}
// MARK: - CPMapButton builder
private class func buildMapButton(type: MapButtonType, action: ((CPMapButton) -> Void)?) -> CPMapButton {
let button = CPMapButton(handler: action)
switch type {
case .startPanning:
button.image = UIImage(named: "btn_carplay_pan_light")
case .zoomIn:
button.image = UIImage(named: "btn_zoom_in_light")
case .zoomOut:
button.image = UIImage(named: "btn_zoom_out_light")
}
return button
}
// MARK: - CPBarButton builder
private class func buildBarButton(type: BarButtonType, action: ((CPBarButton) -> Void)?) -> CPBarButton {
switch type {
case .dismissPaning:
let button = CPBarButton(type: .text, handler: action)
button.title = L("done")
return button
case .destination:
let button = CPBarButton(type: .text, handler: action)
button.title = L("pick_destination")
return button
case .recenter:
let button = CPBarButton(type: .text, handler: action)
button.title = L("follow_my_position")
return button
case .settings:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_settings")
return button
case .mute:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_unmuted")
return button
case .unmute:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_muted")
return button
case .redirectRoute:
let button = CPBarButton(type: .image, handler: action)
button.image = UIImage(named: "ic_carplay_redirect_route")
return button
case .endRoute:
let button = CPBarButton(type: .text, handler: action)
button.title = L("navigation_stop_button").capitalized
return button
}
}
}
| apache-2.0 | 0f3f83bb9357af9bc671e24c8842d039 | 40.122066 | 116 | 0.709784 | 4.321164 | false | false | false | false |
aijaz/icw1502 | playgrounds/Week07Classes.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift | 1 | 2007 | class ConferenceAttendee {
let name: String
let hometown: String?
init(name: String, hometown: String? = nil) {
// Step 3: initialize all properties of this class
self.name = name
self.hometown = hometown
// Step 4: Do any other setup now that all properties are initialized properly
}
func nameBadge() -> String {
let greeting = "Hi. I'm \(name)"
guard let validHometown = hometown else {
return greeting + "."
}
return greeting + " from \(validHometown)."
// if let validHometown = hometown {
// return greeting + " from \(validHometown)"
// }
// else {
// return greeting + "."
// }
}
}
let aijaz = ConferenceAttendee(name: "Aijaz", hometown: "Chicago")
aijaz.nameBadge()
let adel = ConferenceAttendee(name: "Adel")
adel.nameBadge()
class TutorialAttendee : ConferenceAttendee {
let tutorial: String
init(name: String, tutorial: String, hometown: String? = nil) {
// Step 1: initialize all properties of the subclass
self.tutorial = tutorial
// ... other property initializationa
// Step 2: call init on the superclass
super.init(name: name, hometown: hometown)
// Step 5: Do any other setup now that all superclasses have done their setup
}
override func nameBadge() -> String {
return super.nameBadge() + " and I'm taking \(tutorial)"
}
}
let ayesha = TutorialAttendee(name: "Ayesha", tutorial: "Swift", hometown: "Denver")
ayesha.nameBadge()
let maazin = TutorialAttendee(name: "Maazin", tutorial: "TvOS")
maazin.nameBadge()
struct s {
let name: String
let hometown: String
init (name: String, hometown: String) {
self.name = name
self.hometown = hometown
}
init (name: String) {
self.init(name: name, hometown: "Chicago")
}
} | mit | d39915c0995a343ff311fe5dcc6ad5f7 | 21.561798 | 86 | 0.585949 | 4.022044 | false | false | false | false |
DroidsOnRoids/PhotosHelper | Example/PhotosHelper/ViewController.swift | 1 | 3819 | //
// ViewController.swift
// PhotosHelper
//
// Created by Andrzej Filipowicz on 12/03/2015.
// Copyright (c) 2015 Andrzej Filipowicz. All rights reserved.
//
import UIKit
import AVFoundation
import PhotosHelper
let padding: CGFloat = 10.0
class ViewController: UIViewController {
var captureSession: AVCaptureSession?
var captureLayer: AVCaptureVideoPreviewLayer?
let output = AVCaptureStillImageOutput()
override func viewDidLoad() {
super.viewDidLoad()
setupCamera()
setupUI()
}
func setupUI() {
view.clipsToBounds = true
let captureButton = UIButton()
captureButton.setTitle("take a picture", forState: .Normal)
captureButton.sizeToFit()
captureButton.addTarget(self, action: #selector(ViewController.takePicture(_:)), forControlEvents: .TouchUpInside)
captureButton.center = CGPoint(x: view.frame.midX, y: view.frame.height - captureButton.frame.midY - padding)
view.addSubview(captureButton)
}
func setupCamera() {
captureSession = AVCaptureSession()
guard let captureSession = captureSession else { return }
captureSession.beginConfiguration()
setDeviceInput()
if captureSession.canSetSessionPreset(AVCaptureSessionPresetHigh) {
captureSession.sessionPreset = AVCaptureSessionPresetHigh
}
if captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
captureLayer = AVCaptureVideoPreviewLayer(session: captureSession)
captureLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
captureLayer?.frame = view.bounds
guard let captureLayer = captureLayer else { return }
view.layer.addSublayer(captureLayer)
captureSession.commitConfiguration()
captureSession.startRunning()
}
private func setDeviceInput(back: Bool = true) {
guard let captureSession = captureSession else { return }
if let input = captureSession.inputs.first as? AVCaptureInput {
captureSession.removeInput(input)
}
let device = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
.filter {$0.position == (back ? .Back : .Front)}
.first as? AVCaptureDevice ?? AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
guard let input = try? AVCaptureDeviceInput(device: device) else { return }
if captureSession.canAddInput(input) {
captureSession.addInput(input)
}
}
func takePicture(sender: AnyObject) {
let connection = output.connectionWithMediaType(AVMediaTypeVideo)
output.captureStillImageAsynchronouslyFromConnection(connection) { [weak self] buffer, error in
guard let `self` = self where error == nil else { return }
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
guard let image = UIImage(data: imageData) else { return }
PhotosHelper.saveImage(image, toAlbum: "Example Album") { success, _ in
guard success else { return }
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Photo taken", message: "Open Photos.app to see that an album with your photo was created.", preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
}
}
| mit | 7a0a0cdf53112e68b4afc2ddf43966be | 35.028302 | 173 | 0.637601 | 5.717066 | false | false | false | false |
937447974/YJCocoa | Demo/OC/AppFrameworks/UIKit/YJTableView/YJTableView/YJTestTVCell.swift | 1 | 1277 | //
// YJTestTVCell.swift
// YJTableView
//
// Created by 阳君 on 2019/5/23.
// Copyright © 2019 YJCocoa. All rights reserved.
//
import UIKit
import YJCocoa
@objcMembers
class YJTestTVCellModel: NSObject {
var userName: String = ""
}
@objcMembers
class YJTestTVCell: YJUITableViewCell {
lazy var label: UILabel = {
return UILabel.init(frame: self.bounds)
}()
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.contentView.addSubview(self.label)
}
override func layoutSubviews() {
super.layoutSubviews()
self.label.frame = self.bounds
}
// MARK: YJCocoa
override class func tableViewManager(_ tableViewManager: YJUITableViewManager, heightWith cellObject: YJUITableCellObject) -> CGFloat {
return CGFloat(2 * cellObject.indexPath.row + 40)
}
override func tableViewManager(_ tableViewManager: YJUITableViewManager, reloadWith cellObject: YJUITableCellObject) {
super.tableViewManager(tableViewManager, reloadWith: cellObject)
guard let cm = cellObject.cellModel as? YJTestTVCellModel else {
return
}
self.label.text = cm.userName
}
}
| mit | c55eca667a14880972c84c1a803877ac | 26.06383 | 139 | 0.674528 | 4.57554 | false | true | false | false |
ustwo/videoplayback-ios | Source/View/Video/VPKPlaybackControlView.swift | 1 | 9207 | //
// VPKVideoToolBarView.swift
// VideoPlaybackKit
//
// Created by Sonam on 4/21/17.
// Copyright © 2017 ustwo. All rights reserved.
//
import Foundation
import UIKit
import MediaPlayer
import ASValueTrackingSlider
public class VPKPlaybackControlView: UIView {
//Protocol
weak var presenter: VPKVideoPlaybackPresenterProtocol?
var theme: ToolBarTheme = .normal
var progressValue: Float = 0.0 {
didSet {
DispatchQueue.main.async {
self.playbackProgressSlider.value = self.progressValue
}
}
}
var maximumSeconds: Float = 0.0 {
didSet {
playbackProgressSlider.maximumValue = maximumSeconds
}
}
//Private
fileprivate var playPauseButton = UIButton(frame: .zero)
private let fullScreen = UIButton(frame: .zero)
private let volumeCtrl = MPVolumeView()
private let expandButton = UIButton(frame: .zero)
fileprivate let timeProgressLabel = UILabel(frame: .zero)
fileprivate let durationLabel = UILabel(frame: .zero)
private let skipBackButton = UIButton(frame: .zero)
private let skipForwardButton = UIButton(frame: .zero)
private let bottomControlContainer = UIView(frame: .zero)
fileprivate let playbackProgressSlider = ASValueTrackingSlider(frame: .zero)
convenience init(theme: ToolBarTheme) {
self.init(frame: .zero)
self.theme = theme
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
playbackProgressSlider.dataSource = self
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
switch theme {
case .normal:
setupNormalColorTheme()
setupNormalLayout()
case .custom(bottomBackgroundColor: _, sliderBackgroundColor: _, sliderIndicatorColor: _, sliderCalloutColors: _):
setupNormalLayout()
setupCustomColorWith(theme: theme)
}
}
private func setupNormalColorTheme() {
bottomControlContainer.backgroundColor = VPKColor.backgroundiOS11Default.rgbColor
playbackProgressSlider.textColor = VPKColor.borderiOS11Default.rgbColor
playbackProgressSlider.backgroundColor = VPKColor.timeSliderBackground.rgbColor
playbackProgressSlider.popUpViewColor = .white
}
private func setupCustomColorWith(theme: ToolBarTheme) {
switch theme {
case let .custom(bottomBackgroundColor: bottomBGColor, sliderBackgroundColor: sliderBGColor, sliderIndicatorColor: sliderIndicatorColor, sliderCalloutColors: calloutColors):
self.bottomControlContainer.backgroundColor = bottomBGColor
self.playbackProgressSlider.backgroundColor = sliderBGColor
self.playbackProgressSlider.textColor = sliderIndicatorColor
self.playbackProgressSlider.popUpViewAnimatedColors = calloutColors
default:
break
}
}
private func setupNormalLayout() {
isUserInteractionEnabled = true
addSubview(bottomControlContainer)
bottomControlContainer.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(6.5)
make.right.equalTo(self).offset(-6.5)
make.height.equalTo(47)
make.bottom.equalTo(self.snp.bottom).offset(-6.5)
}
bottomControlContainer.layer.cornerRadius = 16.0
bottomControlContainer.layer.borderColor = VPKColor.borderiOS11Default.rgbColor.cgColor
bottomControlContainer.layer.borderWidth = 0.5
let blurContainer = UIView(frame: .zero)
bottomControlContainer.addSubview(blurContainer)
blurContainer.snp.makeConstraints { (make) in
make.edges.equalTo(bottomControlContainer)
}
blurContainer.backgroundColor = .clear
blurContainer.isUserInteractionEnabled = true
blurContainer.clipsToBounds = true
let blurEffect = self.defaultBlurEffect()
blurContainer.addSubview(blurEffect)
blurEffect.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
blurContainer.layer.cornerRadius = bottomControlContainer.layer.cornerRadius
bottomControlContainer.addSubview(playPauseButton)
playPauseButton.snp.makeConstraints { (make) in
make.left.equalTo(bottomControlContainer).offset(8.0)
make.centerY.equalTo(bottomControlContainer)
make.height.width.equalTo(28)
}
playPauseButton.setBackgroundImage(UIImage(named: PlayerState.paused.buttonImageName), for: .normal)
playPauseButton.contentMode = .scaleAspectFit
playPauseButton.addTarget(self, action: #selector(didTapPlayPause), for: .touchUpInside)
bottomControlContainer.addSubview(timeProgressLabel)
bottomControlContainer.addSubview(playbackProgressSlider)
timeProgressLabel.snp.makeConstraints { (make) in
make.left.equalTo(playPauseButton.snp.right).offset(8.0)
make.centerY.equalTo(bottomControlContainer)
make.right.equalTo(playbackProgressSlider.snp.left).offset(-6.0)
}
timeProgressLabel.textColor = UIColor(white: 1.0, alpha: 0.75)
timeProgressLabel.text = "0:00"
bottomControlContainer.addSubview(durationLabel)
playbackProgressSlider.snp.makeConstraints { (make) in
make.left.equalTo(timeProgressLabel.snp.right).offset(5.0)
make.right.equalTo(durationLabel.snp.left).offset(-5.0).priority(1000)
make.centerY.equalTo(bottomControlContainer)
make.height.equalTo(5.0)
}
playbackProgressSlider.addTarget(self, action: #selector(didScrub), for: .valueChanged)
playbackProgressSlider.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal)
playbackProgressSlider.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
bottomControlContainer.addSubview(durationLabel)
durationLabel.snp.makeConstraints { (make) in
make.right.equalTo(bottomControlContainer.snp.right).offset(-8.0)
make.centerY.equalTo(bottomControlContainer)
}
durationLabel.textColor = UIColor(white: 1.0, alpha: 0.75)
durationLabel.text = "0:00"
durationLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, for: .horizontal)
durationLabel.setContentHuggingPriority(UILayoutPriorityFittingSizeLevel, for: .horizontal)
addSubview(expandButton)
expandButton.layer.cornerRadius = 16.0
expandButton.backgroundColor = VPKColor.backgroundiOS11Default.rgbColor
expandButton.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(8.0)
make.width.equalTo(30)
make.height.equalTo(30)
make.top.equalTo(self).offset(8.0)
}
expandButton.setBackgroundImage(#imageLiteral(resourceName: "defaultExpand"), for: .normal)
expandButton.addTarget(self, action: #selector(didTapExpandView), for: .touchUpInside)
bottomControlContainer.setContentHuggingPriority(UILayoutPriorityDefaultHigh, for: .horizontal)
}
}
extension VPKPlaybackControlView: ASValueTrackingSliderDataSource {
public func slider(_ slider: ASValueTrackingSlider!, stringForValue value: Float) -> String! {
return presenter?.formattedProgressTime(from: TimeInterval(value))
}
}
extension VPKPlaybackControlView: VPKPlaybackControlViewProtocol {
func showDurationWith(_ time: String) {
durationLabel.text = time
layoutIfNeeded()
}
func didSkipBack(_ seconds: Float = 15.0) {
presenter?.didSkipBack(seconds)
}
func didSkipForward(_ seconds: Float = 15.0) {
presenter?.didSkipForward(seconds)
}
func updateTimePlayingCompletedTo(_ time: String) {
timeProgressLabel.text = time
}
func didScrub() {
#if DEBUG
print("USER SCRUBBED TO \(playbackProgressSlider.value)")
#endif
presenter?.didScrubTo(TimeInterval(playbackProgressSlider.value))
}
func didTapExpandView() {
presenter?.didExpand()
}
func toggleActionButton(_ imageName: String) {
DispatchQueue.main.async {
self.playPauseButton.setBackgroundImage(UIImage(named: imageName), for: .normal)
}
}
func didTapPlayPause() {
presenter?.didTapVideoView()
}
}
extension VPKPlaybackControlView {
func defaultBlurEffect() -> UIVisualEffectView {
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.clipsToBounds = true
return blurEffectView
}
}
| mit | d10bbdfdfb9ed5d87336c39f4d7edf4f | 35.971888 | 181 | 0.6738 | 5.047149 | false | false | false | false |
CrossWaterBridge/Mole | Mole/MoleServer.swift | 1 | 2815 | //
// Copyright (c) 2015 Hilton Campbell
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Swifter
public class MoleServer {
private let server = HttpServer()
public init() {
do {
try server.start()
} catch {}
}
public subscript(name: String) -> ((Any) throws -> Any?)? {
get {
return nil
}
set {
if let handler = newValue {
server["/" + name] = { request in
let body = request.body
let data = Data(bytes: body, count: body.count)
let parameters: Any
do {
parameters = try PropertyListSerialization.propertyList(from: data, options: [], format: nil)
} catch {
return .internalServerError
}
let response: Any
do {
response = try handler(parameters) ?? []
} catch {
return .internalServerError
}
do {
let data = try PropertyListSerialization.data(fromPropertyList: response, format: .xml, options: 0)
var array = [UInt8](repeating: 0, count: data.count)
data.copyBytes(to: &array, count: data.count)
return .raw(200, "OK", nil, { try $0.write(array) })
} catch {
return .internalServerError
}
}
} else {
server["/" + name] = nil
}
}
}
}
| mit | 8ebf574e226b90423a9e41a306311fbc | 37.561644 | 123 | 0.543872 | 5.281426 | false | false | false | false |
Szpyrol/LoyalMgr | Loyal mgr/SplashFlowCoordinator.swift | 1 | 1069 | //
// SplashFlowCoordinator.swift
// Loyal mgr
//
// Created by Łukasz Szpyrka on 15/04/2017.
// Copyright © 2017 Łukasz Szpyrka. All rights reserved.
//
import Foundation
import UIKit
class SplashFlowCoordinator: FlowCoordinator {
var configure:FlowConfigure!
required init(configure : FlowConfigure) {
self.configure = configure
}
func start() {
let storyboard = UIStoryboard(name: "SplashScreen", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"SplashViewController") as! SplashViewController
if let frame = configure.window?.bounds {
viewController.view.frame = frame
}
viewController.delegate = self
configure.window?.rootViewController = viewController
configure.window?.makeKeyAndVisible()
}
}
extension SplashFlowCoordinator:SplashViewControllerDelegate {
func splashViewControllerDidFinished() {
let mainFlow = MainFlowCoordinator(configure: configure)
mainFlow.start()
}
}
| mit | bf2740d4b3c7367e794f4f642ab40a7b | 27.052632 | 130 | 0.696998 | 5.052133 | false | true | false | false |
eugeneego/utilities-ios | Sources/Logger/ElasticLogger.swift | 1 | 6885 | //
// ElasticLogger
// Legacy
//
// Created by Alexander Babaev.
// Copyright (c) 2016 Eugene Egorov.
// License: MIT, https://github.com/eugeneego/legacy/blob/master/LICENSE
//
import Foundation
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#endif
/// Logger that sends data to the backend using Elastic Search API.
public class ElasticLogger: Logger {
private let environment: String
private let userParameters: () -> [String: String]
private let appAndSystemParameters: [String: String]
private let sender: Sender
public init(
http: Http,
baseUrl: URL,
token: String,
type: String,
environment: String,
deviceInfo: DeviceInfo,
userParameters: @escaping () -> [String: String] = { [:] }
) {
self.environment = environment
self.userParameters = userParameters
appAndSystemParameters = [
"device": deviceInfo.machineName,
"os": "\(deviceInfo.system) \(deviceInfo.systemVersion)",
"app": deviceInfo.bundleIdentifier,
"app_version": deviceInfo.bundleVersion,
"app_build": deviceInfo.bundleBuild,
"environment": environment,
]
sender = Sender(http: http, baseUrl: baseUrl, token: token, type: type)
}
public func start() {
Task {
await sender.start()
}
}
public func stop() {
Task {
await sender.stop()
}
}
private static let timestampFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
private func severity(for level: LoggingLevel) -> String {
switch level {
case .verbose:
return "verbose"
case .debug:
return "debug"
case .info:
return "info"
case .warning:
return "warn"
case .error:
return "err"
case .critical:
return "crit"
}
}
public func log(
_ message: @autoclosure () -> String,
meta: @autoclosure () -> [String: String],
level: LoggingLevel,
tag: String,
file: StaticString = #file,
function: StaticString = #function,
line: UInt = #line
) {
let timestamp = ElasticLogger.timestampFormatter.string(from: Date())
let message = message()
let meta = meta()
var logData: [String: String] = [
"@timestamp": timestamp,
"severity": severity(for: level),
"tag": tag,
"function": "\(function)",
"message": message,
]
meta.forEach { logData[$0.key] = $0.value }
appAndSystemParameters.forEach { logData[$0.key] = $0.value }
userParameters().forEach { logData[$0.key] = $0.value }
Task { [logData] in
await sender.add(logData: logData)
}
}
private actor Sender {
private let http: Http
private let baseUrl: URL
private let token: String
private let type: String
private var sendLogsTimer: Timer?
private let sendLogsTimerDelay: TimeInterval = 5.0
private let maxNumberOfLogs: Int = 1000
private let maxNumberOfLogsToSendInBulk: Int = 20
private var logsToSend: [[String: String]] = []
private var sending: Bool = false
init(http: Http, baseUrl: URL, token: String, type: String) {
self.http = http
self.baseUrl = baseUrl
self.token = token
self.type = type
}
func start() {
if !logsToSend.isEmpty {
startSendLogsTimer()
}
}
func stop() {
stopSendLogsTimer()
}
func add(logData: [String: String]) {
logsToSend.append(logData)
if logsToSend.count > maxNumberOfLogs {
NSLog("Ⓛ Exceeded maximum log messages: \(maxNumberOfLogs)")
logsToSend.removeSubrange(0 ..< (logsToSend.count - maxNumberOfLogs))
}
if !logsToSend.isEmpty && sendLogsTimer == nil {
startSendLogsTimer()
}
}
private func sendLogs() async {
guard !sending else { return }
guard !logsToSend.isEmpty else { return stopSendLogsTimer() }
sending = true
let logs = Array(logsToSend.prefix(maxNumberOfLogsToSendInBulk))
logsToSend = Array(logsToSend.dropFirst(maxNumberOfLogsToSendInBulk))
let path = logs.count == 1 ? "/\(token)/\(type)" : "/_bulk"
let string = logs.count == 1 ? serialize(log: logs[0]) : serialize(logs: logs)
let url = baseUrl.appendingPathComponent(path)
guard let data = string?.data(using: .utf8) else {
sending = false
return
}
#if os(iOS) || os(tvOS)
let taskId = await UIApplication.shared.beginBackgroundTask(withName: String(describing: Swift.type(of: self)))
#endif
let result = await http.data(parameters: .init(method: .post, url: url, body: .data(data)))
sending = false
if result.error != nil {
logsToSend.insert(contentsOf: logs, at: 0)
}
#if os(iOS) || os(tvOS)
await UIApplication.shared.endBackgroundTask(taskId)
#endif
}
private func serialize(logs: [[String: String]]) -> String {
let metaInfo = [
"index": [
"_index": token,
"_type": type,
]
]
guard let metaInfoLine = Json(value: metaInfo).string else { fatalError("Can't create meta info for elastic logs bulk update") }
let result = logs.reduce("") { result, log in
result + (serialize(log: log).map { "\(metaInfoLine)\n\($0)\n" } ?? "")
}
return result
}
private func serialize(log: [String: String]) -> String? {
Json(value: log).string
}
private func startSendLogsTimer() {
sendLogsTimer = Timer.scheduledTimer(withTimeInterval: sendLogsTimerDelay, repeats: true) { _ in
Task { [weak self] in
await self?.sendLogs()
}
}
}
private func stopSendLogsTimer() {
sendLogsTimer?.invalidate()
sendLogsTimer = nil
}
}
}
| mit | aec77ab6cab188588a1c46cb9f2bf814 | 29.455752 | 140 | 0.541915 | 4.597862 | false | false | false | false |
jschmid/couchbase-chat | ios-app/couchbase-chat/Controllers/ChooseNameController.swift | 1 | 1603 | //
// ChooseNameController.swift
// couchbase-chat
//
// Created by Jonas Schmid on 13/07/15.
// Copyright © 2015 schmid. All rights reserved.
//
import UIKit
class ChooseNameController: UIViewController {
@IBOutlet weak var roomTextField: UITextField!
var selectedUsers: Set<String>?
lazy var database: CBLDatabase = {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let db = app.syncHelper!.database
return db
}()
override func viewDidLoad() {
// Make sure we are in the room
let app = UIApplication.sharedApplication().delegate as! AppDelegate
selectedUsers?.insert(app.syncHelper!.username)
}
@IBAction func createClick(sender: UIBarButtonItem) {
createChatroom()
self.dismissViewControllerAnimated(true, completion: nil)
}
private func createChatroom() {
let text = roomTextField.text
if text == nil || text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
return
}
let roomname = text!
let members = Array(selectedUsers!)
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let properties: [String: AnyObject] = [
"type": "chatroom",
"name": roomname,
"user": app.syncHelper!.username,
"members": members
]
let doc = database.createDocument()
do {
try doc.putProperties(properties)
} catch {
print("Could not create chatroom: \(error)")
}
}
}
| mit | ce98afa01f237a25beb2fffcddb6308c | 24.83871 | 87 | 0.616105 | 4.739645 | false | false | false | false |
veeman961/Flicks | Flicks/ContainerViewController.swift | 1 | 13482 | //
// ContainViewController.swift
// Flicks
//
// Created by Kevin Rajan on 1/12/16.
// Copyright © 2016 veeman961. All rights reserved.
//
import UIKit
class ContainerViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var menuContainerView: UIView!
@IBOutlet weak var mainContainerView: UIView!
var mainTabBarController: TabBarViewController?
var leftMenuWidth:CGFloat = 0
/*
checked:[[Bool]]! {
didSet(newValue) {
if (newValue != nil) {
updateTabs(newValue)
}
}
}
*/
var checkedKey:String = "CHECKED_CATEGORIES"
let categories = [["Now Playing Movies","Popular Movies","Top Rated Movies", "Upcoming Movies"],["On the Air TV Shows", "TV Shows Airing Today", "Top Rated TV Shows", "Popular TV Shows"]]
let endPoints = [["movie/now_playing", "movie/popular", "movie/top_rated", "movie/upcoming"], ["tv/on_the_air", "tv/airing_today", "tv/top_rated", "tv/popular"]]
override func viewDidLoad() {
super.viewDidLoad()
/*
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let menuViewController = storyboard.instantiateViewControllerWithIdentifier("MenuViewController") as! MenuViewController
menuViewController.checked = self.checked
*/
// Ensure leftMenuWidth is the width of the menuContainerView
leftMenuWidth = menuContainerView.frame.width
// Apply Shadow
applyPlainShadow(mainContainerView)
// Do any additional setup after loading the view.
// Tab bar controller's child pages have a top-left button toggles the menu
NSNotificationCenter.defaultCenter().addObserver(self, selector: "toggleMenu", name: "toggleMenu", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "closeMenuViaNotification", name: "closeMenuViaNotification", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Cleanup notifications added in viewDidLoad
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func toggleMenu(){
scrollView.contentOffset.x == 0 ? openMenu() : closeMenu()
}
// This wrapper function is necessary because closeMenu params do not match up with Notification
func closeMenuViaNotification(){
closeMenu()
}
// Use scrollview content offset-x to slide the menu.
func closeMenu(animated:Bool = true){
self.view.addSubview(menuContainerView)
menuContainerView.frame = CGRect(x: 0, y: 0, width: menuContainerView.frame.width, height: menuContainerView.frame.height)
self.view.sendSubviewToBack(menuContainerView)
scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: animated)
scrollView.addSubview(mainContainerView)
updateTabs()
}
// Open is the natural state of the menu because of how the storyboard is setup.
func openMenu(){
scrollView.setContentOffset(CGPoint(x: -200, y: 0), animated: true)
}
func applyPlainShadow(view: UIView) {
let layer = view.layer
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = CGSize(width: -15, height: 0)
layer.shadowOpacity = 0.85
layer.shadowRadius = 50
}
// 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.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if segue.identifier == "MenuSegue" {
if let navVC = segue.destinationViewController as? UINavigationController {
if let menuVC = navVC.topViewController as? MenuViewController {
menuVC.containerViewController = self
}
}
}
if segue.destinationViewController.isKindOfClass(UITabBarController) {
//let defaults = NSUserDefaults.standardUserDefaults()
//self.checked = defaults.objectForKey(checkedKey) as! [[Bool]]
let tabVC = segue.destinationViewController as! UITabBarController
tabVC.tabBar.barStyle = .Black
tabVC.tabBar.tintColor = UIColor.orangeColor()
var viewControllers = [UINavigationController]()
for i in 0 ..< categories[0].count {
if myVariables.checked[0][i] {
let moviesNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let moviesViewController = moviesNavigationController.topViewController as! MoviesViewController
moviesViewController.endpoint = endPoints[0][i]
moviesNavigationController.tabBarItem.title = categories[0][i]
moviesNavigationController.tabBarItem.image = UIImage(named: "popular")
moviesNavigationController.navigationBar.barStyle = .BlackTranslucent
viewControllers.append(moviesNavigationController)
}
}
for i in 0 ..< categories[1].count {
if myVariables.checked[1][i] {
let tvShowsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TVShowsNavigationController") as! UINavigationController
let tvShowsViewController = tvShowsNavigationController.topViewController as! TVShowsViewController
tvShowsViewController.endpoint = endPoints[1][i]
tvShowsNavigationController.tabBarItem.title = categories[1][i]
tvShowsNavigationController.tabBarItem.image = UIImage(named: "popular")
tvShowsNavigationController.navigationBar.barStyle = .BlackTranslucent
viewControllers.append(tvShowsNavigationController)
}
}
tabVC.viewControllers? = viewControllers
self.mainTabBarController = tabVC as? TabBarViewController
/*
let nowPlayingMoviesNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let nowPlayingMoviesViewController = nowPlayingMoviesNavigationController.topViewController as! MoviesViewController
nowPlayingMoviesViewController.endpoint = "movie/now_playing"
nowPlayingMoviesNavigationController.tabBarItem.title = "Now Playing"
nowPlayingMoviesNavigationController.tabBarItem.image = UIImage(named: "popular")
nowPlayingMoviesNavigationController.navigationBar.barStyle = .BlackTranslucent
let upcomingMoviesNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let upcomingMoviesViewController = upcomingMoviesNavigationController.topViewController as! MoviesViewController
upcomingMoviesViewController.endpoint = "movie/upcoming"
upcomingMoviesNavigationController.tabBarItem.title = "Upcoming"
upcomingMoviesNavigationController.tabBarItem.image = UIImage(named: "")
upcomingMoviesNavigationController.navigationBar.barStyle = .BlackTranslucent
let onTheAirTVShowsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TVShowsNavigationController") as! UINavigationController
let onTheAirTVShowsViewController = onTheAirTVShowsNavigationController.topViewController as! TVShowsViewController
onTheAirTVShowsViewController.endpoint = "tv/on_the_air"
onTheAirTVShowsNavigationController.tabBarItem.title = "On The Air"
onTheAirTVShowsNavigationController.tabBarItem.image = UIImage(named: "")
onTheAirTVShowsNavigationController.navigationBar.barStyle = .BlackTranslucent
let popularTVShowsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TVShowsNavigationController") as! UINavigationController
let popularTVShowsViewController = popularTVShowsNavigationController.topViewController as! TVShowsViewController
popularTVShowsViewController.endpoint = "tv/popular"
popularTVShowsNavigationController.tabBarItem.title = "Popular"
popularTVShowsNavigationController.tabBarItem.image = UIImage(named: "")
popularTVShowsNavigationController.navigationBar.barStyle = .BlackTranslucent
let tabVC = segue.destinationViewController as! UITabBarController
tabVC.viewControllers = [nowPlayingMoviesNavigationController, upcomingMoviesNavigationController, onTheAirTVShowsNavigationController, popularTVShowsNavigationController]
tabVC.tabBar.barStyle = .Black
tabVC.tabBar.tintColor = UIColor.orangeColor()
*/
}
}
func updateTabs() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let tabVC = self.mainTabBarController {
tabVC.tabBar.barStyle = .Black
tabVC.tabBar.tintColor = UIColor.orangeColor()
var viewControllers = [UINavigationController]()
for i in 0 ..< categories[0].count {
if myVariables.checked[0][i] {
let moviesNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let moviesViewController = moviesNavigationController.topViewController as! MoviesViewController
moviesViewController.endpoint = endPoints[0][i]
moviesNavigationController.tabBarItem.title = categories[0][i]
moviesNavigationController.tabBarItem.image = UIImage(named: "popular")
moviesNavigationController.navigationBar.barStyle = .BlackTranslucent
viewControllers.append(moviesNavigationController)
}
}
for i in 0 ..< categories[1].count {
if myVariables.checked[1][i] {
let tvShowsNavigationController = storyboard.instantiateViewControllerWithIdentifier("TVShowsNavigationController") as! UINavigationController
let tvShowsViewController = tvShowsNavigationController.topViewController as! TVShowsViewController
tvShowsViewController.endpoint = endPoints[1][i]
tvShowsNavigationController.tabBarItem.title = categories[1][i]
tvShowsNavigationController.tabBarItem.image = UIImage(named: "popular")
tvShowsNavigationController.navigationBar.barStyle = .BlackTranslucent
viewControllers.append(tvShowsNavigationController)
}
}
tabVC.viewControllers? = viewControllers
}
//print(myVariables.checked)
}
}
extension ContainerViewController : UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
//print("scrollView.contentOffset.x:: \(scrollView.contentOffset.x)")
if scrollView.contentOffset.x == -menuContainerView.frame.width {
scrollView.addSubview(menuContainerView)
menuContainerView.frame = CGRect(x: -menuContainerView.frame.width, y: 0, width: menuContainerView.frame.width, height: menuContainerView.frame.height)
scrollView.bringSubviewToFront(mainContainerView)
}
}
// http://www.4byte.cn/question/49110/uiscrollview-change-contentoffset-when-change-frame.html
// When paging is enabled on a Scroll View,
// a private method _adjustContentOffsetIfNecessary gets called,
// presumably when present whatever controller is called.
// The idea is to disable paging.
// But we rely on paging to snap the slideout menu in place
// (if you're relying on the built-in pan gesture).
// So the approach is to keep paging disabled.
// But enable it at the last minute during scrollViewWillBeginDragging.
// And then turn it off once the scroll view stops moving.
//
// Approaches that don't work:
// 1. automaticallyAdjustsScrollViewInsets -- don't bother
// 2. overriding _adjustContentOffsetIfNecessary -- messing with private methods is a bad idea
// 3. disable paging altogether. works, but at the loss of a feature
// 4. nest the scrollview inside UIView, so UIKit doesn't mess with it. may have worked before,
// but not anymore.
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
scrollView.pagingEnabled = true
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
scrollView.pagingEnabled = false
}
}
| apache-2.0 | f5e24ac299ad870092c6389e419fd26c | 49.680451 | 191 | 0.67495 | 5.840988 | false | false | false | false |
Aahung/two-half-password | two-half-password/Controllers/VaultSelectionViewController.swift | 1 | 3347 | //
// VaultSelectionViewController.swift
// two-half-password
//
// Created by Xinhong LIU on 14/6/15.
// Copyright © 2015 ParseCool. All rights reserved.
//
import Cocoa
enum VaultSelectionError: ErrorType {
case MissingDropbox1PasswordDirectory
case MissingKeychainFileInDirectory
}
class VaultSelectionViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
weak var mainViewController: MainViewController?
var vaults: [Vault] = []
var selectedVault: Vault? {
didSet {
if (selectedVault != nil) {
selectButton.enabled = true
} else {
selectButton.enabled = false
}
}
}
@IBOutlet weak var selectButton: NSButton!
@IBOutlet weak var tableView: NSTableView?
@IBAction func select(sender: AnyObject) {
mainViewController!.vault = selectedVault
self.dismissController(self)
}
// auto search in ~/Dropbox/Apps/1password and return keychain path if found
func searchInDropbox() throws -> String {
let fileManager = NSFileManager.defaultManager()
let homeDirectory = NSHomeDirectory()
let dropboxPath = "\(homeDirectory)/Dropbox"
let onepasswordDirectoryPath = "\(dropboxPath)/Apps/1Password"
var onepasswordDirectoryContents: [String]?
do {
onepasswordDirectoryContents = try fileManager.contentsOfDirectoryAtPath(onepasswordDirectoryPath)
} catch {
throw VaultSelectionError.MissingDropbox1PasswordDirectory
}
for onepasswordDirectoryContent in onepasswordDirectoryContents! {
if onepasswordDirectoryContent == "1Password.agilekeychain" {
return "\(onepasswordDirectoryPath)/\(onepasswordDirectoryContent)"
}
}
// not found keychain
throw VaultSelectionError.MissingKeychainFileInDirectory
}
override func viewDidLoad() {
super.viewDidLoad()
selectButton.enabled = false
}
override func viewDidAppear() {
do {
let dropboxKeychainPath = try searchInDropbox()
let dropboxKeychain = Vault(path: dropboxKeychainPath, host: Vault.Host.Dropbox)
vaults.append(dropboxKeychain)
} catch {
print(error)
}
tableView?.reloadData()
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return vaults.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let view = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
if tableColumn!.identifier == "keychainTableColumn" {
view.imageView!.image = NSImage(named: "Dropbox-100")
view.textField!.stringValue = vaults[row].path
}
return view
}
func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 60
}
func tableViewSelectionDidChange(notification: NSNotification) {
let row = tableView!.selectedRow
guard (row >= 0) else {
selectedVault = nil
return
}
selectedVault = vaults[row]
}
}
| mit | 5de5af9809c3a7fc0caf52eb077f89c3 | 31.173077 | 113 | 0.639271 | 5.244514 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Non-Audio Tutorial.xcplaygroundpage/Contents.swift | 1 | 3852 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Non-Audio Tutorial
//: In the AudioKit Playgrounds, you'll learn a lot about processing audio,
//: but we won't explain most other basic programming concepts that we'll use.
//: So, here's a mini-tutorial of things that you should probably understand going forward.
//:
//: You will always see the `import` lines which bring in all of
//: AudioKit's functionality to the playground.
import AudioKitPlaygrounds
import AudioKit
//: If you intend to use some of the user interface elements provided by the optional AudioKitUI
//: framework, you will also need to import it.
import AudioKitUI
//: ALERT: This is also the line that most commonly shows an error "No such module"
//: This just means you haven't built AudioKitPlaygrounds yet, in which case pressing Cmd-B or
//: accessing the "Product" menu and choosing "Build".
//: To use a file, copy it intot playground's "Resources" folder and refer to it by name:
let file = try AKAudioFile(readFileName: "mixloop.wav")
//: You are not limited to using the sound files provided with AudioKit, in fact
//: we encourage you to drag your own sound files to the Resources folder.
//: Ideally, to keep things running quickly, loopable 10-20 second `.wav` or `.aiff`
//: files are recommended. Many free loops are avaiable online at sites such as
//: [looperman.com](http://www.looperman.com/) or [freesound.org](http://www.freesound.org/).
//:
//: 
//:
//: While we will do our best to annotate the playgrounds well, you can also get
//: more information about the different code elements on the page by clicking
//: on them and looking at the Quick Help Inspector. Or, you can also option-click
//: on any class, method, or variable name to show information about that element.
//: Try it with the lines below:
let player = try AKAudioPlayer(file: file)
let effect = AKMoogLadder(player)
//: The following lines keep a playground executing even after the last line is
//: run so that the audio elements that were started have time to play and make
//: sounds for us to listen to.
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
//: The other ways we'll keep playgrounds running will by using `sleep` and `usleep`
//: functions and infinite while loops.
//: You can view the waveform on the timeline for any playground page by adding
//: the following lines if they don't exist. The plot does not usually appear
//: by default because it takes significant power to draw the plots and we don't
//: want your laptop's fan to fire up and drain your battery unnecessarily
let plotView = AKOutputWaveformPlot.createView()
PlaygroundPage.current.liveView = plotView
//: Now that we are near the bottom of the screen (unless you have a majorly tall monitor!)
//: we'd like to call your attention to the playground controls on the
//: bottom left right below the navbar.
//:
//: The first button toggles the console log which can be useful to look at when
//: things go wrong. The second button is your play / stop button which is
//: useful to control playback of the audio in the playground. If you click and
//: hold on this button you will get a pop-up that will allow you choose between
//: automatically running the playground or manually pressing play. They both
//: have their reason. Automatic running is great for changing a parameter and
//: quickly hearing the audio results. Manual Run is better for when you're in
//: the middle of creating an audio system and you don't want to hear results
//: until you're further along in the process.
//:
//: 
//: ---
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | f6e0e83992ad3cdf051700f2a5bdd85f | 51.054054 | 96 | 0.74325 | 4.228321 | false | false | false | false |
stephentyrone/swift | stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift | 3 | 18121 | //===--- SwiftReflectionTest.swift ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides infrastructure for introspecting type information in a
// remote swift executable by swift-reflection-test, using pipes and a
// request-response protocol to communicate with the test tool.
//
//===----------------------------------------------------------------------===//
// FIXME: Make this work with Linux
import MachO
import Darwin
let RequestInstanceKind = "k"
let RequestInstanceAddress = "i"
let RequestReflectionInfos = "r"
let RequestImages = "m"
let RequestReadBytes = "b"
let RequestSymbolAddress = "s"
let RequestStringLength = "l"
let RequestDone = "d"
let RequestPointerSize = "p"
internal func debugLog(_ message: @autoclosure () -> String) {
#if DEBUG_LOG
fputs("Child: \(message())\n", stderr)
fflush(stderr)
#endif
}
public enum InstanceKind : UInt8 {
case None
case Object
case Existential
case ErrorExistential
case Closure
case Enum
case EnumValue
}
/// Represents a section in a loaded image in this process.
internal struct Section {
/// The absolute start address of the section's data in this address space.
let startAddress: UnsafeRawPointer
/// The size of the section in bytes.
let size: UInt
}
/// Holds the addresses and sizes of sections related to reflection
internal struct ReflectionInfo : Sequence {
/// The name of the loaded image
internal let imageName: String
/// Reflection metadata sections
internal let fieldmd: Section?
internal let assocty: Section?
internal let builtin: Section?
internal let capture: Section?
internal let typeref: Section?
internal let reflstr: Section?
internal func makeIterator() -> AnyIterator<Section?> {
return AnyIterator([
fieldmd,
assocty,
builtin,
capture,
typeref,
reflstr
].makeIterator())
}
}
#if arch(x86_64) || arch(arm64)
typealias MachHeader = mach_header_64
#else
typealias MachHeader = mach_header
#endif
/// Get the location and size of a section in a binary.
///
/// - Parameter name: The name of the section
/// - Parameter imageHeader: A pointer to the Mach header describing the
/// image.
/// - Returns: A `Section` containing the address and size, or `nil` if there
/// is no section by the given name.
internal func getSectionInfo(_ name: String,
_ imageHeader: UnsafePointer<MachHeader>) -> Section? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var size: UInt = 0
let address = getsectiondata(imageHeader, "__TEXT", name, &size)
guard let nonNullAddress = address else { return nil }
guard size != 0 else { return nil }
return Section(startAddress: nonNullAddress, size: size)
}
/// Get the Swift Reflection section locations for a loaded image.
///
/// An image of interest must have the following sections in the __TEXT
/// segment:
/// - __swift5_fieldmd
/// - __swift5_assocty
/// - __swift5_builtin
/// - __swift5_capture
/// - __swift5_typeref
/// - __swift5_reflstr (optional, may have been stripped out)
///
/// - Parameter i: The index of the loaded image as reported by Dyld.
/// - Returns: A `ReflectionInfo` containing the locations of all of the
/// needed sections, or `nil` if the image doesn't contain all of them.
internal func getReflectionInfoForImage(atIndex i: UInt32) -> ReflectionInfo? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let header = unsafeBitCast(_dyld_get_image_header(i),
to: UnsafePointer<MachHeader>.self)
let imageName = _dyld_get_image_name(i)!
let fieldmd = getSectionInfo("__swift5_fieldmd", header)
let assocty = getSectionInfo("__swift5_assocty", header)
let builtin = getSectionInfo("__swift5_builtin", header)
let capture = getSectionInfo("__swift5_capture", header)
let typeref = getSectionInfo("__swift5_typeref", header)
let reflstr = getSectionInfo("__swift5_reflstr", header)
return ReflectionInfo(imageName: String(validatingUTF8: imageName)!,
fieldmd: fieldmd,
assocty: assocty,
builtin: builtin,
capture: capture,
typeref: typeref,
reflstr: reflstr)
}
/// Get the TEXT segment location and size for a loaded image.
///
/// - Parameter i: The index of the loaded image as reported by Dyld.
/// - Returns: The image name, address, and size.
internal func getAddressInfoForImage(atIndex i: UInt32) ->
(name: String, address: UnsafeMutablePointer<UInt8>?, size: UInt) {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let header = unsafeBitCast(_dyld_get_image_header(i),
to: UnsafePointer<MachHeader>.self)
let name = String(validatingUTF8: _dyld_get_image_name(i)!)!
var size: UInt = 0
let address = getsegmentdata(header, "__TEXT", &size)
return (name, address, size)
}
internal func sendBytes<T>(from address: UnsafePointer<T>, count: Int) {
var source = address
var bytesLeft = count
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
while bytesLeft > 0 {
let bytesWritten = fwrite(source, 1, bytesLeft, stdout)
fflush(stdout)
guard bytesWritten > 0 else {
fatalError("Couldn't write to parent pipe")
}
bytesLeft -= bytesWritten
source = source.advanced(by: bytesWritten)
}
}
/// Send the address of an object to the parent.
internal func sendAddress(of instance: AnyObject) {
debugLog("BEGIN \(#function)")
defer { debugLog("END \(#function)") }
var address = Unmanaged.passUnretained(instance).toOpaque()
sendBytes(from: &address, count: MemoryLayout<UInt>.size)
}
/// Send the `value`'s bits to the parent.
internal func sendValue<T>(_ value: T) {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value = value
sendBytes(from: &value, count: MemoryLayout<T>.size)
}
/// Read a word-sized unsigned integer from the parent.
internal func readUInt() -> UInt {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value: UInt = 0
fread(&value, MemoryLayout<UInt>.size, 1, stdin)
return value
}
/// Send all known `ReflectionInfo`s for all images loaded in the current
/// process.
internal func sendReflectionInfos() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let infos = (0..<_dyld_image_count()).compactMap(getReflectionInfoForImage)
var numInfos = infos.count
debugLog("\(numInfos) reflection info bundles.")
precondition(numInfos >= 1)
sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size)
for info in infos {
debugLog("Sending info for \(info.imageName)")
for section in info {
sendValue(section?.startAddress)
sendValue(section?.size ?? 0)
}
}
}
/// Send all loadedimages loaded in the current process.
internal func sendImages() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let infos = (0..<_dyld_image_count()).map(getAddressInfoForImage)
debugLog("\(infos.count) reflection info bundles.")
precondition(infos.count >= 1)
sendValue(infos.count)
for (name, address, size) in infos {
debugLog("Sending info for \(name)")
sendValue(address)
sendValue(size)
}
}
internal func printErrnoAndExit() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let errorCString = strerror(errno)!
let message = String(validatingUTF8: errorCString)! + "\n"
let bytes = Array(message.utf8)
fwrite(bytes, 1, bytes.count, stderr)
fflush(stderr)
exit(EXIT_FAILURE)
}
/// Retrieve the address and count from the parent and send the bytes back.
internal func sendBytes() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let count = Int(readUInt())
debugLog("Parent requested \(count) bytes from \(address)")
var totalBytesWritten = 0
var pointer = UnsafeMutableRawPointer(bitPattern: address)
while totalBytesWritten < count {
let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout))
fflush(stdout)
if bytesWritten == 0 {
printErrnoAndExit()
}
totalBytesWritten += bytesWritten
pointer = pointer?.advanced(by: bytesWritten)
}
}
/// Send the address of a symbol loaded in this process.
internal func sendSymbolAddress() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let name = readLine()!
name.withCString {
let handle = UnsafeMutableRawPointer(bitPattern: Int(-2))!
let symbol = dlsym(handle, $0)
let symbolAddress = unsafeBitCast(symbol, to: UInt.self)
sendValue(symbolAddress)
}
}
/// Send the length of a string to the parent.
internal func sendStringLength() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let cString = UnsafePointer<CChar>(bitPattern: address)!
var count = 0
while cString[count] != CChar(0) {
count = count + 1
}
sendValue(count)
}
/// Send the size of this architecture's pointer type.
internal func sendPointerSize() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size)
sendValue(pointerSize)
}
/// Hold an `instance` and wait for the parent to query for information.
///
/// This is the main "run loop" of the test harness.
///
/// The parent will necessarily need to:
/// - Get the addresses of any swift dylibs that are loaded, where applicable.
/// - Get the address of the `instance`
/// - Get the pointer size of this process, which affects assumptions about the
/// the layout of runtime structures with pointer-sized fields.
/// - Read raw bytes out of this process's address space.
///
/// The parent sends a Done message to indicate that it's done
/// looking at this instance. It will continue to ask for instances,
/// so call doneReflecting() when you don't have any more instances.
internal func reflect(instanceAddress: UInt, kind: InstanceKind) {
while let command = readLine(strippingNewline: true) {
switch command {
case String(validatingUTF8: RequestInstanceKind)!:
sendValue(kind.rawValue)
case String(validatingUTF8: RequestInstanceAddress)!:
sendValue(instanceAddress)
case String(validatingUTF8: RequestReflectionInfos)!:
sendReflectionInfos()
case String(validatingUTF8: RequestImages)!:
sendImages()
case String(validatingUTF8: RequestReadBytes)!:
sendBytes()
case String(validatingUTF8: RequestSymbolAddress)!:
sendSymbolAddress()
case String(validatingUTF8: RequestStringLength)!:
sendStringLength()
case String(validatingUTF8: RequestPointerSize)!:
sendPointerSize()
case String(validatingUTF8: RequestDone)!:
return
default:
fatalError("Unknown request received: '\(Array(command.utf8))'!")
}
}
}
/// Reflect a class instance.
///
/// This reflects the stored properties of the immediate class.
/// The superclass is not (yet?) visited.
public func reflect(object: AnyObject) {
defer { _fixLifetime(object) }
let address = Unmanaged.passUnretained(object).toOpaque()
let addressValue = UInt(bitPattern: address)
reflect(instanceAddress: addressValue, kind: .Object)
}
/// Reflect any type at all by boxing it into an existential container (an `Any`)
///
/// Given a class, this will reflect the reference value, and not the contents
/// of the instance. Use `reflect(object:)` for that.
///
/// This function serves to exercise the projectExistential function of the
/// SwiftRemoteMirror API.
///
/// It tests the three conditions of existential layout:
///
/// ## Class existentials
///
/// For example, a `MyClass as Any`:
/// ```
/// [Pointer to class instance]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type fits in the 3-word buffer
///
/// For example, a `(1, 2) as Any`:
/// ```
/// [Tuple element 1: Int]
/// [Tuple element 2: Int]
/// [-Empty_]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type has to be allocated into a
/// heap buffer.
///
/// For example, a `LargeStruct<T> as Any`:
/// ```
/// [Pointer to unmanaged heap container] --> [Large struct]
/// [-Empty-]
/// [-Empty-]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// The test doesn't care about the witness tables - we only care
/// about what's in the buffer, so we always put these values into
/// an Any existential.
public func reflect<T>(any: T, kind: InstanceKind = .Existential) {
let any: Any = any
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size)
anyPointer.initialize(to: any)
let anyPointerValue = UInt(bitPattern: anyPointer)
reflect(instanceAddress: anyPointerValue, kind: kind)
anyPointer.deallocate()
}
// Reflect an `Error`, a.k.a. an "error existential".
//
// These are always boxed on the heap, with the following layout:
//
// - Word 0: Metadata Pointer
// - Word 1: 2x 32-bit reference counts
//
// If Objective-C interop is available, an Error is also an
// `NSError`, and so has:
//
// - Word 2: code (NSInteger)
// - Word 3: domain (NSString *)
// - Word 4: userInfo (NSDictionary *)
//
// Then, always follow:
//
// - Word 2 or 5: Instance type metadata pointer
// - Word 3 or 6: Instance witness table for conforming
// to `Swift.Error`.
//
// Following that is the instance that conforms to `Error`,
// rounding up to its alignment.
public func reflect<T: Error>(error: T) {
let error: Error = error
let errorPointerValue = unsafeBitCast(error, to: UInt.self)
reflect(instanceAddress: errorPointerValue, kind: .ErrorExistential)
}
// Reflect an `Enum`
//
// These are handled like existentials, but
// the test driver verifies a different set of data.
public func reflect<T>(enum value: T) {
reflect(any: value, kind: .Enum)
}
public func reflect<T>(enumValue value: T) {
reflect(any: value, kind: .EnumValue)
}
/// Wraps a thick function with arity 0.
struct ThickFunction0 {
var function: () -> Void
}
/// Wraps a thick function with arity 1.
struct ThickFunction1 {
var function: (Int) -> Void
}
/// Wraps a thick function with arity 2.
struct ThickFunction2 {
var function: (Int, String) -> Void
}
/// Wraps a thick function with arity 3.
struct ThickFunction3 {
var function: (Int, String, AnyObject?) -> Void
}
struct ThickFunctionParts {
var function: UnsafeRawPointer
var context: Optional<UnsafeRawPointer>
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping () -> Void) {
let fn = UnsafeMutablePointer<ThickFunction0>.allocate(
capacity: MemoryLayout<ThickFunction0>.size)
fn.initialize(to: ThickFunction0(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int) -> Void) {
let fn =
UnsafeMutablePointer<ThickFunction1>.allocate(
capacity: MemoryLayout<ThickFunction1>.size)
fn.initialize(to: ThickFunction1(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction2>.allocate(
capacity: MemoryLayout<ThickFunction2>.size)
fn.initialize(to: ThickFunction2(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String, AnyObject?) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction3>.allocate(
capacity: MemoryLayout<ThickFunction3>.size)
fn.initialize(to: ThickFunction3(function: function))
let contextPointer = fn.withMemoryRebound(
to: ThickFunctionParts.self, capacity: 1) {
UInt(bitPattern: $0.pointee.context)
}
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate()
}
/// Call this function to indicate to the parent that there are
/// no more instances to look at.
public func doneReflecting() {
reflect(instanceAddress: UInt(InstanceKind.None.rawValue), kind: .None)
}
/* Example usage
public protocol P {
associatedtype Index
var startIndex: Index { get }
}
public struct Thing : P {
public let startIndex = 1010
}
public enum E<T: P> {
case B(T)
case C(T.Index)
}
public class A<T: P> : P {
public let x: T?
public let y: T.Index
public let b = true
public let t = (1, 1.0)
private let type: NSObject.Type
public let startIndex = 1010
public init(x: T) {
self.x = x
self.y = x.startIndex
self.type = NSObject.self
}
}
let instance = A(x: A(x: Thing()))
reflect(A(x: Thing()))
*/
| apache-2.0 | f789d51af2b7704e71baf6c1c00d648f | 30.460069 | 87 | 0.686276 | 4.064827 | false | false | false | false |
phuongvnc/CPConfettiView | Example/CPConfettiViewExample/ViewController.swift | 1 | 1118 | //
// ViewController.swift
// CPConfettiViewExample
//
// Created by framgia on 3/3/17.
// Copyright © 2017 Vo Nguyen Chi Phuong. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var confettiView: CPConfettiView!
@IBOutlet private weak var directionSegment: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func edditingChangValueComment(sender: UITextField) {
guard let text = sender.text else {
return
}
confettiView.direction = directionSegment.selectedSegmentIndex == 0 ? .Top : .Bottom
confettiView.intensity = 0.5
if text == "heart" {
confettiView.setImageForConfetti(image: UIImage(named:"heart")!)
confettiView.startConfetti(duration:3)
} else if text == "beer" {
confettiView.setImageForConfetti(image: UIImage(named:"beer")!)
confettiView.startConfetti(duration:3)
}
}
}
| mit | 19857201468dc3ea9ddc475f7f321d12 | 27.641026 | 92 | 0.658013 | 4.504032 | false | false | false | false |
gitkong/FLTableViewComponent | FLTableComponent/FLCollectionViewHandler.swift | 2 | 14942 | //
// FLCollectionViewHandler.swift
// FLComponentDemo
//
// Created by 孔凡列 on 2017/6/19.
// Copyright © 2017年 YY Inc. All rights reserved.
//
import UIKit
@objc protocol FLCollectionViewHandlerDelegate {
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, itemAt indexPath : IndexPath)
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, headerAt section : NSInteger)
@objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, footerAt section : NSInteger)
}
class FLCollectionViewHandler: NSObject {
private(set) lazy var componentsDict : NSMutableDictionary = {
return NSMutableDictionary.init()
}()
var components : Array<FLCollectionBaseComponent> = [] {
didSet {
self.collectionView?.handler = self
componentsDict.removeAllObjects()
for section in 0..<components.count {
let component = components[section]
component.section = section
// same key will override the old value, so the last component will alaways remove first
componentsDict.setValue(component, forKey: component.componentIdentifier)
}
}
}
var delegate : FLCollectionViewHandlerDelegate?
var collectionView : UICollectionView? {
return components.first?.collectionView
}
}
// Mark : component control
extension FLCollectionViewHandler : FLCollectionViewHandlerProtocol {
func component(at index : NSInteger) -> FLCollectionBaseComponent? {
guard components.count > 0, index < components.count else {
return nil
}
return components[index]
}
func exchange(_ component : FLCollectionBaseComponent, by exchangeComponent : FLCollectionBaseComponent) {
self.components.exchange(component.section!, by: exchangeComponent.section!)
}
func replace(_ component : FLCollectionBaseComponent, by replacementComponent : FLCollectionBaseComponent) {
self.components.replaceSubrange(component.section!...component.section!, with: [replacementComponent])
}
func addAfterIdentifier(_ component : FLCollectionBaseComponent, after identifier : String) {
if let afterComponent = self.component(by: identifier) {
self.addAfterComponent(component, after: afterComponent)
}
}
func addAfterComponent(_ component : FLCollectionBaseComponent, after afterComponent : FLCollectionBaseComponent) {
self.addAfterSection(component, after: afterComponent.section!)
}
func addAfterSection(_ component : FLCollectionBaseComponent, after index : NSInteger) {
guard components.count > 0, index < components.count else {
return
}
self.components.insert(component, at: index)
}
func add(_ component : FLCollectionBaseComponent) {
guard components.count > 0 else {
return
}
self.components.append(component)
}
func removeComponent(by identifier : String, removeType : FLComponentRemoveType) {
guard components.count > 0 else {
return
}
if let component = self.component(by: identifier) {
self.componentsDict.removeObject(forKey: identifier)
if removeType == .All {
self.components = self.components.filter({ $0 != component })
}
else if removeType == .Last {
self.removeComponent(component)
}
}
}
func removeComponent(_ component : FLCollectionBaseComponent?) {
guard component != nil else {
return
}
self.removeComponent(at: component!.section!)
}
func removeComponent(at index : NSInteger) {
guard index < components.count else {
return
}
self.components.remove(at: index)
}
func reloadComponents() {
self.collectionView?.reloadData()
}
func reloadComponents(_ components : [FLCollectionBaseComponent]) {
guard self.components.count > 0, components.count <= self.components.count else {
return
}
for component in components {
self.reloadComponent(at: component.section!)
}
}
func reloadComponent(_ component : FLCollectionBaseComponent) {
self.reloadComponent(at: component.section!)
}
func reloadComponent(at index : NSInteger) {
guard components.count > 0, index < components.count else {
return
}
self.collectionView?.reloadSections(IndexSet.init(integer: index))
}
func component(by identifier : String) -> FLCollectionBaseComponent? {
guard componentsDict.count > 0, !identifier.isEmpty else {
return nil
}
return componentsDict.value(forKey: identifier) as? FLCollectionBaseComponent
}
}
// MARK : dataSources customizaion
extension FLCollectionViewHandler : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
final func numberOfSections(in collectionView: UICollectionView) -> Int {
return components.count
}
final func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard components.count > 0 else {
return 0
}
return components[section].numberOfItems()
}
final func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard components.count > 0 else {
return UICollectionViewCell()
}
let component : FLCollectionBaseComponent = components[indexPath.section]
component.section = indexPath.section
return component.cellForItem(at: indexPath.item)
}
}
// MARK : display method customizaion
extension FLCollectionViewHandler : UICollectionViewDelegate {
final func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(willDisplayCell: cell, at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(didEndDisplayCell: cell, at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(willDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind)
}
final func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath){
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].collectionView(didEndDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind)
}
}
// MARK : header or footer customizaion
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard components.count > 0, section < components.count else {
return CGSize.zero
}
return CGSize.init(width: collectionView.bounds.size.width,
height: components[section].heightForHeader())
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard components.count > 0, section < components.count else {
return CGSize.zero
}
return CGSize.init(width: collectionView.bounds.size.width,
height: components[section].heightForFooter())
}
final func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard components.count > 0, indexPath.section < components.count else {
return UICollectionReusableView()
}
let component = components[indexPath.section]
let headerFooterView :FLCollectionHeaderFooterView = component.collectionView(viewOfKind: kind)
headerFooterView.delegate = self
headerFooterView.section = indexPath.section
// add gesture
let tapG : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.headerFooterDidClick))
headerFooterView.addGestureRecognizer(tapG)
return headerFooterView
}
func headerFooterDidClick(GesR : UIGestureRecognizer) {
let headerFooterView : FLCollectionHeaderFooterView = GesR.view as! FLCollectionHeaderFooterView
guard let identifierType = FLIdentifierType.type(of: headerFooterView.reuseIdentifier) , let section = headerFooterView.section else {
return
}
switch identifierType {
case .Header:
self.collectionHeaderView(headerFooterView, didClickSectionAt: section)
case .Footer:
self.collectionFooterView(headerFooterView, didClickSectionAt: section)
default : break
}
}
}
// MARK : layout customization
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard components.count > 0, indexPath.section < components.count else {
return CGSize.zero
}
var size : CGSize = components[indexPath.section].sizeForItem(at: indexPath.item)
if size == .zero {
if self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
size = flowLayout.itemSize
}
else {
size = (collectionViewLayout.layoutAttributesForItem(at: indexPath) != nil) ? collectionViewLayout.layoutAttributesForItem(at: indexPath)!.size : CGSize.zero
}
}
return size
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
guard components.count > 0, section < components.count else {
return UIEdgeInsets.zero
}
let inset : UIEdgeInsets = components[section].sectionInset()
// set sectionInset, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.sectionInsetArray.append(inset)
}
return inset
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
guard components.count > 0, section < components.count else {
return 0
}
let minimumLineSpacing : CGFloat = components[section].minimumLineSpacing()
// set minimumLineSpacing, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.minimumLineSpacingArray.append(minimumLineSpacing)
}
return minimumLineSpacing
}
final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
guard components.count > 0, section < components.count else {
return 0
}
let minimumInteritemSpacing : CGFloat = components[section].minimumInteritemSpacing()
// set minimumInteritemSpacing, because custom flowLayout can not get that automatily
if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout {
flowLayout.minimumInteritemSpacingArray.append(minimumInteritemSpacing)
}
return minimumInteritemSpacing
}
}
// MARK : Managing Actions for Cells
extension FLCollectionViewHandler {
final func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
guard components.count > 0, indexPath.section < components.count else {
return false
}
return components[indexPath.section].shouldShowMenu(at: indexPath.item)
}
final func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
guard components.count > 0, indexPath.section < components.count else {
return false
}
return components[indexPath.section].canPerform(selector: action, forItemAt: indexPath.item, withSender: sender)
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
guard components.count > 0, indexPath.section < components.count else {
return
}
components[indexPath.section].perform(selector: action, forItemAt: indexPath.item, withSender: sender)
}
}
// MARK :Event
extension FLCollectionViewHandler : FLCollectionComponentEvent {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate?.collectionViewDidClick?(self, itemAt: indexPath)
}
func collectionHeaderView(_ headerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) {
self.delegate?.collectionViewDidClick?(self, headerAt: section)
}
func collectionFooterView(_ footerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) {
self.delegate?.collectionViewDidClick?(self, footerAt: section)
}
}
| mit | 8c7523a9f74c46d944231621018ca338 | 40.706704 | 195 | 0.688835 | 5.722882 | false | false | false | false |
malczak/silicon | Examples/Simple/Simple/AppDelegate.swift | 1 | 1196 | //
// AppDelegate.swift
// Simple
//
// Created by Mateusz Malczak on 02/03/16.
// Copyright © 2016 ThePirateCat. All rights reserved.
//
import UIKit
import Silicon
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Bootstrap.setup()
// self.log(text: "On Boostrap done")
// let sem = DispatchSemaphore(value: 0)
//
// let queue = DispatchQueue(label: "testy1")
// let queue2 = DispatchQueue(label: "testy2")
// let key = DispatchSpecificKey<Int>()
// queue.setSpecific(key: key, value: 1001)
// queue2.async {
// print("\t\ttrying t1")
// if let t1 = DispatchQueue.getSpecific(key: DispatchSpecificKey<Int>()) {
// print("Got t1 = \(t1)")
// }
// print("\t\ttrying t2 \(key)")
// if let t2 = DispatchQueue.getSpecific(key: key) {
// print("Got t2 = \(t2)")
// }
// }
//
return true
}
}
| mit | c81301464b53e83ab0672591e50b0b4b | 26.790698 | 144 | 0.569874 | 3.956954 | false | false | false | false |
playgroundbooks/playgroundbook | spec/fixtures/wrapper/destination/swift_at_artsy_1.swift | 1 | 8698 | import Foundation
/*:
(Note: a screen recording of a presentation of this material is [available on YouTube](https://github.com/artsy/Swift-at-Artsy/tree/master/Beginners/Lesson%20One).)
Hey! So we're going to be looking at Swift from the perspective of learning programming. This means you get to ask awkward questions and I struggle to verbalise concepts that are the programming equivalent of muscle memory. It'll be fun!
To start off we need to get to a point where we can write any code. We're going to assume that you already have a copy of Xcode 7 installed. With that, let's get started!
Open Xcode and you'll get this Welcome dialogue.

We'll be using _playgrounds_ to learn Swift. Click "Get started with a playground", give it a name, and make sure the platform is set to **OS X**.

Awesome. Xcode will create an open the playground for you. It'll look something like this.

The large pane on the left is where we're going to write code. On the right is where the results of our code are displayed. You can see that there's already one line of code written for us, `var str = "Hello, playground"`, and the results pane says `"Hello, playground"`. Neat.
Normally for things I work with, the code we are writing gets transformed from something we, as humans, kind-of understand to something a machine understands via a compiler. Let's stick with the idea that it's basically a translator from human to machine. Normally its a big upfront conversion, for example Eigen can take 5 minutes to compile.
We're going to use Playgrounds, which is more like a back and forth conversation with the compiler, so it's much faster to write code and test things out. These are called REPLs.
What this means is whatever you type will be run by Xcode and the results will be shown on the right. When Xcode is compiling code (whenever you change text), the top bar of the window will change to say "Running" and will show a little spinner.
Let's start by saying what _isn't_ code. You see the the first line, how it is greyed out? Well that's a comment. Comments are annotations in the code that are not ran by the compiler. We'll be using comments occasionally to skip bits of code, or to remind us what something is.
OK let's write some code, let's try typing some things.
*/
1 + 2
1 / 2
1.0 / 2.0
"Hello, Artsy"
/*:
You can see the results in the results pane:

In programming, we want to work with abstractions. So let's make our first variable. A variable holds a value that you can refer to later, you can name them (almost) whatever you want.
Variables are themselves an abstract concept, and it's normal for beginners to take time getting comfortable with them. In essence, a variable is a way to store something in a place that you can refer to later. There are a few good reasons to do this, but the most common one is that we need to refer to the same value more than once.
On an artist's Artsy page, we show their name more than once. It's useful to be able to store the artists name in a variable _once_ and then refer to that variable multiple times to show the user an artist's page.
We're going to make a simple calculator with 3 variables. What I'd like to do is define a variable called `a` and `b` then add them together to make `c`. This is a simple example, but it's about foundations.
*/
var a = 2
var b = 3
var c = a + b
/*:
In this case, you can see that we're referring back to `a` and `b` as variables, instead of the numbers `2` and `3`. This is a simple example, and with more experience, you'll get more comfortable.
Variables all have a _type_. Some variables are numbers, and some are strings, and some are other things, too! Numbers are often `Int`, or an integer (basically a round number: 1, 2, 3, -500, 401). Swift is a **strongly-typed language**, which means that types matter a lot. Swift won't let you confuse one type for another. Even though we haven't _told_ Swift what the type of our variables are, the compiler figures it out automatically.
In Swift, `:` specifies a type. So the following two lines are equivalent.
*/
var myString = "Hello, Artsy"
var myString: String = "Hello, Artsy"
/*:
In this case we're dealing with a collection of letters, that combined, we call a string. This is common terminology in most programming languages, think of it as a string of letters.
*/
var myString: String = 1
/*:
Swift will complain and say that `'Int' is not convertible to 'String'`. This is Swift's compile-time type checking. It prevents bugs from happening in apps at runtime by giving you errors before-hand. Swift's primary goal is safety against crashes in apps.
When we're writing code, very often we want to print out some useful information for someone to read. We're going to use this to show that some of our code is running. So lets add a print statement saying what the value of `c` is:
*/
print(c)
/*:
With `print` working, we can start doing some logic. We want to start checking how big our `c` is, and just like in English, we'll use an `if` statement:
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
Let's unpack what we're seeing here. `if [something]` - what's happening here is that the bit after the `if` is checking to see if `c` is greater than the number (`Int`) `6`. If it is, then it will run the code inside the braces.
`if` statements are fundamentally about doing some code only under certain circumstances. For example, Artsy only shows the "Inquire on Artwork" button **if** that artwork can be inquired upon. There are lots of different places in our code where it's useful to do something only if a condition is met.
It is common to use a left margin / indentation to indicate that something is inside a braced section. It's not enforced though.
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
*/
if c > 6 {
print("Pretty big c you got there.")
}
/*:
*/
if c > 6 { print("Pretty big c you got there.") }
/*:
We've got one more thing to go over, and that is loops. Loops repeat a section of code. Computers are really good at doing the same thing over and over, and loops are how programmers tell computers to do that. Repeating code is really useful in the Artsy's artwork pages, specifically in the related artworks section. As programmers, we tell the computer how to add _one_ artwork to the page, and then tell the computer to do that over and over for all the related artworks.
Let's make a nice simple loop, one that reads like English. For _a_ number in _zero to c_.
*/
for number in 0...c {
print("hi")
}
/*:
It has the same behavior that we saw in the `if` example. It will run the thing inside the braces as many times as the value of `c`. Each time it will print out `"hi"`. I think we can expand on this one little bit. The word `number` here is actually a variable, let's make it sound all mathematical and call it `x` instead.
*/
for x in 0...c {
print("hi")
}
/*:
Now we know it's a variable, lets print it!
*/
for x in 0...c {
print(x)
}
/*:
For loops, often just called "loops", are foundational to programming. In this example above, we've looped over all the numbers from `0` to `c`, but you can loop over other things, too. Say we're making an app at Artsy that shows a bunch of artworks – we might loop over all the artworks to show them on the screen.
If you hit the little triangle in the bottom left you can see the printed output!
----------------
So let's recap.
* We've learned a little bit about variables, they are named values that make it easier for us to think about what something represents vs what it is.
* Then we looked at some `String`s, and showed that you can't change something from a string to a number once you've start using it as a `String`,
* We then printed some information.
* After that we looked at adding an `if` statement to add some logic to our code.
* Finally we wrapped up with a `for in` loop.
If you're keen, feel free to keep playing in the playground. Try changing things in the loops to see what happens. Is it what you expected to happen? Why or why not?
What do you think this code would do?
*/
for number in 0...15 {
if number > 5 {
print("This is greater than five")
}
}
/*:
What about this?
*/
for number in 0...15 {
if number > 5 {
print("This is greater than five")
} else {
print("This is less than five")
}
}
/*:
You can also look at the free Stanford Swift Course: https://www.youtube.com/playlist?list=PLxwBNxx9j4PW4sY-wwBwQos3G6Kn3x6xP
*/ | mit | 1fee80403ab851d3cff6c1aac1c8b013 | 42.485 | 474 | 0.734361 | 3.835906 | false | false | false | false |
zhuhaow/NEKit | src/Socket/AdapterSocket/HTTPAdapter.swift | 1 | 3711 | import Foundation
public enum HTTPAdapterError: Error, CustomStringConvertible {
case invalidURL, serailizationFailure
public var description: String {
switch self {
case .invalidURL:
return "Invalid url when connecting through proxy"
case .serailizationFailure:
return "Failed to serialize HTTP CONNECT header"
}
}
}
/// This adapter connects to remote host through a HTTP proxy.
public class HTTPAdapter: AdapterSocket {
enum HTTPAdapterStatus {
case invalid,
connecting,
readingResponse,
forwarding,
stopped
}
/// The host domain of the HTTP proxy.
let serverHost: String
/// The port of the HTTP proxy.
let serverPort: Int
/// The authentication information for the HTTP proxy.
let auth: HTTPAuthentication?
/// Whether the connection to the proxy should be secured or not.
var secured: Bool
var internalStatus: HTTPAdapterStatus = .invalid
public init(serverHost: String, serverPort: Int, auth: HTTPAuthentication?) {
self.serverHost = serverHost
self.serverPort = serverPort
self.auth = auth
secured = false
super.init()
}
override public func openSocketWith(session: ConnectSession) {
super.openSocketWith(session: session)
guard !isCancelled else {
return
}
do {
internalStatus = .connecting
try socket.connectTo(host: serverHost, port: serverPort, enableTLS: secured, tlsSettings: nil)
} catch {}
}
override public func didConnectWith(socket: RawTCPSocketProtocol) {
super.didConnectWith(socket: socket)
guard let url = URL(string: "\(session.host):\(session.port)") else {
observer?.signal(.errorOccured(HTTPAdapterError.invalidURL, on: self))
disconnect()
return
}
let message = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "CONNECT" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
if let authData = auth {
CFHTTPMessageSetHeaderFieldValue(message, "Proxy-Authorization" as CFString, authData.authString() as CFString?)
}
CFHTTPMessageSetHeaderFieldValue(message, "Host" as CFString, "\(session.host):\(session.port)" as CFString?)
CFHTTPMessageSetHeaderFieldValue(message, "Content-Length" as CFString, "0" as CFString?)
guard let requestData = CFHTTPMessageCopySerializedMessage(message)?.takeRetainedValue() else {
observer?.signal(.errorOccured(HTTPAdapterError.serailizationFailure, on: self))
disconnect()
return
}
internalStatus = .readingResponse
write(data: requestData as Data)
socket.readDataTo(data: Utils.HTTPData.DoubleCRLF)
}
override public func didRead(data: Data, from socket: RawTCPSocketProtocol) {
super.didRead(data: data, from: socket)
switch internalStatus {
case .readingResponse:
internalStatus = .forwarding
observer?.signal(.readyForForward(self))
delegate?.didBecomeReadyToForwardWith(socket: self)
case .forwarding:
observer?.signal(.readData(data, on: self))
delegate?.didRead(data: data, from: self)
default:
return
}
}
override public func didWrite(data: Data?, by socket: RawTCPSocketProtocol) {
super.didWrite(data: data, by: socket)
if internalStatus == .forwarding {
observer?.signal(.wroteData(data, on: self))
delegate?.didWrite(data: data, by: self)
}
}
}
| bsd-3-clause | 609fa8333c5e509b2a9a88df29ef69ee | 32.736364 | 145 | 0.645379 | 4.941411 | false | false | false | false |
4faramita/TweeBox | TweeBox/SpamUserParams.swift | 1 | 885 | //
// SpamUserParams.swift
// TweeBox
//
// Created by 4faramita on 2017/8/29.
// Copyright © 2017年 4faramita. All rights reserved.
//
import Foundation
class SpamUserParams: SimpleUserParams {
var performBlock = true
init(userID: String?, screenName: String?, performBlock: Bool?) {
if let performBlock = performBlock {
self.performBlock = performBlock
}
super.init(userID: userID, screenName: screenName)
}
override func getParams() -> [String : Any] {
var params = [String: String]()
if userID != nil {
params["user_id"] = userID
} else if screenName != nil {
params["screen_name"] = screenName
}
params["perform_block"] = performBlock.description
return params
}
}
| mit | 18c2bca9eab656f45240041fd4f7f2d0 | 21.05 | 69 | 0.552154 | 4.432161 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Models/Habitica Models/HabiticaModel.swift | 1 | 722 | //
// HabiticaModel.swift
// Habitica Models
//
// Created by Phillip Thelen on 05.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
public protocol HabiticaModel {
}
public typealias HabiticaModelCodable = HabiticaModel & Codable
public extension HabiticaModel where Self: Codable {
static func from(json: String, using encoding: String.Encoding = .utf8) -> Self? {
guard let data = json.data(using: encoding) else { return nil }
return from(data: data)
}
static func from(data: Data) -> Self? {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return try? decoder.decode(Self.self, from: data)
}
}
| gpl-3.0 | 7ca28822837f104f4b963847d621ea15 | 25.703704 | 86 | 0.675451 | 4.005556 | false | false | false | false |
riamf/BendCell | BendCell/BendCell/BendableCell.swift | 1 | 3309 | //
// BendableCell.swift
// BendCell
//
// Created by Pawel Kowalczuk on 03/05/2017.
// Copyright © 2017 Pawel Kowalczuk. All rights reserved.
//
import Foundation
import UIKit
protocol BendableCellType {
var bendView: BendView? { get }
func draw(with velocity: CGFloat, directionUp: Bool)
}
extension BendableCellType where Self: UITableViewCell {
func draw(with velocity: CGFloat, directionUp: Bool) {
bendView?.draw(with: velocity, directionUp: directionUp)
}
}
open class BendableCell: UITableViewCell, BendableCellType {
var bendView: BendView?
fileprivate var originalColor: UIColor!
fileprivate func initialize() {
originalColor = contentView.backgroundColor ?? .random
backgroundColor = nil
contentView.backgroundColor = nil
addBendView()
addObservers()
}
fileprivate func updateIfNeeded(with color: UIColor) {
bendView?.update(color)
contentView.backgroundColor = nil
}
fileprivate func replaceBendViewIfNeeded() {
guard let bendViewIndex = contentView.subviews.index(where: { $0 === bendView }),
bendViewIndex != 0 else { return }
bendView?.removeFromSuperview()
contentView.insertSubview(bendView!, at: 0)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initialize()
}
override open func layoutSubviews() {
super.layoutSubviews()
bendView?.frame = CGRect(origin: .zero, size: frame.size)
}
fileprivate func addBendView() {
let view = BendView(frame: frame, color: originalColor)
contentView.addSubview(view)
bendView = view
}
//MARK: KVO
enum Observerable {
static let color: String = #keyPath(contentView.backgroundColor)
static let subviews: String = #keyPath(contentView.subviews)
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let color = change?[NSKeyValueChangeKey.newKey] as? UIColor {
updateIfNeeded(with: color)
}
if keyPath == #keyPath(contentView.subviews) {
replaceBendViewIfNeeded()
}
}
fileprivate func addObservers() {
addObserver(self, forKeyPath: Observerable.color, options: .new, context: nil)
addObserver(self, forKeyPath: Observerable.subviews, options: .initial, context: nil)
}
deinit {
removeObserver(self, forKeyPath: Observerable.color, context: nil)
removeObserver(self, forKeyPath: Observerable.subviews, context: nil)
}
}
extension UIColor {
static var random: UIColor {
let hue : CGFloat = CGFloat(arc4random() % 256) / 256
let saturation : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5
let brightness : CGFloat = CGFloat(arc4random() % 128) / 256 + 0.5
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1)
}
}
| mit | 9a19543d71203fa83bd836d547c31372 | 29.915888 | 156 | 0.647219 | 4.613668 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Modules/BIND/Sources/BINDWithdrawUI/BINDWithdraw.swift | 1 | 6886 | @_exported import BINDWithdrawDomain
import BlockchainComponentLibrary
import BlockchainNamespace
import Combine
import Errors
import SwiftUI
import ToolKit
public struct BINDWithdrawView: View {
@EnvironmentObject private var service: BINDWithdrawService
@ObservedObject private var search = DebounceTextFieldObserver(delay: .seconds(1))
@MainActor private let success: (BINDBeneficiary) -> Void
public init(success: @escaping (BINDBeneficiary) -> Void) {
self.success = success
}
public var body: some View {
VStack(alignment: .leading) {
Group {
searchView
switch service.result {
case .none:
emptyView
case .success(let bind):
detailsView(bind)
case .failure(let error):
Text(error.title)
.typography(.caption1)
.foregroundColor(.semantic.error)
if error.message.isNotEmpty {
Text(error.message)
.typography(.caption2)
.foregroundColor(.semantic.error)
}
}
}
.padding([.leading, .trailing])
Spacer()
footerView
}
.background(Color.semantic.background)
}
@State private var isFirstResponder: Bool = false
@ViewBuilder private var searchView: some View {
Text(L10n.search.title)
.typography(.paragraph2)
.foregroundColor(.semantic.title)
Input(
text: $search.input,
isFirstResponder: $isFirstResponder,
placeholder: L10n.search.placeholder,
trailing: {
if search.input.isNotEmpty {
IconButton(
icon: .close,
action: { search.input = "" }
)
}
}
)
.onChange(of: search.output) { term in
service.search(term)
}
}
@ViewBuilder private var emptyView: some View {
Text(L10n.empty.info)
.typography(.caption1)
.foregroundColor(.semantic.body)
}
@ViewBuilder private func detailsView(_ bind: BINDBeneficiary) -> some View {
Color.clear
.frame(height: 8.pt)
List {
ForEach(bind.ux, id: \.self) { row in
PrimaryRow(
title: row.title,
trailing: { Text(row.value) }
)
.typography(.body1)
.frame(height: 50.pt)
}
}
.listStyle(.plain)
.background(Color.semantic.background)
}
@ViewBuilder private var footerView: some View {
VStack {
HStack {
Icon.bank
.aspectRatio(1, contentMode: .fit)
.frame(width: 24.pt)
VStack(alignment: .leading) {
Text(L10n.disclaimer.title)
.foregroundColor(.semantic.title)
Text(L10n.disclaimer.description)
.foregroundColor(.semantic.body)
}
.typography(.caption1)
}
.frame(maxWidth: .infinity, alignment: .leading)
Group {
if case .success(let bind) = service.result {
PrimaryButton(
title: L10n.action.next,
isLoading: service.isLoading
) {
Task(priority: .userInitiated) {
try await service.link(bind)
success(bind)
}
}
} else {
PrimaryButton(
title: L10n.action.next,
isLoading: service.isLoading
)
.disabled(true)
}
}
.padding()
}
.padding([.leading, .top, .trailing])
.frame(maxWidth: .infinity, alignment: .leading)
.background(
Color.semantic.background
.shadow(color: Color.semantic.dark, radius: 10, x: 0, y: 0)
.mask(Rectangle().padding(.top, -20))
)
}
}
extension BINDBeneficiary {
fileprivate struct Row: Hashable {
let title: String
let value: String
}
fileprivate var ux: [Row] {
[
.init(title: L10n.information.bankName, value: agent.bankName),
.init(title: L10n.information.alias, value: agent.label),
.init(title: L10n.information.accountHolder, value: agent.name),
.init(title: L10n.information.accountType, value: agent.accountType),
.init(title: L10n.information.CBU, value: agent.address),
.init(title: L10n.information.CUIL, value: agent.holderDocument)
]
}
}
struct BINDWithdrawViewPreviews: PreviewProvider {
static var previews: some View {
BINDWithdrawView(success: { _ in })
.environmentObject(
BINDWithdrawService(
initialResult: nil,
repository: BINDWithdrawPreviewRepository()
)
)
BINDWithdrawView(success: { _ in })
.environmentObject(
BINDWithdrawService(
initialResult: .failure(
.init(
title: "Please, only send funds from a bank account in your name.",
message: "Please, only send funds from a bank account in your name."
)
),
repository: BINDWithdrawPreviewRepository()
)
)
BINDWithdrawView(success: { _ in })
.environmentObject(
BINDWithdrawService(
initialResult: .success(.preview),
repository: BINDWithdrawPreviewRepository()
)
)
}
}
final class BINDWithdrawPreviewRepository: BINDWithdrawRepositoryProtocol {
init() {}
func currency(_ currency: String) -> BINDWithdrawPreviewRepository {
self
}
func search(address: String) -> AnyPublisher<BINDBeneficiary, Nabu.Error> {
Just(.preview)
.setFailureType(to: NabuError.self)
.delay(for: .seconds(1), scheduler: DispatchQueue.main)
.eraseToAnyPublisher()
}
func link(beneficiary beneficiaryId: String) -> AnyPublisher<Void, Nabu.Error> {
Just(())
.setFailureType(to: NabuError.self)
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | 7e5791f7943052e8db2ede2a97b3c818 | 31.027907 | 96 | 0.501888 | 5.224583 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/TodayExtension/Src/TodayViewController.swift | 1 | 4364 | //
// ReportsByDateViewController.swift
// TodayExtension
//
// Created by Maxim Pervushin on 22/11/15.
// Copyright © 2015 Maxim Pervushin. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBAction func openApplicationButtonAction(sender: AnyObject) {
// [self.extensionContext openURL:[NSURL URLWithString:@"timelogger://add"] completionHandler:nil];
if let url = NSURL(string: "hyperhabit://open") {
extensionContext?.openURL(url, completionHandler: nil)
}
print("Open Application");
}
private let dataSource = TodayDataSource(dataProvider: App.dataProvider)
private var _heightConstraint: NSLayoutConstraint?
private var heightConstraint: NSLayoutConstraint {
get {
if _heightConstraint == nil {
_heightConstraint = NSLayoutConstraint(item: tableView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: tableView.contentSize.height)
tableView.addConstraint(_heightConstraint!)
}
return _heightConstraint!
}
}
private func updateUI() {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.heightConstraint.constant = self.tableView.contentSize.height
}
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource.changesObserver = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
updateUI()
}
}
extension TodayViewController: ChangesObserver {
func observableChanged(observable: AnyObject) {
updateUI()
}
}
extension TodayViewController: NCWidgetProviding {
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
tableView.reloadData()
updateUI()
completionHandler(NCUpdateResult.NewData)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 0, 0, 0)
}
}
extension TodayViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return dataSource.incompletedReports.count
} else {
return dataSource.completedReports.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let report = indexPath.section == 0 ? dataSource.incompletedReports[indexPath.row] : dataSource.completedReports[indexPath.row]
if report.habitDefinition.characters.count > 0 {
let cell = tableView.dequeueReusableCellWithIdentifier(ReportWithDefinitionCell.defaultReuseIdentifier, forIndexPath: indexPath) as! ReportWithDefinitionCell
cell.report = report
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(ReportCell.defaultReuseIdentifier, forIndexPath: indexPath) as! ReportCell
cell.report = report
return cell
}
// let cell = tableView.dequeueReusableCellWithIdentifier(ReportCell.defaultReuseIdentifier, forIndexPath: indexPath) as! ReportCell
// let report = indexPath.section == 0 ? dataSource.incompletedReports[indexPath.row] : dataSource.completedReports[indexPath.row]
// cell.report = report
// return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let updatedReport = indexPath.section == 0 ? dataSource.incompletedReports[indexPath.row].completedReport : dataSource.completedReports[indexPath.row].incompletedReport
if dataSource.saveReport(updatedReport) {
tableView.reloadData()
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44;
}
}
| mit | 1dff224723f4741cbaa1018761ad5bb0 | 35.663866 | 206 | 0.693101 | 5.44015 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Preprocessors/ConditionalPreprocessor.swift | 5 | 3173 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public struct HeroConditionalContext {
internal weak var hero: HeroTransition!
public weak var view: UIView!
public private(set) var isAppearing: Bool
public var isPresenting: Bool {
return hero.isPresenting
}
public var isInTabbarController: Bool {
return hero.inTabBarController
}
public var isInNavbarController: Bool {
return hero.inNavigationController
}
public var isMatched: Bool {
return matchedView != nil
}
public var isAncestorViewMatched: Bool {
return matchedAncestorView != nil
}
public var matchedView: UIView? {
return hero.context.pairedView(for: view)
}
public var matchedAncestorView: (UIView, UIView)? {
var current = view.superview
while let ancestor = current, ancestor != hero.context.container {
if let pairedView = hero.context.pairedView(for: ancestor) {
return (ancestor, pairedView)
}
current = ancestor.superview
}
return nil
}
public var fromViewController: UIViewController {
return hero.fromViewController!
}
public var toViewController: UIViewController {
return hero.toViewController!
}
public var currentViewController: UIViewController {
return isAppearing ? toViewController : fromViewController
}
public var otherViewController: UIViewController {
return isAppearing ? fromViewController : toViewController
}
}
class ConditionalPreprocessor: BasePreprocessor {
override func process(fromViews: [UIView], toViews: [UIView]) {
process(views: fromViews, appearing: false)
process(views: toViews, appearing: true)
}
func process(views: [UIView], appearing: Bool) {
for view in views {
guard let conditionalModifiers = context[view]?.conditionalModifiers else { continue }
for (condition, modifiers) in conditionalModifiers {
if condition(HeroConditionalContext(hero: hero, view: view, isAppearing: appearing)) {
context[view]!.append(contentsOf: modifiers)
}
}
}
}
}
| mit | cc539e0dad6327ef9d3cb5a6c05e34c3 | 33.868132 | 94 | 0.731484 | 4.673049 | false | false | false | false |
silence0201/Swift-Study | AdvancedSwift/可选值/A Tour of Optional Techniques - switch-case Matching for Optionals:.playgroundpage/Contents.swift | 1 | 1335 | /*:
### `switch`-`case` Matching for Optionals:
Another consequence of optionals not being `Equatable` is that you can't check
them in a `case` statement. `case` matching is controlled in Swift by the `~=`
operator, and the relevant definition looks a lot like the one that wasn't
working for arrays:
``` swift-example
func ~=<T: Equatable>(a: T, b: T) -> Bool
```
But it's simple to produce a matching version for optionals that just calls
`==`:
*/
//#-editable-code
func ~=<T: Equatable>(pattern: T?, value: T?) -> Bool {
return pattern == value
}
//#-end-editable-code
/*:
It's also nice to implement a range match at the same time:
*/
//#-editable-code
func ~=<Bound>(pattern: Range<Bound>, value: Bound?) -> Bool {
return value.map { pattern.contains($0) } ?? false
}
//#-end-editable-code
/*:
Here, we use `map` to check if a non-`nil` value is inside the interval. Because
we want `nil` not to match any interval, we return `false` in case of `nil`.
Given this, we can now match optional values with `switch`:
*/
//#-editable-code
for i in ["2", "foo", "42", "100"] {
switch Int(i) {
case 42:
print("The meaning of life")
case 0..<10:
print("A single digit")
case nil:
print("Not a number")
default:
print("A mystery number")
}
}
//#-end-editable-code
| mit | 5270dfa161f5918fcedb7eb37b32d809 | 22.839286 | 80 | 0.641948 | 3.48564 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/MapEntry.swift | 1 | 2817 | import CoreData
import EurofurenceWebAPI
@objc(MapEntry)
class MapEntry: NSManagedObject {
@nonobjc class func fetchRequest() -> NSFetchRequest<MapEntry> {
return NSFetchRequest<MapEntry>(entityName: "MapEntry")
}
@NSManaged var identifier: String
@NSManaged var radius: Int32
@NSManaged var x: Int32
@NSManaged var y: Int32
@NSManaged var links: Set<MapEntryLink>
@NSManaged var map: Map
func isWithinTappingRange(of coordinate: Map.Coordinate) -> Bool {
distance(from: coordinate) <= Double(radius)
}
private func distance(from coordinate: Map.Coordinate) -> Double {
let (dX, dY) = (coordinate.x - Int(x), coordinate.y - Int(y))
return hypot(Double(abs(dX)), Double(abs(dY)))
}
}
// MARK: - Fetching
extension MapEntry {
class func entry(identifiedBy identifier: String, in managedObjectContext: NSManagedObjectContext) -> MapEntry {
let fetchRequest: NSFetchRequest<MapEntry> = MapEntry.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier)
fetchRequest.fetchLimit = 1
let fetchResults = try? managedObjectContext.fetch(fetchRequest)
if let existingEntry = fetchResults?.first {
return existingEntry
} else {
let newEntry = MapEntry(context: managedObjectContext)
newEntry.identifier = identifier
return newEntry
}
}
}
// MARK: - Updating
extension MapEntry {
func update(from entry: EurofurenceWebAPI.Map.Entry, managedObjectContext: NSManagedObjectContext) {
identifier = entry.id
x = Int32(entry.x)
y = Int32(entry.y)
radius = Int32(entry.tapRadius)
for link in entry.links {
// Only insert this link if the entry does not contain an existing link.
let containsLink = links.contains { entityLink in
return entityLink.fragmentType == link.fragmentType &&
entityLink.target == link.target &&
entityLink.name == link.name
}
if containsLink {
continue
}
let linkEntity = MapEntryLink(context: managedObjectContext)
linkEntity.update(from: link)
addToLinks(linkEntity)
}
}
}
// MARK: Generated accessors for links
extension MapEntry {
@objc(addLinksObject:)
@NSManaged func addToLinks(_ value: MapEntryLink)
@objc(removeLinksObject:)
@NSManaged func removeFromLinks(_ value: MapEntryLink)
@objc(addLinks:)
@NSManaged func addToLinks(_ values: Set<MapEntryLink>)
@objc(removeLinks:)
@NSManaged func removeFromLinks(_ values: Set<MapEntryLink>)
}
| mit | dfd39204d87a2808f29f0a49f9bfa7f1 | 28.652632 | 116 | 0.631168 | 4.718593 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/TXTReader/BookDetail/Views/QSBookDetailRateView.swift | 1 | 1680 | //
// QSBookDetailRateView.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/4/13.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class QSBookDetailRateView: UIView {
var rate:[String]?{
didSet{
setRate()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupSubviews(){
self.backgroundColor = UIColor.white
let text = ["追书人数","读者留存率","更新字数/天"]
let x:CGFloat = 0
let y:CGFloat = 20
let width = ScreenWidth/3
let height:CGFloat = 21.0
for index in 0..<3 {
let label = UILabel(frame: CGRect(x: x + width*CGFloat(index),y: y,width: width,height: height))
label.text = text[index]
label.textAlignment = .center
label.textColor = UIColor.gray
label.font = UIFont.systemFont(ofSize: 13)
self.addSubview(label)
let slabel = UILabel(frame: CGRect(x: x + width*CGFloat(index),y: y + 21,width: width,height: height))
slabel.textAlignment = .center
slabel.textColor = UIColor.gray
slabel.tag = 123 + index
slabel.font = UIFont.systemFont(ofSize: 13)
self.addSubview(slabel)
}
}
func setRate(){
for index in 0..<(rate?.count ?? 0) {
let label:UILabel? = self.viewWithTag(123 + index) as? UILabel
label?.text = rate?[index]
}
}
}
| mit | ec5251e71211144ddc7cccc009f642c3 | 27.431034 | 114 | 0.554882 | 4.012165 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.