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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tiger8888/LayerPlayer | LayerPlayer/CATiledLayerViewController.swift | 3 | 3849 | //
// CATiledLayerViewController.swift
// LayerPlayer
//
// Created by Scott Gardner on 11/17/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
import UIKit
class CATiledLayerViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var zoomLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var viewForTiledLayer: TilingView!
@IBOutlet weak var fadeDurationSlider: UISlider!
@IBOutlet weak var fadeDurationSliderValueLabel: UILabel!
@IBOutlet weak var tileSizeSlider: UISlider!
@IBOutlet weak var tileSizeSliderValueLabel: UILabel!
@IBOutlet weak var levelsOfDetailSlider: UISlider!
@IBOutlet weak var levelsOfDetailSliderValueLabel: UILabel!
@IBOutlet weak var detailBiasSlider: UISlider!
@IBOutlet weak var detailBiasSliderValueLabel: UILabel!
@IBOutlet weak var zoomScaleSlider: UISlider!
@IBOutlet weak var zoomScaleSliderValueLabel: UILabel!
var tiledLayer: TiledLayer {
return viewForTiledLayer.layer as TiledLayer
}
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
scrollView.contentSize = scrollView.frame.size
updateFadeDurationSliderValueLabel()
updateTileSizeSliderValueLabel()
updateLevelsOfDetailSliderValueLabel()
updateDetailBiasSliderValueLabel()
updateZoomScaleSliderValueLabel()
}
deinit {
TiledLayer.setFadeDuration(CFTimeInterval(0.25))
}
// MARK: - IBActions
@IBAction func fadeDurationSliderChanged(sender: UISlider) {
TiledLayer.setFadeDuration(CFTimeInterval(sender.value))
updateFadeDurationSliderValueLabel()
tiledLayer.contents = nil
tiledLayer.setNeedsDisplayInRect(tiledLayer.bounds)
}
@IBAction func tileSizeSliderChanged(sender: UISlider) {
let value = Int(sender.value)
tiledLayer.tileSize = CGSize(width: value, height: value)
updateTileSizeSliderValueLabel()
}
@IBAction func levelsOfDetailSliderChanged(sender: UISlider) {
tiledLayer.levelsOfDetail = UInt(sender.value)
updateLevelsOfDetailSliderValueLabel()
}
@IBAction func levelsOfDetailSliderTouchedUp(sender: AnyObject) {
showZoomLabel()
}
func showZoomLabel() {
zoomLabel.alpha = 1.0
zoomLabel.hidden = false
let label = zoomLabel
UIView.animateWithDuration(1.0, delay: 0.0, options: nil, animations: {
label.alpha = 0
}, completion: { _ in
label.hidden = true
})
}
@IBAction func detailBiasSliderChanged(sender: UISlider) {
tiledLayer.levelsOfDetailBias = UInt(sender.value)
updateDetailBiasSliderValueLabel()
}
@IBAction func detailBiasSliderTouchedUp(sender: AnyObject) {
showZoomLabel()
}
@IBAction func zoomScaleSliderChanged(sender: UISlider) {
scrollView.zoomScale = CGFloat(sender.value)
updateZoomScaleSliderValueLabel()
}
// MARK: - Helpers
func updateFadeDurationSliderValueLabel() {
fadeDurationSliderValueLabel.text = String(format: "%.2f", adjustableFadeDuration)
}
func updateTileSizeSliderValueLabel() {
tileSizeSliderValueLabel.text = "\(Int(tiledLayer.tileSize.width))"
}
func updateLevelsOfDetailSliderValueLabel() {
levelsOfDetailSliderValueLabel.text = "\(tiledLayer.levelsOfDetail)"
}
func updateDetailBiasSliderValueLabel() {
detailBiasSliderValueLabel.text = "\(tiledLayer.levelsOfDetailBias)"
}
func updateZoomScaleSliderValueLabel() {
zoomScaleSliderValueLabel.text = "\(Int(scrollView.zoomScale))"
}
// MARK: UIScrollViewDelegate
func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
return viewForTiledLayer
}
func scrollViewDidZoom(scrollView: UIScrollView!) {
zoomScaleSlider.setValue(Float(scrollView.zoomScale), animated: true)
updateZoomScaleSliderValueLabel()
}
}
| mit | d5a40edf49d0a841fde9618a6617d897 | 28.607692 | 86 | 0.742531 | 4.582143 | false | false | false | false |
aestusLabs/ASChatApp | ChatButton.swift | 1 | 1778 | //
// ChatButton.swift
// ChatAppOrigionalFiles
//
// Created by Ian Kohlert on 2017-07-19.
// Copyright © 2017 aestusLabs. All rights reserved.
//
import Foundation
import UIKit
class ChatButton: UIButton {
var buttonTag: WidgetTagNames = .error
let gradient = CAGradientLayer()
override init (frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.25
self.layer.shadowOffset = CGSize(width: 2, height: 4)
self.layer.shadowRadius = 4
// gradient.frame = self.bounds
//
// let red = UIColor(red: 1.0, green: 0.28627451, blue: 0.568627451, alpha: 1.0)
// let orange = UIColor(red: 1.0, green: 0.462745098, blue: 0.462745098, alpha: 1.0)
// gradient.colors = [red.cgColor, orange.cgColor]
//
// gradient.startPoint = CGPoint.zero
// gradient.endPoint = CGPoint(x: 1, y: 1)
// self.layer.insertSublayer(gradient, at: 0)
// self.layer.borderColor = appColours.getMainAppColour().cgColor
// self.layer.borderWidth = 1
self.backgroundColor = appColours.getMainAppColour() //UIColor.white
self.layer.cornerRadius = 18
self.setTitleColor(UIColor.white, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
func createChatButton(text: String, tag: WidgetTagNames) -> ChatButton{
let button = ChatButton(frame: CGRect(x: 0, y: 0, width: 250, height: 40))
button.setTitle(text, for: .normal)
button.buttonTag = tag
return button
}
| mit | a044a08d1f868a7eabd85eda184d4c25 | 30.732143 | 91 | 0.639842 | 3.748945 | false | false | false | false |
abitofalchemy/auralML | Sandbox/STBlueMS_iOS/W2STApp/MainApp/Demo/BlueVoice/W2STBlueVoiceViewController.swift | 1 | 28450 |
/** My notes:
** https://stackoverflow.com/questions/34361991/saving-recorded-audio-swift
** https://stackoverflow.com/questions/28233219/recording-1-second-audio-ios
*
* Removing the ASR code
* Work to
** */
import Foundation
import MediaPlayer
import BlueSTSDK
import AVFoundation
//import UIKit
/**
* Audio callback called when an audio buffer can be reused
* userData: pointer to our SyncQueue with the buffer to reproduce
* queue: audio queue where the buffer will be played
* buffer: audio buffer that must be filled
*/
fileprivate func audioCallback(usedData:UnsafeMutableRawPointer?,
queue:AudioQueueRef,
buffer:AudioQueueBufferRef){
// SampleQueue *ptr = (SampleQueue*) userData
let sampleQueuePtr = usedData?.assumingMemoryBound(to: BlueVoiceSyncQueue.self)
//NSData* data = sampleQueuePtr->pop();
let data = sampleQueuePtr?.pointee.pop();
//uint8* temp = (uint8*) buffer->mAudioData
let temp = buffer.pointee.mAudioData.assumingMemoryBound(to: UInt8.self);
//memcpy(temp,data)
data?.copyBytes(to: temp, count: Int(buffer.pointee.mAudioDataByteSize));
// Enqueuing an audio queue buffer after writing to disk?
AudioQueueEnqueueBuffer(queue, buffer, 0, nil);
}
public class W2STBlueVoiceViewController: BlueMSDemoTabViewController,
BlueVoiceSelectDelegate, BlueSTSDKFeatureDelegate, AVAudioRecorderDelegate,
UITableViewDataSource{
/* sa> see below for base decarasion */
private static let ASR_LANG_PREF="W2STBlueVoiceViewController.AsrLangValue"
private static let DEFAULT_ASR_LANG=BlueVoiceLangauge.ENGLISH
private static let CODEC="ADPCM"
private static let SAMPLING_FREQ_kHz = 8;
private static let NUM_CHANNELS = UInt32(1);
/*
* number of byffer that the sysmte will allocate, each buffer will contain
* a sample recived trought the ble connection
*/
private static let NUM_BUFFERS=18;
private static let SAMPLE_TYPE_SIZE = UInt32(2)//UInt32(MemoryLayout<UInt16>.size);
//each buffer contains 40 audio sample
private static let BUFFER_SIZE = (40*SAMPLE_TYPE_SIZE);
/** object used to check if the user has an internet connection */
private var mInternetReachability: Reachability?;
//////////////////// GUI reference ////////////////////////////////////////
@IBOutlet weak var mCodecLabel: UILabel!
@IBOutlet weak var mAddAsrKeyButton: UIButton!
@IBOutlet weak var mSampligFreqLabel: UILabel!
@IBOutlet weak var mAsrStatusLabel: UILabel!
@IBOutlet weak var mSelectLanguageButton: UIButton!
@IBOutlet weak var mRecordButton: UIButton!
@IBOutlet weak var mPlayButton: UIButton!
@IBOutlet weak var mAsrResultsTableView: UITableView!
@IBOutlet weak var mAsrRequestStatusLabel: UILabel!
private var engine:BlueVoiceASREngine?;
private var mFeatureAudio:BlueSTSDKFeatureAudioADPCM?;
private var mFeatureAudioSync:BlueSTSDKFeatureAudioADPCMSync?;
private var mAsrResults:[String] = [];
var recordingSession: AVAudioSession!
var whistleRecorder: AVAudioRecorder!
var whistlePlayer: AVAudioPlayer!
var playButton: UIButton!
/////////////////// AUDIO //////////////////////////////////////////////////
//https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/c/tdef/AudioStreamBasicDescription
private var mAudioFormat = AudioStreamBasicDescription(
mSampleRate: Float64(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000),
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kLinearPCMFormatFlagIsSignedInteger,
mBytesPerPacket: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE * W2STBlueVoiceViewController.NUM_CHANNELS,
mFramesPerPacket: 1,
mBytesPerFrame: W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE*W2STBlueVoiceViewController.NUM_CHANNELS,
mChannelsPerFrame: W2STBlueVoiceViewController.NUM_CHANNELS,
mBitsPerChannel: UInt32(8) * W2STBlueVoiceViewController.SAMPLE_TYPE_SIZE,
mReserved: 0);
//audio queue where play the sample
private var queue:AudioQueueRef?;
//queue of audio buffer to play
private var buffers:[AudioQueueBufferRef?] = Array(repeating:nil, count: NUM_BUFFERS)
//syncronized queue used to store the audio sample from the node
// when an audio buffer is free it will be filled with sample from this object
private var mSyncAudioQueue:BlueVoiceSyncQueue?;
//variable where store the audio before send to an speech to text service
private var mRecordData:Data?;
/////////CONTROLLER STATUS////////////
private var mIsMute:Bool=false;
private var mIsRecording:Bool=false;
override public func viewDidLoad(){
super.viewDidLoad()
view.backgroundColor = UIColor.gray
//set the constant string
mCodecLabel.text = mCodecLabel.text!+W2STBlueVoiceViewController.CODEC
mSampligFreqLabel.text = mSampligFreqLabel.text!+String(W2STBlueVoiceViewController.SAMPLING_FREQ_kHz)+" kHz"
newLanguageSelected(getDefaultLanguage());
mAsrResultsTableView.dataSource=self;
/* ** here I add ** */
recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try recordingSession.setActive(true)
recordingSession.requestRecordPermission() { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
self.loadRecordingUI()
} else {
self.loadFailUI()
}
}
}
} catch {
self.loadFailUI()
}
// UI
mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1)
}
func loadRecordingUI() {
// mRecordButton = UIButton()
mRecordButton.translatesAutoresizingMaskIntoConstraints = false
mRecordButton.setTitle("Tap to Record", for: .normal)
mRecordButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1)
mRecordButton.addTarget(self, action: #selector(onRecordButtonPressed(_:)), for: .touchUpInside)
// stackView.addArrangedSubview(recordButton)
playButton = UIButton()
playButton.translatesAutoresizingMaskIntoConstraints = false
playButton.setTitle("Tap to Play", for: .normal)
playButton.isHidden = true
playButton.alpha = 0
playButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1)
playButton.addTarget(self, action: #selector(playTapped), for: .touchUpInside)
// stackView.addArrangedSubview(playButton)
}
func loadFailUI() {
let failLabel = UILabel()
failLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
failLabel.text = "Recording failed: please ensure the app has access to your microphone."
failLabel.numberOfLines = 0
// self.view.addArrangedSubview(failLabel)
self.view.addSubview(failLabel)
}
class func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
class func getWhistleURL() -> URL {
NSLog("test: getting the file url");
return getDocumentsDirectory().appendingPathComponent("whistle.m4a")
}
/*
* enable the ble audio stremaing and initialize the audio queue
*/
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
mFeatureAudio = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCM.self) as! BlueSTSDKFeatureAudioADPCM?;
mFeatureAudioSync = self.node.getFeatureOfType(BlueSTSDKFeatureAudioADPCMSync.self) as!
BlueSTSDKFeatureAudioADPCMSync?;
//if both feature are present enable the audio
if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{
audio.add(self);
audioSync.add(self);
self.node.enableNotification(audio);
self.node.enableNotification(audioSync);
initAudioQueue();
initRecability();
NSLog(">> audio features ARE present!!")
}else{
NSLog(">> both features are not present!!")
}
}
/**
* stop the ble audio streaming and the audio queue
*/
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated);
if let audio = mFeatureAudio, let audioSync = mFeatureAudioSync{
deInitAudioQueue();
audio.remove(self);
audioSync.remove(self);
self.node.disableNotification(audio);
self.node.disableNotification(audioSync);
}
}
override public func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated);
engine?.destroyListener();
}
private func initAudioQueue(){
//create the queue where store the sample
mSyncAudioQueue = BlueVoiceSyncQueue(size: W2STBlueVoiceViewController.NUM_BUFFERS);
//create the audio queue
AudioQueueNewOutput(&mAudioFormat,audioCallback, &mSyncAudioQueue,nil, nil, 0, &queue);
//create the system audio buffer that will be filled with the data inside the mSyncAudioQueue
for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{
AudioQueueAllocateBuffer(queue!,
W2STBlueVoiceViewController.BUFFER_SIZE,
&buffers[i]);
if let buffer = buffers[i]{
buffer.pointee.mAudioDataByteSize = W2STBlueVoiceViewController.BUFFER_SIZE;
memset(buffer.pointee.mAudioData,0,Int(W2STBlueVoiceViewController.BUFFER_SIZE));
AudioQueueEnqueueBuffer(queue!, buffer, 0, nil);
}
}//for
//start playing the audio
AudioQueueStart(queue!, nil);
mIsMute=false;
}
/// free the audio initialized audio queues
private func deInitAudioQueue(){
AudioQueueStop(queue!, true);
for i in 0..<W2STBlueVoiceViewController.NUM_BUFFERS{
if let buffer = buffers[i]{
AudioQueueFreeBuffer(queue!,buffer);
}
}
}
/// function called when the net state change
///
/// - Parameter notifier: object where read the net state
private func onReachabilityChange(_ notifier:Reachability?){
let netStatus = notifier?.currentReachabilityStatus();
if let status = netStatus{
if(status == NotReachable){
mAsrStatusLabel.text="Disabled";
}else{
NSLog("attemping to load ASR Engine");
loadAsrEngine(getDefaultLanguage());
}
}
}
/// register this class as a observer of the net state
private func initRecability(){
NotificationCenter.default.addObserver(forName:Notification.Name.reachabilityChanged,
object:nil, queue:nil) {
notification in
if(!(notification.object is Reachability)){
return;
}
let notificaitonObj = notification.object as! Reachability?;
self.onReachabilityChange(notificaitonObj);
}
mInternetReachability = Reachability.forInternetConnection();
mInternetReachability?.startNotifier();
onReachabilityChange(mInternetReachability);
}
private func deInitRecability(){
mInternetReachability?.stopNotifier();
}
/// get the selected language for the asr engine
///
/// - Returns: <#return value description#>
public func getDefaultLanguage()->BlueVoiceLangauge{
// let lang = loadAsrLanguage();
return W2STBlueVoiceViewController.DEFAULT_ASR_LANG;
}
/// called when the user select a new language for the asr
/// it store this information an reload the engine
///
/// - Parameter language: language selected
public func newLanguageSelected(_ language:BlueVoiceLangauge){
// loadAsrEngine(language);
// storeAsrLanguage(language);
mSelectLanguageButton.setTitle(language.rawValue, for:UIControlState.normal)
}
/// load the language from the user preference
///
/// - Returns: language stored in the preference or the default one
// private func loadAsrLanguage()->BlueVoiceLangauge?{
// let userPref = UserDefaults.standard;
// let langString = userPref.string(forKey: W2STBlueVoiceViewController.ASR_LANG_PREF);
// if let str = langString{
// return BlueVoiceLangauge(rawValue: str);
// }
// return nil;
// }
/// store in the preference the selected language
///
/// - Parameter language: language to store
private func storeAsrLanguage(_ language:BlueVoiceLangauge){
let userPref = UserDefaults.standard;
userPref.setValue(language.rawValue, forKey:W2STBlueVoiceViewController.ASR_LANG_PREF);
}
/// register this class as a delegate of the BlueVoiceSelectLanguageViewController
///
/// - Parameters:
/// - segue: segue to prepare
/// - sender: object that start the segue
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dest = segue.destination as? BlueVoiceSelectLanguageViewController;
if let dialog = dest{
dialog.delegate=self;
}
}
/// call when the user press the mute button, it mute/unmute the audio
///
/// - Parameter sender: button where the user click
@IBAction func onMuteButtonClick(_ sender: UIButton) {
var img:UIImage?;
if(!mIsMute){
img = UIImage(named:"volume_off");
AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0);
}else{
img = UIImage(named:"volume_on");
AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0);
}
mIsMute = !mIsMute;
sender.setImage(img, for:.normal);
}
/// check that the audio engine has a valid service key
///
/// - Returns: true if the service has a valid service key or it does not need a key,
/// false otherwise
private func checkAsrKey() -> Bool{
if let engine = engine{
if(engine.needAuthKey && !engine.hasLoadedAuthKey()){
showErrorMsg("Please add the engine key", title: "Engine Fail", closeController: false);
return false;// orig bool is False
}else{
return true;
}
}
return false;
}
/// Start the voice to text, if the engine can manage the continuos recognition
private func onContinuousRecognizerStart(){
// NSLog("Entered on cont recognizer start");
// guard checkAsrKey() else{
// return;
// }
// mRecordButton.setTitle("Stop recongition", for: .normal);
// if(!mIsMute){
// AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0);
// }
// engine?.startListener();
// mIsRecording=true;
}
/// Stop a continuos recognition
private func onContinuousRecognizerStop(){
// mIsRecording=false;
// if(!mIsMute){
// AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0);
// }
// if let engine = engine{
// engine.stopListener();
// setRecordButtonTitle(engine);
// }
}
/// Start a non continuos voice to text service
private func onRecognizerStart(){
/* Unused: guard checkAsrKey() else{
return;
}*/
if(!mIsMute){
AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0);
}
let audioURL = W2STBlueVoiceViewController.getWhistleURL()
print(audioURL.absoluteString)
mRecordData = Data();
engine?.startListener();
mIsRecording=true;
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
do {
// 5
whistleRecorder = try AVAudioRecorder(url: audioURL, settings: settings)
whistleRecorder.delegate = self
whistleRecorder.record()
} catch {
finishRecording(success: false)
}
}
/// Stop a non continuos voice to text service, and send the recorded data
/// to the service
private func onRecognizerStop(){
print ("RECOGNIZER STOP...");
mIsRecording=false;
mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1)
// print (mIsRecording);
if(!mIsMute){
AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,1.0);
}
if let engine = engine{
if(mRecordData != nil){
print ("Data is not nil");
// _ = engine.sendASRRequest(audio: mRecordData!, callback: self);
mRecordData=nil;
}
engine.stopListener();
setRecordButtonTitle(engine);
print ("setRecordButtonTitle")
}
}
/// set the starting value for the record button
/// who is calling on this?
/// - Parameter asrEngine: voice to text engine that will be used
private func setRecordButtonTitle(_ asrEngine: BlueVoiceASREngine!){
let recorTitle = asrEngine.hasContinuousRecognizer ? "Start recongition" : "Keep press to record"
print ("mIsRecording:",mIsRecording)
mRecordButton.setTitle(recorTitle, for: .normal);
}
/// call when the user release the record button, it stop a non contiuos
/// voice to text
///
/// - Parameter sender: button released
@IBAction func onRecordButtonRelease(_ sender: UIButton) {
if (engine?.hasContinuousRecognizer == false){
print ("onRecordButton Released")
// onRecognizerStop();
}
}
/// call when the user press the record buttom, it start the voice to text
/// service
///
/// - Parameter sender: button pressed
@IBAction func onRecordButtonPressed(_ sender: UIButton) {
print("Button Pressed");
// engine?.hasContinousRecognizer does not work, so it will be taken out for now
// if let hasContinuousRecognizer = engine?.hasContinuousRecognizer{
// if (hasContinuousRecognizer){
// if(mIsRecording){
// NSLog("Is recording");
// onContinuousRecognizerStop();
// }else{
// onContinuousRecognizerStart();
//
// }//if isRecording
// }else{
if (mIsRecording) {
onRecognizerStop()
mRecordButton.backgroundColor = UIColor(red: 0, green: 0.3, blue: 0, alpha: 1)
mRecordButton.setTitle("Keep Pressed to Record!!!!!!!", for: .normal);
}else{
onRecognizerStart(); // in this func we set the mIsRecording
mRecordButton.setTitle("Stop Recording", for: .normal);
mRecordButton.backgroundColor = UIColor(red: 0.6, green: 0, blue: 0, alpha: 1)
engine?.startListener();
mIsRecording=true;
}
// }//if hasContinuos
// }else{ print ("not engine has cont recognizer"); }//if let
if(!mIsMute){
AudioQueueSetParameter(queue!, kAudioQueueParam_Volume,0.0);
}
}//onRecordButtonPressed
public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
NSLog("audioRecorderDidFinishRecording");
if !flag {
finishRecording(success: false)
}
}
/// call when the user press the add key button, it show the popup to insert
/// the key
///
/// - Parameter sender: button pressed
@IBAction func onAddAsrKeyButtonClick(_ sender: UIButton) {
let insertKeyDialog = engine?.getAuthKeyDialog();
if let viewContoller = insertKeyDialog {
viewContoller.modalPresentationStyle = .popover;
self.present(viewContoller, animated: false, completion: nil);
let presentationController = viewContoller.popoverPresentationController;
presentationController?.sourceView = sender;
presentationController?.sourceRect = sender.bounds
}//if let
}
/// create a new voice to text service that works with the selected language
///
/// - Parameter language: voice language
private func loadAsrEngine(_ language:BlueVoiceLangauge){
if(engine != nil){
engine!.destroyListener();
}
let samplingRateHz = UInt((W2STBlueVoiceViewController.SAMPLING_FREQ_kHz*1000))
engine = BlueVoiceASREngineUtil.getEngine(samplingRateHz:samplingRateHz,language: language);
if let asrEngine = engine{
mAsrStatusLabel.text = asrEngine.name;
mAddAsrKeyButton.isHidden = !asrEngine.needAuthKey;
let asrTitle = asrEngine.hasLoadedAuthKey() ? "Change Service Key" : "Add Service Key";
mAddAsrKeyButton.setTitle(asrTitle, for:UIControlState.normal)
setRecordButtonTitle(asrEngine);
}
}
func finishRecording(success: Bool) {
view.backgroundColor = UIColor(red: 0, green: 0.6, blue: 0, alpha: 1)
whistleRecorder.stop()
whistleRecorder = nil
if success {
mRecordButton.setTitle("(again)Tap to Re-record", for: .normal)
// if playButton.isHidden {
// UIView.animate(withDuration: 0.35) { [unowned self] in
// self.playButton.isHidden = false
// self.playButton.alpha = 1
// }
// }
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTapped))
} else {
mRecordButton.setTitle("(start)Tap to Record", for: .normal)
let ac = UIAlertController(title: "Record failed", message: "There was a problem recording your whistle; please try again.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
func playTapped() {
let audioURL = W2STBlueVoiceViewController.getWhistleURL()
do {
whistlePlayer = try AVAudioPlayer(contentsOf: audioURL)
whistlePlayer.play()
} catch {
let ac = UIAlertController(title: "Playback failed",
message: "Problem playing your whistle; please try re-recording.",
preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
/////////////////////// BlueSTSDKFeatureDelegate ///////////////////////////
/// call when the BlueSTSDKFeatureAudioADPCM has new data, it will enque the data
/// to be play by the sistem and send it to the asr service if it is recording the audio
///
/// - Parameters:
/// - feature: feature that generate the new data
/// - sample: new data
private func didAudioUpdate(_ feature: BlueSTSDKFeatureAudioADPCM, sample: BlueSTSDKFeatureSample){
let sampleData = BlueSTSDKFeatureAudioADPCM.getLinearPCMAudio(sample);
if let data = sampleData{
mSyncAudioQueue?.push(data: data)
if(mIsRecording){
// if(engine!.hasContinuousRecognizer){
// _ = engine!.sendASRRequest(audio: data, callback: self);
// }else{
if(mRecordData != nil){
objc_sync_enter(mRecordData);
mRecordData?.append(data);
objc_sync_exit(mRecordData);
// }// mRecordData!=null
}
}
// else { print ("not recording");} //if is Recording
}//if data!=null
}
/// call when the BlueSTSDKFeatureAudioADPCMSync has new data, it is used to
/// correclty decode the data from the the BlueSTSDKFeatureAudioADPCM feature
///
/// - Parameters:
/// - feature: feature that generate new data
/// - sample: new data
private func didAudioSyncUpdate(_ feature: BlueSTSDKFeatureAudioADPCMSync, sample: BlueSTSDKFeatureSample){
// NSLog("test");
mFeatureAudio?.audioManager.setSyncParam(sample);
}
/// call when a feature gets update
///
/// - Parameters:
/// - feature: feature that get update
/// - sample: new feature data
public func didUpdate(_ feature: BlueSTSDKFeature, sample: BlueSTSDKFeatureSample) {
if(feature .isKind(of: BlueSTSDKFeatureAudioADPCM.self)){
self.didAudioUpdate(feature as! BlueSTSDKFeatureAudioADPCM, sample: sample);
}
if(feature .isKind(of: BlueSTSDKFeatureAudioADPCMSync.self)){
self.didAudioSyncUpdate(feature as! BlueSTSDKFeatureAudioADPCMSync, sample: sample);
}
}
//////////////////////////BlueVoiceAsrRequestCallback///////////////////////////
/// callback call when the asr engin has a positive results, the reult table
/// will be updated wit the new results
///
/// - Parameter text: world say from the user
func onAsrRequestSuccess(withText text:String ){
print("ASR Success:"+text);
mAsrResults.append(text);
DispatchQueue.main.async {
self.mAsrResultsTableView.reloadData();
self.mAsrRequestStatusLabel.isHidden=true;
}
}
/// callback when some error happen during the voice to text translation
///
/// - Parameter error: error during the voice to text translation
func onAsrRequestFail(error:BlueVoiceAsrRequestError){
print("ASR Fail:"+error.rawValue.description);
DispatchQueue.main.async {
self.mAsrRequestStatusLabel.text = error.description;
self.mAsrRequestStatusLabel.isHidden=false;
if(self.mIsRecording){ //if an error happen during the recording, stop it
if(self.engine!.hasContinuousRecognizer){
self.onContinuousRecognizerStop();
}else{
self.onRecognizerStop();
}
}
}
}
/////////////////////// TABLE VIEW DATA DELEGATE /////////////////////////
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return mAsrResults.count;
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var cell = tableView.dequeueReusableCell(withIdentifier: "AsrResult");
if (cell == nil){
cell = UITableViewCell(style: .default, reuseIdentifier: "AsrResult");
cell?.selectionStyle = .none;
}
cell?.textLabel?.text=mAsrResults[indexPath.row];
return cell!;
}
}
| bsd-3-clause | 7a91797bd31aab92e45f4cf77acec021 | 36.782205 | 160 | 0.610053 | 4.863248 | false | false | false | false |
tokenlab/TKSequenceTextField | Example/Pods/TLCustomMask/TLCustomMask/Classes/TLCustomMask.swift | 1 | 9446 | //
// TLCustomMask.swift
// Pods
//
// Created by Domene on 29/03/17.
//
//
import Foundation
/*
* CustomMask takes a string and returns it with the matching pattern
* Usualy it is used inside the shouldChangeCharactersInRange method
*
* usage:
* func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
* self.text = customMask!.formatStringWithRange(range, string: string)
* return false
* }
*
* Use $ for digits ($$-$$$$)
* Use * for characters [a-zA-Z] (**-****)
*/
public class TLCustomMask {
private var _formattingPattern : String;
var finalText : String?
private let digitChar : String = "$" //represents a digit
private let alfaChar : String = "*" //represents an character
public var cleanText : String {
return alfanumericOnly(string: self.finalText!)
}
public var formattingPattern : String{
get{return self._formattingPattern}
set(newPattern){
self._formattingPattern = newPattern
//pass previous text to new pattern
let text = formatString(string: alfanumericOnly(string: self.finalText!))
self.finalText = text != "" ? addPatternToString(string: text) : newPattern
}
}
public init(formattingPattern : String = ""){
self._formattingPattern = formattingPattern;
self.finalText = self._formattingPattern
}
/*
* This approach is based on indexes that
* will iterate independently on two arrays,
* one for the pattern e.g: ["$","-","$"]
* and one for the string e.g: ["1","a","2"]
*/
public func formatString(string: String) -> String{
// if there is no pattern, return string
if self._formattingPattern.isEmpty{
return string
}
//Transform into arrays
let patternArray = Array(_formattingPattern.characters)
let stringArray = Array(alfanumericOnly(string: string).characters)
var finalTextArray = Array<Character>()
var patternArrayIndex = 0
var stringArrayIndex = 0
//iterate through string array
loopStringArray: while stringArrayIndex < stringArray.count{
//iterate through pattern array
loopPatternArray: while patternArrayIndex < patternArray.count{
switch patternArray[patternArrayIndex] {
case "$":
//Check if Int
if let _ = Int(String(stringArray[stringArrayIndex])){
finalTextArray.append(stringArray[stringArrayIndex])
}else{
break loopPatternArray
}
case "*":
//Check if character
//if matches
if matchesForRegexInText(regex: "[a-zA-Z]", text: String(stringArray[stringArrayIndex])).first != nil{
finalTextArray.append(stringArray[stringArrayIndex])
}else{
break loopPatternArray
}
default:
finalTextArray.append(patternArray[patternArrayIndex])
patternArrayIndex += 1
continue loopStringArray
}
patternArrayIndex += 1
break
}
stringArrayIndex += 1
}
//Add pattern to finalText and return string without pattern
let textResult = String(finalTextArray)
self.finalText = addPatternToString(string: textResult)
return textResult
}
/*
* This approach is based on regex
* it will search for the first special character ($ or *)
* and replace it with the user input e.g: 12-$$$$ -> 12-3$$$
*/
public func formatStringWithRange(range: NSRange, string: String) -> String {
//Detect backspace
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) { //Backspace was pressed
self.finalText = deleteLastChar()
}else{
//Find index of first special character ($ or *)
if let range = self.finalText!.range(of: "\\*|\\$", options: .regularExpression){
let char = self.finalText?.substring(with: range)
if(char == "$"){
if let _ = Int(string){
self.finalText = self.finalText?.replacingCharacters(in: range, with: string)
}
}
else if(char == "*"){
//if matches
let matches = matchesForRegexInText(regex: "[a-zA-Z]", text: string)
if (matches.count > 0) {
self.finalText = self.finalText?.replacingCharacters(in: range, with: string)
}
}
}
}
//If empty
if(self.finalText == self._formattingPattern){
return ""
}else{
return removePatternFromString(string: self.finalText!)
}
}
private func deleteLastChar() -> String{
//find last char which is not the replacement char (the last thing that the user typed)
let matches = matchesForRegexInText(regex: "[a-zA-Z0-9]((?=.*?\\*.*)|(?=.*?\\$.*))", text: self.finalText!)
let ft = self.finalText!
var replaceRange : Range<String.Index>? = nil
var originalCharFromPattern : String? = nil
//return empty if finalText is null
if ft.isEmpty{
return ""
}
//if match found
if (matches.count > 0){
let matchReplacementChar = matches.last
replaceRange = self.finalText!.range(of: matchReplacementChar!, options: .backwards)
originalCharFromPattern = self._formattingPattern[replaceRange!.lowerBound...replaceRange!.lowerBound]
}
//there is no match, consequently, formatting pattern is full: "123-66-1234" OR empty: "($$) $$$$-$$$$"
else{
//get last char from formatting pattern
replaceRange = ft.range(of: ft.substring(from: ft.index(before: ft.endIndex)), options: .backwards)
originalCharFromPattern = self._formattingPattern[replaceRange!]
}
//Insert the pattern char back to the final string and return
return ft.replacingCharacters(in: replaceRange!, with: originalCharFromPattern!)
}
/*
* Cleans the string, removing the pattern
* e.g: "123-4*-***" will return "123-4"
*/
private func removePatternFromString(string : String) -> String{
//let matches = regMatchGroup("-?((\\*.*)|(\\$.*))", text: self.finalText!)
let matches = matchesForRegexInText(regex: "((-)|(\\()|(\\)))?(\\*.*)|(\\$.*)", text: self.finalText!)
var finalString = string
var matchStr : String? = nil
if (matches.count > 0){
matchStr = matches[0]
finalString = string.replacingOccurrences(of: matchStr!, with: "")
}
return finalString
}
/*
* Add pattern to string
* e.g: "123-4" will return "123-4*-***"
*/
private func addPatternToString(string : String) -> String{
if let range = string.range(of: string){
var result = ""
//If range exists in self.formattingPattern
if range.upperBound <= self.formattingPattern.endIndex {
result = self.formattingPattern.replacingCharacters(in: range, with: string)
}
return result
}
return self._formattingPattern
}
private func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
/*
* Checks if pattern is valid
* TODO: improve this
*/
private func checkValidPattern(pattern: String){
let matches = matchesForRegexInText(regex: "[^\\$|\\*|\\-|\\.]", text: pattern)
if(matches.count > 0){
print("Warning: not a valid pattern for CustomMask!");
}
}
/*
* Returns alfanumeric string only
*/
private func alfanumericOnly(string: String) -> String{
return string.stringByRemovingRegexMatches(pattern: "\\W")
}
}
extension String {
func stringByRemovingRegexMatches(pattern: String, replaceWith: String = "") -> String {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let range = NSMakeRange(0, self.characters.count)
return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
} catch {
return self
}
}
}
| mit | 7b895666d4d551402a24caf57c408f26 | 36.633466 | 133 | 0.566377 | 4.844103 | false | false | false | false |
kaushaldeo/Olympics | Olympics/ViewControllers/KDEventViewController.swift | 1 | 3892 | //
// KDEventViewController.swift
// Olympics
//
// Created by Kaushal Deo on 8/4/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
import CoreData
class KDEventViewController: UITableViewController {
var events = [Event]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.backgroundView = nil
self.tableView.backgroundColor = UIColor.backgroundColor()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:" ", style: .Plain, target: nil, action: nil)
self.addBackButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.events.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
// Configure the cell...
let event = self.events[indexPath.row]
cell.textLabel?.text = event.name
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("kResultViewController") as? KDResultViewController {
viewController.event = self.events[indexPath.row]
self.navigationController?.pushViewController(viewController, animated: true)
}
}
}
| apache-2.0 | befd3f0eb62a3452bf7ac84269854512 | 34.372727 | 158 | 0.67412 | 5.63913 | false | false | false | false |
xingerdayu/dayu | dayu/ModifyIntroViewController.swift | 1 | 1817 | //
// ModifyIntroViewController.swift
// dayu
//
// Created by Xinger on 15/9/10.
// Copyright (c) 2015年 Xinger. All rights reserved.
//
import UIKit
class ModifyIntroViewController: BaseUIViewController, UITextViewDelegate {
@IBOutlet weak var utfIntro: UITextView!
@IBOutlet weak var wordLabel: UILabel!
override func viewDidLoad() {
utfIntro.layer.borderColor = Colors.MyLightGrayColor.CGColor
utfIntro.layer.borderWidth = 1
utfIntro.layer.masksToBounds = true
utfIntro.text = app.user.intro
}
@IBAction func saveIntro(sender: UIButton) {
let intro = utfIntro.text
let params = ["token":app.getToken(), "intro":intro]
HttpUtil.post(URLConstants.updateUserUrl, params: params, success: {(response:AnyObject!) in
if response["stat"] as! String == "OK" {
self.app.user.intro = intro
UserDao.modifyIntro(intro, id: self.app.user.id)
ViewUtil.showToast(self.view, text: "修改成功", afterDelay: 1)
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "cancel", userInfo: nil, repeats: false)
}
}
)
}
// override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// utfIntro.resignFirstResponder()
// }
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
utfIntro.resignFirstResponder()
}
func cancel() {
self.navigationController?.popViewControllerAnimated(true)
}
func textViewDidChange(textView: UITextView) {
changeLength()
}
func changeLength() {
let length = (utfIntro.text as NSString).length
wordLabel.text = "\(length)/100"
}
}
| bsd-3-clause | d77af22aec87edbee2497adee5d5875c | 30.155172 | 124 | 0.627559 | 4.439803 | false | false | false | false |
jackpocket/helpshift-phonegap | src/ios/HelpshiftPhonegap.swift | 1 | 5360 | @objc(HelpshiftPhonegap) class HelpshiftPhonegap : CDVPlugin {
private var initialized = false
enum Errors: Error {
case Empty
case Incomplete
}
// Moved this so it only exists inside HelpshiftPhonegap (ex : HelpshiftPhonegap.ConfigRequest(someargs))
class ConfigRequest {
var apiKey = ""
var domainName = ""
var appID = ""
init(_ args: Any) throws {
guard let args = args as? [String:String] else { throw HelpshiftPhonegap.Errors.Empty }
guard let apiKey = args["apiKey"] else { throw HelpshiftPhonegap.Errors.Incomplete }
guard let domainName = args["domainName"] else { throw HelpshiftPhonegap.Errors.Incomplete }
guard let appID = args["appID"] else { throw HelpshiftPhonegap.Errors.Incomplete }
self.apiKey = apiKey
self.domainName = domainName
self.appID = appID
}
}
class HelpshiftUser {
var id = ""
var name = ""
var email = ""
init(_ args: Any) throws {
guard let args = args as? [String:String] else { throw HelpshiftPhonegap.Errors.Empty }
guard let id = args["id"] else { throw HelpshiftPhonegap.Errors.Incomplete }
guard let name = args["name"] else { throw HelpshiftPhonegap.Errors.Incomplete }
guard let email = args["email"] else { throw HelpshiftPhonegap.Errors.Incomplete }
self.id = id
self.name = name
self.email = email
}
}
func setup(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
if initialized == true {
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "HelpshfitPhonegap setup")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
return
}
guard let config = try? ConfigRequest(command.arguments[0]) else { return }
HelpshiftCore.initialize(with: HelpshiftAll.sharedInstance())
HelpshiftCore.install (
forApiKey: config.apiKey,
domainName: config.domainName,
appID: config.appID
);
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "HelpshfitPhonegap setup")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
initialized = true
}
func showConversation(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
let options = command.arguments[0] as? [AnyHashable: Any]
HelpshiftSupport.showConversation(self.viewController, withOptions: options)
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "Show Conversation Success")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
func showFAQs(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
HelpshiftSupport.showFAQs(self.viewController)
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "show FAQs Success")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
func login(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
do {
let user = try HelpshiftUser(command.arguments[0])
print("HS LOGIN: User \(user.id) \(user.name) \(user.email)")
HelpshiftCore.login(withIdentifier: user.id, withName: user.name, andEmail: user.email)
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "User id: \(user.id) logged in")
print("User \(user.id) successfully logged in")
} catch {
print(error)
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription)
}
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
}
func logout(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
HelpshiftCore.logout()
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "User logged out")
self.commandDelegate?.send(pluginResult, callbackId: command.callbackId)
print("User logged out")
}
func setName(_ command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
do {
let user = try HelpshiftUser(command.arguments[0])
print("HS Name and email Submitted: \(user.name) \(user.email)")
HelpshiftCore.setName(user.name, andEmail: user.email)
pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "\(user.name) set as name")
print("User name \(user.name) successfully set")
} catch {
print(error)
pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription)
}
}
}
| mit | 28f1bbb32036cf421223d1545b96af6b | 32.5 | 115 | 0.636754 | 4.981413 | false | false | false | false |
cylim/csci342-asgn3-historical-map-ios | csci342-asgn3-historical-map-ios/SatelliteViewController.swift | 1 | 5537 | //
// ViewController.swift
// csci342-asgn3-historical-map-ios
//
// Created by CY Lim on 10/05/2016.
// Copyright © 2016 CY Lim. All rights reserved.
//
import UIKit
class SatelliteViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
var activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0,0, 150, 150))
let API_KEY:String = "Xp0y6oG3BRlfCs3OPCS52FfTEpOclBinNwYEb0N7"
let baseURL: String = "https://api.nasa.gov/planetary/earth/imagery"
var latitude: String = "37.4249706"
var longitude: String = "-122.1878931"
let MAX_FETCH = 5
var locationHistory = [LocationInformation]()
var historyIndex = 0
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = .WhiteLarge
activityIndicator.color = UIColor.blackColor()
view.addSubview(activityIndicator)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if(!UIApplication.sharedApplication().isIgnoringInteractionEvents()){
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
getLocationHistoryFromAPI()
}
}
func getLocationHistoryFromAPI(){
performNASARequestSequence(){ result in
dispatch_async(dispatch_get_main_queue()){
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.activityIndicator.stopAnimating()
self.timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(SatelliteViewController.displayHistory), userInfo: nil, repeats: true)
}
}
}
func displayHistory(){
// Can't managed to sort correctly in getLocationHistoryFromAPI()
self.locationHistory.sortInPlace({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending })
let nextIndex = (historyIndex) % locationHistory.count
historyIndex += 1
self.imageView.image = locationHistory[nextIndex].image
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
self.dateLabel.text = dateFormatter.stringFromDate(locationHistory[nextIndex].date)
}
}
//MARK: GET Method to get Sequence of Image about particular location
extension SatelliteViewController {
struct LocationInformation {
var imageURL: NSURL
var date: NSDate
var image: UIImage?
}
func performNASARequestSequence(completion: (result: Bool) -> ()){
locationHistory.removeAll()
let calendar = NSCalendar.currentCalendar()
let dateComponent = NSDateComponents()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
let currentDate = NSDate()
for index in 0..<MAX_FETCH {
dateComponent.month = -index
if let date = calendar.dateByAddingComponents(dateComponent, toDate: currentDate, options: []){
let dateString = dateFormatter.stringFromDate(date)
self.performNASARequest(dateString){ result in
if index == self.MAX_FETCH - 1 {
completion(result: true)
}
}
}
}
}
func performNASARequest(date: String, completion: (result: Bool) -> ()){
let parameter: Dictionary = [
"api_key" : API_KEY,
"lat" : latitude,
"lon" : longitude,
"date" : date,
"cloud_score": "True"
]
let urlComponents = NSURLComponents(string: baseURL)!
var queryItems = [NSURLQueryItem]()
for (key, value) in parameter {
queryItems.append(NSURLQueryItem(name: key, value: value))
}
urlComponents.queryItems = queryItems
let url = urlComponents.URL!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.timeoutInterval = 5000
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let response = response as? NSHTTPURLResponse where 200...299 ~= response.statusCode {
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments )
if let result = json as? NSDictionary{
let urlString = result["url"] as? String
var dateString = result["date"] as? String
dateString = dateString?.substringWithRange(Range<String.Index>(dateString!.startIndex..<(dateString?.startIndex.advancedBy(10))!))
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
guard let imageURL = NSURL(string: urlString!), date = dateFormatter.dateFromString(dateString!) else {
completion(result: false)
return
}
self.fetchImage(LocationInformation(imageURL: imageURL, date: date, image: nil), completion: completion)
}
} catch {
print("json format issue")
}
} else {
print("Failed")
}
}.resume()
}
func fetchImage(location: LocationInformation, completion: (result: Bool) -> ()){
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(location.imageURL, completionHandler: {(data, response, error) in
if error != nil {
print("error with image url")
completion(result: false)
} else if let imageData = data, image = UIImage(data: imageData) {
self.locationHistory.append(LocationInformation(imageURL: location.imageURL, date: location.date, image: image))
completion(result: true)
}
}).resume()
}
}
| mit | f448bd562b9cda60a68d3697db8c591f | 29.417582 | 165 | 0.712428 | 4.082596 | false | false | false | false |
Eccelor/material-components-ios | components/AppBar/examples/AppBarImageryExample.swift | 1 | 3730 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import MaterialComponents
class AppBarImagerySwiftExample: UITableViewController {
let appBar = MDCAppBar()
override func viewDidLoad() {
super.viewDidLoad()
let headerView = appBar.headerViewController.headerView
// Create our custom image view and add it to the header view.
let imageView = UIImageView(image: self.headerBackgroundImage())
imageView.frame = headerView.bounds
// Ensure that the image view resizes in reaction to the header view bounds changing.
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Ensure that the image view is below other App Bar views (headerStackView).
headerView.insertSubview(imageView, at: 0)
// Scales up the image while the header is over-extending.
imageView.contentMode = .scaleAspectFill
// The header view does not clip to bounds by default so we ensure that the image is clipped.
imageView.clipsToBounds = true
// We want navigation bar + status bar tint color to be white, so we set tint color here and
// implement -preferredStatusBarStyle.
appBar.navigationBar.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes =
[ NSForegroundColorAttributeName: UIColor.white ]
// Make sure navigation bar background color is clear so the image view is visible.
appBar.navigationBar.backgroundColor = UIColor.clear
// Allow the header to show more of the image.
headerView.maximumHeight = 200
headerView.trackingScrollView = self.tableView
self.tableView.delegate = appBar.headerViewController
appBar.addSubviewsToParent()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
// Ensure that our status bar is white.
return .lightContent
}
// MARK: Typical configuration
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Imagery (Swift)"
self.addChildViewController(appBar.headerViewController)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func headerBackgroundImage() -> UIImage {
let bundle = Bundle(for: AppBarImagerySwiftExample.self)
let imagePath = bundle.path(forResource: "mdc_theme", ofType: "png")!
return UIImage(contentsOfFile: imagePath)!
}
}
// MARK: Catalog by convention
extension AppBarImagerySwiftExample {
class func catalogBreadcrumbs() -> [String] {
return ["App Bar", "Imagery (Swift)"]
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarImagerySwiftExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell!.layoutMargins = UIEdgeInsets.zero
return cell!
}
}
| apache-2.0 | eadc90d364b716f694ef45982036d6dd | 30.880342 | 97 | 0.736997 | 4.856771 | false | false | false | false |
davidprochazka/HappyDay | HappyDayMobileApp/HappyDay/NewTeamViewController.swift | 1 | 2280 | //
// NewTeamViewController.swift
// HappyDay
//
// Created by David Prochazka on 09/03/16.
// Copyright © 2016 David Prochazka. All rights reserved.
//
import UIKit
import MobileCoreServices
class NewTeamViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var imageView: UIImageView!
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.
}
@IBAction func save(sender: AnyObject) {
if let teamName = nameTextField.text {
if teamName != "" {
Team.createTeamWithName(teamName, andImage: imageView.image!)
dismissViewControllerAnimated(true, completion: nil)
} else {
nameTextField.becomeFirstResponder()
}
} else {
nameTextField.becomeFirstResponder()
}
}
@IBAction func cancel(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - ImagePicker
@IBAction func loadPhoto(sender : AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
picker.mediaTypes = [kUTTypeImage as String]
self.presentViewController(picker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
imageView.image = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
imageView.image = possibleImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-3.0 | 961b32f75a9a9c77aebfac927e049d14 | 31.557143 | 123 | 0.668714 | 5.919481 | false | false | false | false |
huonw/swift | test/SILGen/protocol_optional.swift | 3 | 3645 |
// RUN: %target-swift-emit-silgen -module-name protocol_optional -parse-as-library -disable-objc-attr-requires-foundation-module -enable-objc-interop -enable-sil-ownership %s | %FileCheck %s
@objc protocol P1 {
@objc optional func method(_ x: Int)
@objc optional var prop: Int { get }
@objc optional subscript (i: Int) -> Int { get }
}
// CHECK-LABEL: sil hidden @$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF : $@convention(thin) <T where T : P1> (@guaranteed T) -> ()
func optionalMethodGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed (Int) -> ()> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<@callee_guaranteed (Int) -> ()>
// CHECK: dynamic_method_br [[T]] : $T, #P1.method!1.foreign
var methodRef = t.method
}
// CHECK: } // end sil function '$S17protocol_optional0B13MethodGeneric1tyx_tAA2P1RzlF'
// CHECK-LABEL: sil hidden @$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> ()
func optionalPropertyGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign
var propertyRef = t.prop
}
// CHECK: } // end sil function '$S17protocol_optional0B15PropertyGeneric{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T where T : P1> (@guaranteed T) -> ()
func optionalSubscriptGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : @guaranteed $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $<τ_0_0 where τ_0_0 : P1> { var τ_0_0 } <T>
// CHECK: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: [[T_COPY:%.*]] = copy_value [[T]]
// CHECK: store [[T_COPY]] to [init] [[PT]] : $*T
// CHECK: [[OPT_BOX:%[0-9]+]] = alloc_box ${ var Optional<Int> }
// CHECK: project_box [[OPT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PT]] : $*T
// CHECK: [[T:%[0-9]+]] = load [copy] [[READ]] : $*T
// CHECK: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
// CHECK: [[INTCONV:%[0-9]+]] = function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC
// CHECK: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
var subscriptRef = t[5]
}
// CHECK: } // end sil function '$S17protocol_optional0B16SubscriptGeneric{{[_0-9a-zA-Z]*}}F'
| apache-2.0 | 553179b9d96dd13dbe192e03b512c5a1 | 52.470588 | 190 | 0.565182 | 2.758725 | false | false | false | false |
adityaparakh/HackIllinois2017App | healapp/UserFinalViewController.swift | 1 | 1678 | //
// UserFinalViewController.swift
// healapp
//
// Created by Admin on 2/26/17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
class UserFinalViewController: UIViewController {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var distance: UILabel!
@IBOutlet weak var tittle: UILabel!
@IBOutlet weak var reviews: UILabel!
@IBOutlet weak var disease: UILabel!
@IBOutlet weak var imocode: UILabel!
var userData: [String:AnyObject] = [:]
override func viewDidLoad() {
super.viewDidLoad()
print(userData)
name.text = userData["name"] as! String?
distance.text = String(userData["distance"] as! Int)
tittle.text = userData["title"] as! String?
reviews.text = "42 reviews"
disease.text = DISEASE
imocode.text = "IMOCODE:" + "\(IMOCODE)"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backbtn(_ sender: Any) {
self.performSegue(withIdentifier: "unwind", sender: self)
}
@IBAction func logout(_ sender: Any) {
self.performSegue(withIdentifier: "logout", sender: self)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | 0f796d305a231f84a83209226a51d0de | 30.641509 | 106 | 0.652952 | 4.333333 | false | false | false | false |
bigtreenono/NSPTools | RayWenderlich/Introduction to Swift/2 . Optionals/DemoOptionalsPlayground.playground/section-1.swift | 1 | 651 | // Playground - noun: a place where people can play
import UIKit
var movie:String? = "Attack of the Killer Tomatoes"
//movie = nil
//if let movie = movie {
// println(movie)
//} else {
// println("No movie to display")
//}
println(movie!)
var temp:String!
var i = 11
if i % 2 == 0 {
temp = "Even"
} else {
temp = "Odd"
}
println(temp)
class Game {
var player:Player?
}
class Player {
var name:String
init(name:String) {
self.name = name
}
}
var game = Game()
var player = Player(name: "Ray")
//game.player = player
if let playerName = game.player?.name {
println(playerName)
}
var name = game.player?.name ?? "Player 1"
| mit | e17fa8d46658ffd6d15f0ab6eb5a899e | 13.466667 | 51 | 0.634409 | 2.972603 | false | false | false | false |
guidomb/PortalView | Sources/UIKit/Renderers/TableRenderer.swift | 1 | 1877 | //
// TableRenderer.swift
// PortalView
//
// Created by Guido Marucci Blas on 2/14/17.
// Copyright © 2017 Guido Marucci Blas. All rights reserved.
//
import UIKit
internal struct TableRenderer<MessageType, CustomComponentRendererType: UIKitCustomComponentRenderer>: UIKitRenderer
where CustomComponentRendererType.MessageType == MessageType {
typealias CustomComponentRendererFactory = () -> CustomComponentRendererType
let properties: TableProperties<MessageType>
let style: StyleSheet<TableStyleSheet>
let layout: Layout
let rendererFactory: CustomComponentRendererFactory
func render(with layoutEngine: LayoutEngine, isDebugModeEnabled: Bool) -> Render<MessageType> {
let table = PortalTableView(
items: properties.items,
layoutEngine: layoutEngine,
rendererFactory: rendererFactory
)
table.isDebugModeEnabled = isDebugModeEnabled
table.showsVerticalScrollIndicator = properties.showsVerticalScrollIndicator
table.showsHorizontalScrollIndicator = properties.showsHorizontalScrollIndicator
table.apply(style: style.base)
table.apply(style: style.component)
layoutEngine.apply(layout: layout, to: table)
return Render(view: table, mailbox: table.mailbox)
}
}
extension UITableView {
fileprivate func apply(style: TableStyleSheet) {
self.separatorColor = style.separatorColor.asUIColor
}
}
extension TableItemSelectionStyle {
internal var asUITableViewCellSelectionStyle: UITableViewCellSelectionStyle {
switch self {
case .none:
return .none
case .`default`:
return .`default`
case .blue:
return .blue
case .gray:
return .gray
}
}
}
| mit | f8a77399f0fbb1168c6767be531a004b | 27.861538 | 116 | 0.674307 | 5.719512 | false | false | false | false |
digoreis/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0020.xcplaygroundpage/Contents.swift | 1 | 3305 | /*:
# Swift Language Version Build Configuration
* Proposal: [SE-0020](0020-if-swift-version.md)
* Author: [David Farler](https://github.com/bitjammer)
* Review Manager: [Doug Gregor](https://github.com/DougGregor)
* Status: **Implemented (Swift 2.2)**
* Commit: [apple/swift@c32fb8e](https://github.com/apple/swift/commit/c32fb8e7b9a67907e8b6580a46717c6a345ec7c6)
## Introduction
This proposal aims to add a new build configuration option to Swift
2.2: `#if swift`.
Swift-evolution threads:
- [Swift 2.2: #if swift language version](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/003385.html)
- [Review](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006398.html)
## Motivation
Over time, Swift syntax may change but library and package authors will
want their code to work with multiple versions of the language. Up until
now, the only recourse developers have is to maintain separate release
branches that follow the language. This gives developers another tool to
track syntax changes without having to maintain separate source trees.
We also want to ease the transition between language revisions for
package authors that distribute their source code, so clients can build
their package with older or newer Swift.
## Proposed solution
The solution is best illustrated with a simple example:
```swift
#if swift(>=2.2)
print("Active!")
#else
this! code! will! not! parse! or! produce! diagnostics!
#endif
```
## Detailed design
This will use existing version mechanics already present in the
compiler. The version of the language is baked into the compiler when
it's built, so we know how to determine whether a block of code is
active. If the version is at least as recent as specified in the
condition, the active branch is parsed and compiled into your code.
Like other build configurations, `#if swift` isn't line-based - it
encloses whole statements or declarations. However, unlike the others,
the compiler won't parse inactive branches guarded by `#if swift` or
emit lex diagnostics, so syntactic differences for other Swift versions
can be in the same file.
For now, we'll only expect up to two version components, since it will
be unlikely that a syntax change will make it in a +0.0.1 revision.
The argument to the configuration function is a unary prefix expression,
with one expected operator, `>=`, for simplicity. If the need arises,
this can be expanded to include other comparison operators.
## Impact on existing code
This mechanism is opt-in, so existing code won't be affected by this
change.
## Alternatives considered
We considered two other formats for the version argument:
- String literals (`#if swift("2.2")`): this allows us to embed an
arbitrary number of version components, but syntax changes are
unlikely in micro-revisions. If we need another version component, the
parser change won't be severe.
- Just plain `#if swift(2.2)`: Although `>=` is a sensible default, it
isn't clear what the comparison is here, and might be assumed to be
`==`.
- Argument lists (`#if swift(2, 2)`: This parses flexibly but can
indicate that the second `2` might be an argument with a different
meaning, instead of a component of the whole version.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | c4d3939a7e9196aec7bade1ba0fd3ea3 | 36.556818 | 125 | 0.763691 | 3.897406 | false | false | false | false |
evgenyneu/SigmaSwiftStatistics | SigmaSwiftStatisticsTests/VarianceTests.swift | 1 | 1277 | import XCTest
import SigmaSwiftStatistics
class VarianceDeviationTests: XCTestCase {
// MARK: - Sample variance
func testVarianceSample() {
let result = Sigma.varianceSample([1, 12, 19.5, -5, 3, 8])!
XCTAssertEqual(75.2416666667, Helpers.round10(result))
}
func testVarianceSample_whenSame() {
let result = Sigma.varianceSample([3, 3])!
XCTAssertEqual(0, Helpers.round10(result))
}
func testVarianceSample_whenOne() {
let result = Sigma.varianceSample([1])
XCTAssert(result == nil)
}
func testVarianceSample_whenEmpty() {
let result = Sigma.varianceSample([])
XCTAssert(result == nil)
}
// MARK: - Population variance
func testVariancePopulation() {
let result = Sigma.variancePopulation([1, 12, 19.5, -5, 3, 8])!
XCTAssertEqual(62.7013888889, Helpers.round10(result))
}
func testVariancePopulation_whenSame() {
let result = Sigma.variancePopulation([3, 3])!
XCTAssertEqual(0, Helpers.round10(result))
}
func testVariancePopulation_whenOne() {
let result = Sigma.variancePopulation([1])!
XCTAssertEqual(0, Helpers.round10(result))
}
func testVariancePopulation_whenEmpty() {
let result = Sigma.variancePopulation([])
XCTAssert(result == nil)
}
}
| mit | 8f7db133833c04386acd10baf1a3f34d | 25.061224 | 67 | 0.681284 | 3.893293 | false | true | false | false |
gowansg/firefox-ios | Utils/Extensions/HashExtensions.swift | 23 | 2307 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension NSData {
public var sha1: NSData {
let len = Int(CC_SHA1_DIGEST_LENGTH)
var digest = UnsafeMutablePointer<UInt8>.alloc(len)
CC_SHA1(self.bytes, CC_LONG(self.length), digest)
return NSData(bytes: UnsafePointer<Void>(digest), length: len)
}
public var sha256: NSData {
let len = Int(CC_SHA256_DIGEST_LENGTH)
var digest = UnsafeMutablePointer<UInt8>.alloc(len)
CC_SHA256(self.bytes, CC_LONG(self.length), digest)
return NSData(bytes: UnsafePointer<Void>(digest), length: len)
}
}
extension String {
public var sha1: NSData {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
return data.sha1
}
public var sha256: NSData {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
return data.sha256
}
}
extension NSData {
public func hmacSha256WithKey(key: NSData) -> NSData {
let len = Int(CC_SHA256_DIGEST_LENGTH)
var digest = UnsafeMutablePointer<Void>.alloc(len)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256),
key.bytes, Int(key.length),
self.bytes, Int(self.length),
digest)
return NSData(bytes: UnsafePointer<Void>(digest), length: len)
}
}
extension String {
public var utf8EncodedData: NSData? {
return self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
}
extension NSData {
public var utf8EncodedString: String? {
return NSString(data: self, encoding: NSUTF8StringEncoding) as String?
}
}
extension NSData {
public func xoredWith(other: NSData) -> NSData? {
if self.length != other.length {
return nil
}
var xoredBytes = [UInt8](count: self.length, repeatedValue: 0)
let selfBytes = UnsafePointer<UInt8>(self.bytes)
let otherBytes = UnsafePointer<UInt8>(other.bytes)
for i in 0..<self.length {
xoredBytes[i] = selfBytes[i] ^ otherBytes[i]
}
return NSData(bytes: xoredBytes, length: self.length)
}
}
| mpl-2.0 | 40258456c4259cd3b90c8f23865298e4 | 30.175676 | 88 | 0.648461 | 3.923469 | false | false | false | false |
alexlivenson/BlueLibrarySwift | BlueLibrarySwift/ViewController.swift | 1 | 6405 | //
// ViewController.swift
// BlueLibrarySwift
//
// Created by alex livenson on 9/23/15.
// Copyright © 2015 alex livenson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var dataTable: UITableView!
@IBOutlet weak var toolbar: UIToolbar!
@IBOutlet weak var scroller: HorizontalScroller!
@IBOutlet weak var undoButton: UIBarButtonItem!
@IBOutlet weak var deleteButton: UIBarButtonItem!
let userDefaults = NSUserDefaults.standardUserDefaults()
let notificationCenter = NSNotificationCenter.defaultCenter()
let libraryAPI = LibraryAPI.sharedInstance
private var allAlbums = [Album]()
private var currentAlbumData: (titles: [String], values: [String])?
private var currentAlbumIndex = 0
// We will use this array as a stick to push / pop operation for the undo option
private var undoStack: [(Album, Int)] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// 1
self.navigationController?.navigationBar.translucent = false
currentAlbumIndex = 0
// 2
allAlbums = libraryAPI.getAlbums()
// 3
dataTable.delegate = self
dataTable.dataSource = self
dataTable.backgroundView = nil
view.addSubview(dataTable)
loadPreviousState()
scroller.delegate = self
reloadScroller()
showDataForAlbum(currentAlbumIndex)
styleToolbarButtons()
notificationCenter.addObserver(self,
selector: "saveCurrentState",
name: UIApplicationDidEnterBackgroundNotification,
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func styleToolbarButtons() {
if allAlbums.count == 0 {
deleteButton.enabled = false
}
if undoStack.count == 0 {
undoButton.enabled = false
}
}
func showDataForAlbum(albumIndex: Int) {
if albumIndex < allAlbums.count && albumIndex > -1 {
let album = allAlbums[albumIndex]
currentAlbumData = album.ae_tableRepresentation()
} else {
currentAlbumData = nil
}
dataTable.reloadData()
}
func reloadScroller() {
allAlbums = libraryAPI.getAlbums()
if currentAlbumIndex < 0 {
currentAlbumIndex = 0
} else if currentAlbumIndex >= allAlbums.count {
currentAlbumIndex = allAlbums.count - 1
}
scroller.reload()
showDataForAlbum(currentAlbumIndex)
}
// MARK: Memento Pattern
func saveCurrentState() {
userDefaults.setInteger(currentAlbumIndex, forKey: "currentAlbumIndex")
}
func loadPreviousState() {
currentAlbumIndex = userDefaults.integerForKey("currentAlbumIndex")
showDataForAlbum(currentAlbumIndex)
}
func addAlbumAtIndex(album: Album, index: Int) {
libraryAPI.addAlbum(album, index: index)
currentAlbumIndex = index
reloadScroller()
}
@IBAction func undoAction(sender: UIBarButtonItem) {
// 1
if undoStack.count > 0 {
let (deletedAlbum, index) = undoStack.popLast()!
addAlbumAtIndex(deletedAlbum, index: index)
}
// 2
if undoStack.count == 0 {
undoButton.enabled = false
}
// 3
deleteButton.enabled = true
}
@IBAction func deleteAlbum(sender: UIBarButtonItem) {
// 1
let deleteAlbum = allAlbums[currentAlbumIndex]
// 2
let undoAction = (deleteAlbum, currentAlbumIndex)
undoStack.append(undoAction)
// 3
libraryAPI.deleteAlbum(currentAlbumIndex)
reloadScroller()
// 4
undoButton?.enabled = true
// 5
if allAlbums.count == 0 {
deleteButton.enabled = false
}
}
deinit {
notificationCenter.removeObserver(self)
}
}
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let rows = currentAlbumData?.titles.count {
return rows
}
return 0
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if let albumData = currentAlbumData {
cell.textLabel?.text = albumData.titles[indexPath.row]
cell.detailTextLabel?.text = albumData.values[indexPath.row]
}
return cell
}
}
extension ViewController: UITableViewDelegate {
}
extension ViewController: HorizontalScrollerDelegate {
func horizontalScrollerClickedViewAtIndex(scroller: HorizontalScroller, index: Int) {
let previousAlbumView = scroller.viewAtIndex(currentAlbumIndex) as! AlbumView
previousAlbumView.highlightAlbum(false)
currentAlbumIndex = index
let albumView = scroller.viewAtIndex(index) as! AlbumView
albumView.highlightAlbum(true)
showDataForAlbum(index)
}
func numberOfViewsForHorizontalScroller(scroller: HorizontalScroller) -> Int {
return allAlbums.count
}
func horizontalScrollerViewAtIndex(scroller: HorizontalScroller, index: Int) -> UIView {
let album = allAlbums[index]
let albumView = AlbumView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), albumCover: album.coverUrl)
if currentAlbumIndex == index {
albumView.highlightAlbum(true)
} else {
albumView.highlightAlbum(false)
}
return albumView
}
func initialViewIndex(scroller: HorizontalScroller) -> Int {
return currentAlbumIndex
}
}
| mit | c9d97cc764b75913fc0930cb2ee48094 | 27.846847 | 114 | 0.61649 | 5.202275 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | nRF Toolbox/Profiles/Template/PeripheralViewController.swift | 1 | 14286 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import CoreBluetooth
struct PeripheralDescription {
struct Service {
struct Characteristic {
enum Property {
case read, notify(Bool)
}
let uuid: CBUUID
let properties: Property?
}
let uuid: CBUUID
let characteristics: [Characteristic]
}
let uuid: CBUUID?
let services: [Service]
let mandatoryServices: [CBUUID]?
let mandatoryCharacteristics: [CBUUID]?
}
class PeripheralViewController: UIViewController, StatusDelegate, AlertPresenter {
private lazy var peripheralManager = PeripheralManager(peripheral: peripheralDescription)
var navigationTitle: String { "" }
var peripheralDescription: PeripheralDescription { SystemLog(category: .app, type: .fault).fault("Override this method in subclass") }
var requiredServices: [CBUUID]?
var activePeripheral: CBPeripheral?
private var savedView: UIView!
private var discoveredServices: [CBUUID] = []
private var discoveredCharacteristics: [CBUUID] = []
private var serviceFinderTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
savedView = view
self.view = InfoActionView.instanceWithParams()
peripheralManager.delegate = self
navigationItem.title = navigationTitle
if #available(iOS 11.0, *) {
navigationController?.navigationItem.largeTitleDisplayMode = .never
}
AppUtilities.requestNotificationAuthorization { (_, error) in
if let e = error {
self.displayErrorAlert(error: e)
}
}
}
@objc func disconnect() {
guard let peripheral = activePeripheral else { return }
peripheralManager.closeConnection(peripheral: peripheral)
}
@objc func didEnterBackground(notification: Notification) {
guard let peripheral = activePeripheral else { return }
let name = peripheral.name ?? "peripheral"
let msg = "You are still connected to \(name). It will collect data also in background."
AppUtilities.showBackgroundNotification(title: "Still connected", message: msg)
}
// MARK: Status changed
func statusDidChanged(_ status: PeripheralStatus) {
SystemLog(category: .ble, type: .debug).log(message: "Changed Bluetooth status in \(String(describing: type(of: self))), status: \(status)")
switch status {
case .poweredOff:
onPowerOffStatus()
case .disconnected(let error):
onDisconnectedStatus(error: error)
case .connecting:
onConnectingStatus()
case .connected(let peripheral):
onConnectedStatus(peripheral: peripheral)
case .discoveringServicesAndCharacteristics:
onDiscoveringServicesAndCharacteristics()
case .discoveredRequiredServicesAndCharacteristics:
onDiscoveredMandatoryServices()
case .unauthorized:
onUnauthorizedStatus()
}
}
func onPowerOffStatus() {
serviceFinderTimer?.invalidate()
activePeripheral = nil
let bSettings: InfoActionView.ButtonSettings = ("Settings", {
UIApplication.shared.openSettings()
})
let notContent = InfoActionView.instanceWithParams(message: "Bluetooth is powered off", buttonSettings: bSettings)
view = notContent
}
func onDisconnectedStatus(error: Error?) {
serviceFinderTimer?.invalidate()
activePeripheral = nil
let bSettings: InfoActionView.ButtonSettings = ("Connect", { [unowned self] in
self.openConnectorViewController()
})
let notContent = InfoActionView.instanceWithParams(message: "No connected device", buttonSettings: bSettings)
notContent.actionButton.style = .mainAction
view = notContent
switch error {
case let e as ConnectionTimeoutError :
displaySettingsAlert(title: e.title , message: e.readableMessage)
case let e?:
displayErrorAlert(error: e)
default:
break
}
if case .background = UIApplication.shared.applicationState {
let name = activePeripheral?.name ?? "Peripheral"
let msg = "\(name) is disconnected."
AppUtilities.showBackgroundNotification(title: "Disconnected", message: msg)
}
}
func onConnectingStatus() {
let notContent = InfoActionView.instanceWithParams(message: "Connecting...")
notContent.actionButton.style = .mainAction
view = notContent
dismiss(animated: true, completion: nil)
}
func onConnectedStatus(peripheral: CBPeripheral) {
activePeripheral = peripheral
activePeripheral?.delegate = self
activePeripheral?.discoverServices(peripheralDescription.services.map { $0.uuid } )
if let requiredServices = peripheralDescription.mandatoryServices, !requiredServices.isEmpty {
statusDidChanged(.discoveringServicesAndCharacteristics)
serviceFinderTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { [weak self] (t) in
self?.displayBindingErrorAlert()
self?.disconnect()
t.invalidate()
}
} else {
statusDidChanged(.discoveredRequiredServicesAndCharacteristics)
}
}
func onDiscoveringServicesAndCharacteristics() {
let notContent = InfoActionView.instanceWithParams(message: "Discovering services...")
notContent.messageLabel.text = "Looking for mandatory services and characteristics"
notContent.titleLabel.numberOfLines = 0
notContent.titleLabel.textAlignment = .center
notContent.actionButton.style = .mainAction
view = notContent
}
func onDiscoveredMandatoryServices() {
serviceFinderTimer?.invalidate()
view = savedView
}
func onUnauthorizedStatus() {
let bSettings: InfoActionView.ButtonSettings = ("Settings", {
UIApplication.shared.openSettings()
})
let notContent = InfoActionView.instanceWithParams(message: "Using Bluetooth is not Allowed", buttonSettings: bSettings)
notContent.messageLabel.text = "It seems you denied nRF-Toolbox to use Bluetooth. Open settings and allow to use Bluetooth."
view = notContent
}
@objc func openConnectorViewController() {
let scanner = PeripheralScanner(services: peripheralDescription.uuid.map {[$0]})
let connectionController = ConnectionViewController(scanner: scanner)
connectionController.delegate = self
let nc = UINavigationController.nordicBranded(rootViewController: connectionController)
nc.modalPresentationStyle = .formSheet
present(nc, animated: true, completion: nil)
}
func didDiscover(service: CBService, for peripheral: CBPeripheral) {
let characteristics: [CBUUID]? = peripheralDescription
.services
.first(where: { $0.uuid == service.uuid })?
.characteristics
.map { $0.uuid }
peripheral.discoverCharacteristics(characteristics, for: service)
discoveredServices.append(service.uuid)
let requiredServices = peripheralDescription.mandatoryServices ?? []
let requiredCharacteristics = peripheralDescription.mandatoryCharacteristics ?? []
if Set(requiredServices).subtracting(Set(discoveredServices)).isEmpty &&
Set(requiredCharacteristics).subtracting(Set(discoveredCharacteristics)).isEmpty &&
peripheralManager.status != .discoveredRequiredServicesAndCharacteristics {
peripheralManager.status = .discoveredRequiredServicesAndCharacteristics
}
}
func didDiscover(characteristic: CBCharacteristic, for service: CBService, peripheral: CBPeripheral) {
peripheralDescription.services
.first(where: { $0.uuid == service.uuid })?.characteristics
.first(where: { $0.uuid == characteristic.uuid })
.flatMap {
switch $0.properties {
case .read: peripheral.readValue(for: characteristic)
case .notify(let enabled): peripheral.setNotifyValue(enabled, for: characteristic)
default: break
}
}
discoveredCharacteristics.append(characteristic.uuid)
let requiredServices = peripheralDescription.mandatoryServices ?? []
let requiredCharacteristics = peripheralDescription.mandatoryCharacteristics ?? []
if Set(requiredServices).subtracting(Set(discoveredServices)).isEmpty &&
Set(requiredCharacteristics).subtracting(Set(discoveredCharacteristics)).isEmpty &&
peripheralManager.status != .discoveredRequiredServicesAndCharacteristics {
peripheralManager.status = .discoveredRequiredServicesAndCharacteristics
}
}
func didUpdateValue(for characteristic: CBCharacteristic) {
SystemLog(category: .ble, type: .debug).log(message: "Cannot handle update value for characteristic \(characteristic)")
}
}
extension PeripheralViewController {
private func displaySettingsAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { _ in
UIApplication.shared.openSettings()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(settingsAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
private func displayBindingErrorAlert() {
let title = "No services discovered"
let message = "Required service has not been discovered. Check your device, or try to restart Bluetooth in Settings."
displaySettingsAlert(title: title, message: message)
}
}
extension PeripheralViewController: ConnectionViewControllerDelegate {
func requestConnection(to peripheral: Peripheral) {
peripheralManager.connect(peripheral: peripheral)
}
}
extension PeripheralViewController: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
SystemLog(category: .ble, type: .error).log(message: "Services discovery failed: \(error.localizedDescription)")
return
}
SystemLog(category: .ble, type: .debug).log(message: """
Found services:
\(peripheral.services.debugDescription)
in peripheral: \(peripheral)
""")
peripheral.services?.forEach { [unowned peripheral] service in
didDiscover(service: service, for: peripheral)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
SystemLog(category: .ble, type: .error).log(message: "Characteristic discovery failed: \(error.localizedDescription)")
return
}
SystemLog(category: .ble, type: .debug).log(message: "Discovered characteristics \(service.characteristics.debugDescription) for service: \(service)")
service.characteristics?.forEach { [unowned service] ch in
didDiscover(characteristic: ch, for: service, peripheral: peripheral)
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
SystemLog(category: .ble, type: .error).log(message: "Update value for characteristic \(characteristic) failed with error: \(error.localizedDescription). Peripheral: \(peripheral)")
return
}
SystemLog(category: .ble, type: .debug).log(message: "New value in characteristic: \(characteristic.debugDescription)")
didUpdateValue(for: characteristic)
}
@objc func dismissPresentedViewController() {
presentedViewController?.dismiss(animated: true, completion: nil)
}
}
| bsd-3-clause | 674cd97f6fc212ad5f0dc1e0e828a7bb | 39.585227 | 193 | 0.668627 | 5.415466 | false | false | false | false |
uasys/swift | validation-test/compiler_crashers_2_fixed/0020-rdar21598514.swift | 66 | 5661 | // RUN: not %target-swift-frontend %s -typecheck
protocol Resettable : AnyObject {
func reset()
}
internal var _allResettables: [Resettable] = []
public class TypeIndexed<Value> : Resettable {
public init(_ value: Value) {
self.defaultValue = value
_allResettables.append(self)
}
public subscript(t: Any.Type) -> Value {
get {
return byType[ObjectIdentifier(t)] ?? defaultValue
}
set {
byType[ObjectIdentifier(t)] = newValue
}
}
public func reset() { byType = [:] }
internal var byType: [ObjectIdentifier:Value] = [:]
internal var defaultValue: Value
}
public protocol Wrapper {
typealias Base
init(_: Base)
var base: Base {get set}
}
public protocol LoggingType : Wrapper {
typealias Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return self.dynamicType
}
}
public class IteratorLog {
public static func dispatchTester<G : IteratorProtocol>(
g: G
) -> LoggingIterator<LoggingIterator<G>> {
return LoggingIterator(LoggingIterator(g))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base : IteratorProtocol>
: IteratorProtocol, LoggingType {
typealias Log = IteratorLog
public init(_ base: Base) {
self.base = base
}
public mutating func next() -> Base.Element? {
++Log.next[selfType]
return base.next()
}
public var base: Base
}
public class SequenceLog {
public class func dispatchTester<S: Sequence>(
s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(LoggingSequence(s))
}
public static var iterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var map = TypeIndexed(0)
public static var filter = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _preprocessingPass = TypeIndexed(0)
public static var _copyToNativeArrayBuffer = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
}
public protocol LoggingSequenceType : Sequence, LoggingType {
typealias Base : Sequence
}
extension LoggingSequenceType {
public init(_ base: Base) {
self.base = base
}
public func makeIterator() -> LoggingIterator<Base.Iterator> {
++SequenceLog.iterator[selfType]
return LoggingIterator(base.makeIterator())
}
public func underestimatedCount() -> Int {
++SequenceLog.underestimatedCount[selfType]
return base.underestimatedCount()
}
public func map<T>(
transform: (Base.Iterator.Element) -> T
) -> [T] {
++SequenceLog.map[selfType]
return base.map(transform)
}
public func filter(
isIncluded: (Base.Iterator.Element) -> Bool
) -> [Base.Iterator.Element] {
++SequenceLog.filter[selfType]
return base.filter(isIncluded)
}
public func _customContainsEquatableElement(
element: Base.Iterator.Element
) -> Bool? {
++SequenceLog._customContainsEquatableElement[selfType]
return base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(
_ preprocess: (Self) -> R
) -> R? {
++SequenceLog._preprocessingPass[selfType]
return base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
++SequenceLog._copyToNativeArrayBuffer[selfType]
return base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) {
++SequenceLog._copyContents[selfType]
return base._copyContents(initializing: ptr)
}
}
public struct LoggingSequence<Base_: Sequence> : LoggingSequenceType {
typealias Log = SequenceLog
typealias Base = Base_
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public class CollectionLog : SequenceLog {
public class func dispatchTester<C: Collection>(
c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(LoggingCollection(c))
}
static var subscriptIndex = TypeIndexed(0)
static var subscriptRange = TypeIndexed(0)
static var isEmpty = TypeIndexed(0)
static var count = TypeIndexed(0)
static var _customIndexOfEquatableElement = TypeIndexed(0)
static var first = TypeIndexed(0)
}
public protocol LoggingCollectionType : Collection, LoggingSequenceType {
typealias Base : Collection
}
extension LoggingCollectionType {
subscript(position: Base.Index) -> Base.Iterator.Element {
++CollectionLog.subscriptIndex[selfType]
return base[position]
}
subscript(_prext_bounds: Range<Base.Index>) -> Base._prext_SubSequence {
++CollectionLog.subscriptRange[selfType]
return base[_prext_bounds]
}
var isEmpty: Bool {
++CollectionLog.isEmpty[selfType]
return base.isEmpty
}
var count: Base.Index.Distance {
++CollectionLog.count[selfType]
return base.count
}
func _customIndexOfEquatableElement(element: Iterator.Element) -> Base.Index?? {
++CollectionLog._customIndexOfEquatableElement[selfType]
return base._customIndexOfEquatableElement(element)
}
var first: Iterator.Element? {
++CollectionLog.first[selfType]
return base.first
}
}
struct LoggingCollection<Base_: Collection> : LoggingCollectionType {}
| apache-2.0 | 583750932fe171bfdcad740724b2d7f4 | 24.731818 | 82 | 0.704469 | 4.314787 | false | false | false | false |
apple/swift | benchmark/single-source/ArrayAppend.swift | 1 | 11364 | //===--- ArrayAppend.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 test checks the performance of appending to an array.
//
// Note: Several benchmarks are marked .unstable until we have a way
// of controlling malloc behavior from the benchmark driver.
import TestsUtils
let t: [BenchmarkCategory] = [.validation, .api, .Array]
public let benchmarks = [
BenchmarkInfo(name: "ArrayAppend", runFunction: run_ArrayAppend, tags: t + [.unstable], legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendArrayOfInt", runFunction: run_ArrayAppendArrayOfInt, tags: t,
setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendAscii", runFunction: run_ArrayAppendAscii, tags: t, legacyFactor: 34),
BenchmarkInfo(name: "ArrayAppendAsciiSubstring", runFunction: run_ArrayAppendAsciiSubstring, tags: t, legacyFactor: 36),
BenchmarkInfo(name: "ArrayAppendFromGeneric", runFunction: run_ArrayAppendFromGeneric, tags: t,
setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendGenericStructs", runFunction: run_ArrayAppendGenericStructs, tags: t,
setUpFunction: { otherStructs = Array(repeating: S(x: 3, y: 4.2), count: 10_000) },
tearDownFunction: { otherStructs = nil }, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendLatin1", runFunction: run_ArrayAppendLatin1, tags: t + [.unstable], legacyFactor: 34),
BenchmarkInfo(name: "ArrayAppendLatin1Substring", runFunction: run_ArrayAppendLatin1Substring, tags: t, legacyFactor: 36),
BenchmarkInfo(name: "ArrayAppendLazyMap", runFunction: run_ArrayAppendLazyMap, tags: t,
setUpFunction: { blackHole(array) }, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendOptionals", runFunction: run_ArrayAppendOptionals, tags: t + [.unstable],
setUpFunction: { otherOptionalOnes = Array(repeating: 1, count: 10_000) },
tearDownFunction: { otherOptionalOnes = nil }, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendRepeatCol", runFunction: run_ArrayAppendRepeatCol, tags: t + [.unstable], legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendReserved", runFunction: run_ArrayAppendReserved, tags: t, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendSequence", runFunction: run_ArrayAppendSequence, tags: t, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendStrings", runFunction: run_ArrayAppendStrings, tags: t,
setUpFunction: { otherStrings = stride(from: 0, to: 10_000, by: 1).map { "\($0)" } },
tearDownFunction: { otherStrings = nil }, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendToFromGeneric", runFunction: run_ArrayAppendToFromGeneric, tags: t + [.unstable],
setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendToGeneric", runFunction: run_ArrayAppendToGeneric, tags: t,
setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),
BenchmarkInfo(name: "ArrayAppendUTF16", runFunction: run_ArrayAppendUTF16, tags: t + [.unstable], legacyFactor: 34),
BenchmarkInfo(name: "ArrayAppendUTF16Substring", runFunction: run_ArrayAppendUTF16Substring, tags: t, legacyFactor: 36),
BenchmarkInfo(name: "ArrayPlusEqualArrayOfInt", runFunction: run_ArrayPlusEqualArrayOfInt, tags: t + [.unstable],
setUpFunction: ones, tearDownFunction: releaseOnes, legacyFactor: 10),
BenchmarkInfo(name: "ArrayPlusEqualFiveElementCollection", runFunction: run_ArrayPlusEqualFiveElementCollection, tags: t + [.unstable], legacyFactor: 37),
BenchmarkInfo(name: "ArrayPlusEqualSingleElementCollection", runFunction: run_ArrayPlusEqualSingleElementCollection, tags: t, legacyFactor: 47),
BenchmarkInfo(name: "ArrayPlusEqualThreeElements", runFunction: run_ArrayPlusEqualThreeElements, tags: t, legacyFactor: 10),
]
var otherOnes: [Int]!
var otherOptionalOnes: [Int?]!
var otherStrings: [String]!
var otherStructs: [S<Int, Double>]!
let array = Array(0..<10_000)
func ones() { otherOnes = Array(repeating: 1, count: 10_000) }
func releaseOnes() { otherOnes = nil }
// Append single element
@inline(never)
public func run_ArrayAppend(_ n: Int) {
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<40000 {
nums.append(1)
}
}
}
// Append single element with reserve
@inline(never)
public func run_ArrayAppendReserved(_ n: Int) {
for _ in 0..<n {
var nums = [Int]()
nums.reserveCapacity(40000)
for _ in 0..<40000 {
nums.append(1)
}
}
}
// Append a sequence. Length of sequence unknown so
// can't pre-reserve capacity.
@inline(never)
public func run_ArrayAppendSequence(_ n: Int) {
let seq = stride(from: 0, to: 10_000, by: 1)
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
nums.append(contentsOf: seq)
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendArrayOfInt(_ n: Int) {
let other: [Int] = otherOnes
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
nums.append(contentsOf: other)
}
}
}
// Identical to run_ArrayAppendArrayOfInt
// except +=, to check equally performant.
@inline(never)
public func run_ArrayPlusEqualArrayOfInt(_ n: Int) {
let other: [Int] = otherOnes
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendStrings(_ n: Int) {
let other: [String] = otherStrings
for _ in 0..<n {
var nums = [String]()
// lower inner count due to string slowness
for _ in 0..<4 {
nums += other
}
}
}
struct S<T,U> {
var x: T
var y: U
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendGenericStructs(_ n: Int) {
let other: [S<Int, Double>] = otherStructs
for _ in 0..<n {
var nums = [S<Int,Double>]()
for _ in 0..<8 {
nums += other
}
}
}
// Append another array. Length of sequence known so
// can pre-reserve capacity.
@inline(never)
public func run_ArrayAppendOptionals(_ n: Int) {
let other: [Int?] = otherOptionalOnes
for _ in 0..<n {
var nums = [Int?]()
for _ in 0..<8 {
nums += other
}
}
}
// Append a lazily-mapped array. Length of sequence known so
// can pre-reserve capacity, but no optimization points used.
@inline(never)
public func run_ArrayAppendLazyMap(_ n: Int) {
let other = array.lazy.map { $0 * 2 }
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
// Append a Repeat collection. Length of sequence known so
// can pre-reserve capacity, but no optimization points used.
@inline(never)
public func run_ArrayAppendRepeatCol(_ n: Int) {
let other = repeatElement(1, count: 10_000)
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
nums += other
}
}
}
// Append an array as a generic sequence to another array
@inline(never)
public func appendFromGeneric<
S: Sequence
>(array: inout [S.Element], sequence: S) {
array.append(contentsOf: sequence)
}
@inline(never)
public func run_ArrayAppendFromGeneric(_ n: Int) {
let other: [Int] = otherOnes
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
appendFromGeneric(array: &nums, sequence: other)
}
}
}
// Append an array to an array as a generic range replaceable collection.
@inline(never)
public func appendToGeneric<
R: RangeReplaceableCollection
>(collection: inout R, array: [R.Element]) {
collection.append(contentsOf: array)
}
@inline(never)
public func run_ArrayAppendToGeneric(_ n: Int) {
let other: [Int] = otherOnes
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
appendToGeneric(collection: &nums, array: other)
}
}
}
// Append an array as a generic sequence to an array as a generic range
// replaceable collection.
@inline(never)
public func appendToFromGeneric<
R: RangeReplaceableCollection, S: Sequence
>(collection: inout R, sequence: S)
where R.Element == S.Element {
collection.append(contentsOf: sequence)
}
@inline(never)
public func run_ArrayAppendToFromGeneric(_ n: Int) {
let other: [Int] = otherOnes
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<8 {
appendToFromGeneric(collection: &nums, sequence: other)
}
}
}
// Append a single element array with the += operator
@inline(never)
public func run_ArrayPlusEqualSingleElementCollection(_ n: Int) {
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<10_000 {
nums += [1]
}
}
}
// Append a five element array with the += operator
@inline(never)
public func run_ArrayPlusEqualFiveElementCollection(_ n: Int) {
for _ in 0..<n {
var nums = [Int]()
for _ in 0..<10_000 {
nums += [1, 2, 3, 4, 5]
}
}
}
@inline(never)
public func appendThreeElements(_ a: inout [Int]) {
a += [1, 2, 3]
}
@inline(never)
public func run_ArrayPlusEqualThreeElements(_ n: Int) {
for _ in 0..<(1_000 * n) {
var a: [Int] = []
appendThreeElements(&a)
}
}
// Append the utf8 elements of an ascii string to a [UInt8]
@inline(never)
public func run_ArrayAppendAscii(_ n: Int) {
let s = "the quick brown fox jumps over the lazy dog!"
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getString(s).utf8
}
}
}
// Append the utf8 elements of a latin1 string to a [UInt8]
@inline(never)
public func run_ArrayAppendLatin1(_ n: Int) {
let s = "the quick brown fox jumps over the lazy dog\u{00A1}"
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getString(s).utf8
}
}
}
// Append the utf8 elements of an utf16 string to a [UInt8]
@inline(never)
public func run_ArrayAppendUTF16(_ n: Int) {
let s = "the quick brown 🦊 jumps over the lazy dog"
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getString(s).utf8
}
}
}
// Append the utf8 elements of an ascii substring to a [UInt8]
@inline(never)
public func run_ArrayAppendAsciiSubstring(_ n: Int) {
let s = "the quick brown fox jumps over the lazy dog!"[...]
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getSubstring(s).utf8
}
}
}
// Append the utf8 elements of a latin1 substring to a [UInt8]
@inline(never)
public func run_ArrayAppendLatin1Substring(_ n: Int) {
let s = "the quick brown fox jumps over the lazy dog\u{00A1}"[...]
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getSubstring(s).utf8
}
}
}
// Append the utf8 elements of an utf16 substring to a [UInt8]
@inline(never)
public func run_ArrayAppendUTF16Substring(_ n: Int) {
let s = "the quick brown 🦊 jumps over the lazy dog"[...]
for _ in 0..<n {
var nums = [UInt8]()
for _ in 0..<3_000 {
nums += getSubstring(s).utf8
}
}
}
| apache-2.0 | f0163bcf648a69698d506db73a8e49d8 | 29.047619 | 156 | 0.664994 | 3.633397 | false | false | false | false |
brettg/Signal-iOS | Signal/src/environment/ExperienceUpgrades/ExperienceUpgrade.swift | 2 | 2742 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
class ExperienceUpgrade: TSYapDatabaseObject {
let title: String
let body: String
let image: UIImage?
var seenAt: Date?
required init(uniqueId: String, title: String, body: String, image: UIImage) {
self.title = title
self.body = body
self.image = image
super.init(uniqueId: uniqueId)
}
override required init(uniqueId: String) {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
super.init(uniqueId: uniqueId)
}
required init!(coder: NSCoder!) {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
super.init(coder: coder)
}
required init(dictionary dictionaryValue: [AnyHashable : Any]!) throws {
// This is the unfortunate seam between strict swift and fast-and-loose objc
// we can't leave these properties nil, since we really "don't know" that the superclass
// will assign them.
self.title = "New Feature"
self.body = "Bug fixes and performance improvements."
self.image = nil
try super.init(dictionary: dictionaryValue)
}
override class func storageBehaviorForProperty(withKey propertyKey: String) -> MTLPropertyStorage {
// These exist in a hardcoded set - no need to save them, plus it allows us to
// update copy/image down the line if there was a typo and we want to re-expose
// these models in a "change log" archive.
if propertyKey == "title" || propertyKey == "body" || propertyKey == "image" {
return MTLPropertyStorageNone
} else if propertyKey == "uniqueId" || propertyKey == "seenAt" {
return super.storageBehaviorForProperty(withKey: propertyKey)
} else {
// Being conservative here in case we rename a property.
assertionFailure("unknown property \(propertyKey)")
return super.storageBehaviorForProperty(withKey: propertyKey)
}
}
func markAsSeen(transaction: YapDatabaseReadWriteTransaction) {
self.seenAt = Date()
super.save(with: transaction)
}
}
| gpl-3.0 | 57db2a66ae2624a0a8e665ac28dc1b08 | 38.73913 | 103 | 0.645879 | 4.57 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/EditHistory/EditHistoryCoordinatorBridgePresenter.swift | 1 | 4082 | // File created from FlowTemplate
// $ createRootCoordinator.sh Room/EditHistory EditHistory
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
@objc protocol EditHistoryCoordinatorBridgePresenterDelegate {
func editHistoryCoordinatorBridgePresenterDelegateDidComplete(_ coordinatorBridgePresenter: EditHistoryCoordinatorBridgePresenter)
}
/// EditHistoryCoordinatorBridgePresenter enables to start EditHistoryCoordinator from a view controller.
/// This bridge is used while waiting for global usage of coordinator pattern.
@objcMembers
final class EditHistoryCoordinatorBridgePresenter: NSObject {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let event: MXEvent
private var coordinator: EditHistoryCoordinator?
// MARK: Public
weak var delegate: EditHistoryCoordinatorBridgePresenterDelegate?
// MARK: - Setup
init(session: MXSession,
event: MXEvent) {
self.session = session
self.event = event
super.init()
}
// MARK: - Public
// NOTE: Default value feature is not compatible with Objective-C.
// func present(from viewController: UIViewController, animated: Bool) {
// self.present(from: viewController, animated: animated)
// }
func present(from viewController: UIViewController, animated: Bool) {
guard let formatter = self.createEventFormatter(session: self.session) else {
return
}
let editHistoryCoordinator = EditHistoryCoordinator(session: self.session, formatter: formatter, event: self.event)
editHistoryCoordinator.delegate = self
let navigationController = RiotNavigationController(rootViewController: editHistoryCoordinator.toPresentable())
navigationController.modalPresentationStyle = .formSheet
viewController.present(navigationController, animated: animated, completion: nil)
editHistoryCoordinator.start()
self.coordinator = editHistoryCoordinator
}
func dismiss(animated: Bool, completion: (() -> Void)?) {
guard let coordinator = self.coordinator else {
return
}
coordinator.toPresentable().dismiss(animated: animated) {
self.coordinator = nil
if let completion = completion {
completion()
}
}
}
// MARK: - Private
func createEventFormatter(session: MXSession) -> EventFormatter? {
guard let formatter = EventFormatter(matrixSession: session) else {
MXLog.debug("[EditHistoryCoordinatorBridgePresenter] createEventFormatter: Cannot build formatter")
return nil
}
// Use the same event formatter settings as RoomDataSource
formatter.treatMatrixUserIdAsLink = true
formatter.treatMatrixRoomIdAsLink = true
formatter.treatMatrixRoomAliasAsLink = true
formatter.treatMatrixGroupIdAsLink = true
formatter.eventTypesFilterForMessages = MXKAppSettings.standard()?.eventsFilterForMessages
// But do not display "...(Edited)"
formatter.showEditionMention = false
return formatter
}
}
// MARK: - EditHistoryCoordinatorDelegate
extension EditHistoryCoordinatorBridgePresenter: EditHistoryCoordinatorDelegate {
func editHistoryCoordinatorDidComplete(_ coordinator: EditHistoryCoordinatorType) {
self.delegate?.editHistoryCoordinatorBridgePresenterDelegateDidComplete(self)
}
}
| apache-2.0 | b990f6632150bef6083fabb8f0ec373e | 34.189655 | 134 | 0.711661 | 5.449933 | false | false | false | false |
jindulys/ChainPageCollectionView | ChainPageCollectionViewDemo/ImageCardCollectionCell.swift | 1 | 1538 | //
// ImageCardCollectionCell.swift
// ChainPageCollectionView
//
// Created by yansong li on 2017-07-23.
// Copyright © 2017 yansong li. All rights reserved.
//
import UIKit
/// The base card collection cell.
public class ImageCardCollectionViewCell: UICollectionViewCell {
public var backGroundImageView: UIImageView!
public override init(frame: CGRect) {
super.init(frame: frame)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 1, height: 1)
self.layer.shadowOpacity = 0.7
self.layer.shadowRadius = 4.0
backGroundImageView = UIImageView()
backGroundImageView.contentMode = .scaleAspectFill
backGroundImageView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.layer.masksToBounds = true
self.contentView.layer.cornerRadius = 8.0
self.contentView.addSubview(backGroundImageView)
buildConstraint()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private
private func buildConstraint() {
self.backGroundImageView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
self.backGroundImageView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true
self.backGroundImageView.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
self.backGroundImageView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
}
}
| mit | 7a81be0e54a06841dc98c50b4281a767 | 34.744186 | 112 | 0.763826 | 4.685976 | false | false | false | false |
vbudhram/firefox-ios | Sync/Synchronizers/ClientsSynchronizer.swift | 2 | 17928 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
import Deferred
import SwiftyJSON
private let log = Logger.syncLogger
let ClientsStorageVersion = 1
// TODO
public protocol Command {
static func fromName(_ command: String, args: [JSON]) -> Command?
func run(_ synchronizer: ClientsSynchronizer) -> Success
static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command?
}
// Shit.
// We need a way to wipe or reset engines.
// We need a way to log out the account.
// So when we sync commands, we're gonna need a delegate of some kind.
open class WipeCommand: Command {
public init?(command: String, args: [JSON]) {
return nil
}
open class func fromName(_ command: String, args: [JSON]) -> Command? {
return WipeCommand(command: command, args: args)
}
open func run(_ synchronizer: ClientsSynchronizer) -> Success {
return succeed()
}
open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? {
let json = JSON(parseJSON: syncCommand.value)
if let name = json["command"].string,
let args = json["args"].array {
return WipeCommand.fromName(name, args: args)
}
return nil
}
}
open class DisplayURICommand: Command {
let uri: URL
let title: String
let sender: String
public init?(command: String, args: [JSON]) {
if let uri = args[0].string?.asURL,
let sender = args[1].string,
let title = args[2].string {
self.uri = uri
self.sender = sender
self.title = title
} else {
// Oh, Swift.
self.uri = "http://localhost/".asURL!
self.title = ""
return nil
}
}
open class func fromName(_ command: String, args: [JSON]) -> Command? {
return DisplayURICommand(command: command, args: args)
}
open func run(_ synchronizer: ClientsSynchronizer) -> Success {
func display(_ deviceName: String? = nil) -> Success {
synchronizer.delegate.displaySentTab(for: uri, title: title, from: deviceName)
return succeed()
}
guard let getClientWithId = synchronizer.localClients?.getClientWithId(sender) else {
return display()
}
return getClientWithId >>== { client in
return display(client?.name)
}
}
open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? {
let json = JSON(parseJSON: syncCommand.value)
if let name = json["command"].string,
let args = json["args"].array {
return DisplayURICommand.fromName(name, args: args)
}
return nil
}
}
open class RepairResponseCommand: Command {
let repairResponse: RepairResponse
public init(command: String, args: [JSON]) {
self.repairResponse = RepairResponse.fromJSON(args: args[0])
}
open class func fromName(_ command: String, args: [JSON]) -> Command? {
return RepairResponseCommand(command: command, args: args)
}
open func run(_ synchronizer: ClientsSynchronizer) -> Success {
let repairer = BookmarksRepairRequestor(scratchpad: synchronizer.scratchpad, basePrefs: synchronizer.basePrefs, remoteClients: synchronizer.localClients!)
return repairer.continueRepairs(response: self.repairResponse) >>> succeed
}
open static func commandFromSyncCommand(_ syncCommand: SyncCommand) -> Command? {
let json = JSON(parseJSON: syncCommand.value)
if let name = json["command"].string,
let args = json["args"].array {
return RepairResponseCommand.fromName(name, args: args)
}
return nil
}
}
let Commands: [String: (String, [JSON]) -> Command?] = [
"wipeAll": WipeCommand.fromName,
"wipeEngine": WipeCommand.fromName,
// resetEngine
// resetAll
// logout
"displayURI": DisplayURICommand.fromName,
"repairResponse": RepairResponseCommand.fromName
]
open class ClientsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "clients")
}
var localClients: RemoteClientsAndTabs?
override var storageVersion: Int {
return ClientsStorageVersion
}
var clientRecordLastUpload: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastClientUpload")
}
get {
return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0
}
}
// Sync Object Format (Version 1) for Form Factors: http://docs.services.mozilla.com/sync/objectformats.html#id2
fileprivate enum SyncFormFactorFormat: String {
case phone = "phone"
case tablet = "tablet"
}
open func getOurClientRecord() -> Record<ClientPayload> {
let guid = self.scratchpad.clientGUID
let formfactor = formFactorString()
let json = JSON(object: [
"id": guid,
"fxaDeviceId": self.scratchpad.fxaDeviceId,
"version": AppInfo.appVersion,
"protocols": ["1.5"],
"name": self.scratchpad.clientName,
"os": "iOS",
"commands": [JSON](),
"type": "mobile",
"appPackage": AppInfo.baseBundleIdentifier,
"application": AppInfo.displayName,
"device": DeviceInfo.deviceModel(),
"formfactor": formfactor])
let payload = ClientPayload(json)
return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds)
}
fileprivate func formFactorString() -> String {
let userInterfaceIdiom = UIDevice.current.userInterfaceIdiom
var formfactor: String
switch userInterfaceIdiom {
case .phone:
formfactor = SyncFormFactorFormat.phone.rawValue
case .pad:
formfactor = SyncFormFactorFormat.tablet.rawValue
default:
formfactor = SyncFormFactorFormat.phone.rawValue
}
return formfactor
}
fileprivate func clientRecordToLocalClientEntry(_ record: Record<ClientPayload>) -> RemoteClient {
let modified = record.modified
let payload = record.payload
return RemoteClient(json: payload.json, modified: modified)
}
// If this is a fresh start, do a wipe.
// N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!)
// N.B., but perhaps we should discard outgoing wipe/reset commands!
fileprivate func wipeIfNecessary(_ localClients: RemoteClientsAndTabs) -> Success {
if self.lastFetched == 0 {
return localClients.wipeClients()
}
return succeed()
}
/**
* Returns whether any commands were found (and thus a replacement record
* needs to be uploaded). Also returns the commands: we run them after we
* upload a replacement record.
*/
fileprivate func processCommandsFromRecord(_ record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> {
log.debug("Processing commands from downloaded record.")
// TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead.
if let record = record {
let commands = record.payload.commands
if !commands.isEmpty {
func parse(_ json: JSON) -> Command? {
if let name = json["command"].string,
let args = json["args"].array,
let constructor = Commands[name] {
return constructor(name, args)
}
return nil
}
// TODO: can we do anything better if a command fails?
return deferMaybe((true, optFilter(commands.map(parse))))
}
}
return deferMaybe((false, []))
}
fileprivate func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
return localClients.getCommands() >>== { clientCommands in
return clientCommands.map { (clientGUID, commands) -> Success in
self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient)
}.allSucceed()
}
}
fileprivate func syncClientCommands(_ clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let deleteCommands: () -> Success = {
return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() })
}
log.debug("Fetching current client record for client \(clientGUID).")
let fetch = storageClient.get(clientGUID)
return fetch.bind() { result in
if let response = result.successValue, response.value.payload.isValid() {
let record = response.value
if var clientRecord = record.payload.json.dictionary {
clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON(parseJSON: $0.value) })
let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds)
return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified)
>>== { resp in
log.debug("Client \(clientGUID) commands upload succeeded.")
// Always succeed, even if we couldn't delete the commands.
return deleteCommands()
}
}
} else {
if let failure = result.failureValue {
log.warning("Failed to fetch record with GUID \(clientGUID).")
if failure is NotFound<HTTPURLResponse> {
log.debug("Not waiting to see if the client comes back.")
// TODO: keep these around and retry, expiring after a while.
// For now we just throw them away so we don't fail every time.
return deleteCommands()
}
if failure is BadRequestError<HTTPURLResponse> {
log.debug("We made a bad request. Throwing away queued commands.")
return deleteCommands()
}
}
}
log.error("Client \(clientGUID) commands upload failed: No remote client for GUID")
return deferMaybe(UnknownError())
}
}
/**
* Upload our record if either (a) we know we should upload, or (b)
* our own notes tell us we're due to reupload.
*/
fileprivate func maybeUploadOurRecord(_ should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success {
let lastUpload = self.clientRecordLastUpload
let expired = lastUpload < (Date.now() - (2 * OneDayInMilliseconds))
log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).")
if !should && !expired {
return succeed()
}
let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload)
var uploadStats = SyncUploadStats()
return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS)
>>== { resp in
if let ts = resp.metadata.lastModifiedMilliseconds {
// Protocol says this should always be present for success responses.
log.debug("Client record upload succeeded. New timestamp: \(ts).")
self.clientRecordLastUpload = ts
uploadStats.sent += 1
} else {
uploadStats.sentFailed += 1
}
self.statsSession.recordUpload(stats: uploadStats)
return succeed()
}
}
fileprivate func applyStorageResponse(_ response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>, notifier: CollectionChangedNotifier?) -> Success {
log.debug("Applying clients response.")
var downloadStats = SyncDownloadStats()
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) client records.")
let ourGUID = self.scratchpad.clientGUID
var toInsert = [RemoteClient]()
var ours: Record<ClientPayload>? = nil
for (rec) in records {
guard rec.payload.isValid() else {
log.warning("Client record \(rec.id) is invalid. Skipping.")
continue
}
if rec.id == ourGUID {
if rec.modified == self.clientRecordLastUpload {
log.debug("Skipping our own unmodified record.")
} else {
log.debug("Saw our own record in response.")
ours = rec
}
} else {
toInsert.append(self.clientRecordToLocalClientEntry(rec))
}
}
downloadStats.applied += toInsert.count
// Apply remote changes.
// Collect commands from our own record and reupload if necessary.
// Then run the commands and return.
return localClients.insertOrUpdateClients(toInsert)
>>== { succeeded in
downloadStats.succeeded += succeeded
downloadStats.failed += (toInsert.count - succeeded)
self.statsSession.recordDownload(stats: downloadStats)
return succeed()
}
>>== { self.processCommandsFromRecord(ours, withServer: storageClient) }
>>== { (shouldUpload, commands) in
let isFirstSync = self.lastFetched == 0
let ourRecordDidChange = self.why == .didLogin || self.why == .clientNameChanged
return self.maybeUploadOurRecord(shouldUpload || ourRecordDidChange, ifUnmodifiedSince: ours?.modified, toServer: storageClient)
>>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) }
>>> {
log.debug("Running \(commands.count) commands.")
for command in commands {
_ = command.run(self)
}
self.lastFetched = responseTimestamp!
if isFirstSync,
let notifier = notifier {
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { _ = notifier.notifyAll(collectionsChanged: ["clients"], reason: "firstsync") }
}
return succeed()
}
}
}
open func synchronizeLocalClients(_ localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections, notifier: CollectionChangedNotifier?) -> SyncResult {
log.debug("Synchronizing clients.")
self.localClients = localClients // Store for later when we process a repairResponse command
if let reason = self.reasonToNotSync(storageClient) {
switch reason {
case .engineRemotelyNotEnabled:
// This is a hard error for us.
return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?"))
default:
return deferMaybe(SyncStatus.notStarted(reason))
}
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0.json })
let encrypter = keys?.encrypter(self.collection, encoder: encoder)
if encrypter == nil {
log.error("Couldn't make clients encrypter.")
return deferMaybe(FatalError(message: "Couldn't make clients encrypter."))
}
let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!)
// TODO: some of the commands we process might involve wiping collections or the
// entire profile. We should model this as an explicit status, and return it here
// instead of .completed.
statsSession.start()
// XXX: This is terrible. We always force a re-sync of the clients to work around
// the fact that `fxaDeviceId` may not have been populated if the list of clients
// hadn't changed since before the update to v8.0. To force a re-sync, we get all
// clients since the beginning of time instead of looking at `self.lastFetched`.
return clientsClient.getSince(0)
>>== { response in
return self.wipeIfNecessary(localClients)
>>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient, notifier: notifier) }
}
>>> { deferMaybe(self.completedWithStats) }
}
}
| mpl-2.0 | 2e553154e6ac2f0b8c5b51fd203dba18 | 40.404157 | 262 | 0.608657 | 5.31515 | false | false | false | false |
ajeferson/AJImageViewController | Example/AJImageViewController/ViewController.swift | 1 | 3011 | //
// ViewController.swift
// AJImageViewController
//
// Created by Alan Jeferson on 08/24/2015.
// Copyright (c) 2015 Alan Jeferson. All rights reserved.
//
import UIKit
import AJImageViewController
class ViewController: UIViewController {
@IBOutlet weak var imageViewA: UIImageView!
@IBOutlet weak var imageViewB: UIImageView!
@IBOutlet weak var imageViewC: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.setupImageViewA()
self.setupGestureRecognizers()
}
func setupImageViewA() -> Void {
self.imageViewA.clipsToBounds = true
self.imageViewA.layer.cornerRadius = self.imageViewA.frame.width/2
self.imageViewA.layer.borderWidth = 3.0
self.imageViewA.layer.borderColor = UIColor.purpleColor().CGColor
}
func setupGestureRecognizers() -> Void {
let tapA = UITapGestureRecognizer(target: self, action: Selector("presentSingleImageViewControllerA:"))
tapA.numberOfTapsRequired = 1
tapA.numberOfTouchesRequired = 1
self.imageViewA.userInteractionEnabled = true
self.imageViewA.addGestureRecognizer(tapA)
let tapB = UITapGestureRecognizer(target: self, action: Selector("presentImageViewController:"))
tapB.numberOfTapsRequired = 1
tapB.numberOfTouchesRequired = 1
self.imageViewB.userInteractionEnabled = true
self.imageViewB.addGestureRecognizer(tapB)
let tapC = UITapGestureRecognizer(target: self, action: Selector("presentSingleImageViewControllerC:"))
tapC.numberOfTapsRequired = 1
tapC.numberOfTouchesRequired = 1
self.imageViewC.userInteractionEnabled = true
self.imageViewC.addGestureRecognizer(tapC)
}
func presentSingleImageViewControllerA(gesture: UITapGestureRecognizer) -> Void {
var imageViewController = AJImageViewController(imageView: self.imageViewA, images: UIImage(named: "image4")!)
imageViewController.dismissButton.hidden = true
imageViewController.enableSingleTapToDismiss = true
self.presentViewController(imageViewController, animated: true, completion: nil)
}
func presentImageViewController(gesture: UITapGestureRecognizer) -> Void {
let imageViewController = AJImageViewController(imageView: self.imageViewB, images: UIImage(named: "image1")!, UIImage(named: "image2")!, UIImage(named: "image3")!, UIImage(named: "image4")!)
self.presentViewController(imageViewController, animated: true, completion: nil)
}
func presentSingleImageViewControllerC(gesture: UITapGestureRecognizer) -> Void {
var imageViewController = AJImageViewController(imageView: self.imageViewC, images: self.imageViewC.image!)
imageViewController.dismissButton.hidden = true
imageViewController.enableSingleTapToDismiss = true
self.presentViewController(imageViewController, animated: true, completion: nil)
}
}
| mit | da37a208a4dab068a4d1760a6e3b3d52 | 41.408451 | 199 | 0.71903 | 5.209343 | false | false | false | false |
synchromation/Buildasaur | BuildaKit/SyncPairExtensions.swift | 2 | 3776 | //
// SyncPairExtensions.swift
// Buildasaur
//
// Created by Honza Dvorsky on 19/05/15.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
import BuildaGitServer
import BuildaUtils
extension SyncPair {
public struct Actions {
public let integrationsToCancel: [Integration]?
public let githubStatusToSet: (status: HDGitHubXCBotSyncer.GitHubStatusAndComment, commit: String, issue: Issue?)?
public let startNewIntegrationBot: Bot? //if non-nil, starts a new integration on this bot
}
func performActions(actions: Actions, completion: Completion) {
let group = dispatch_group_create()
var lastGroupError: NSError?
if let integrationsToCancel = actions.integrationsToCancel {
dispatch_group_enter(group)
self.syncer.cancelIntegrations(integrationsToCancel, completion: { () -> () in
dispatch_group_leave(group)
})
}
if let newStatus = actions.githubStatusToSet {
let status = newStatus.status
let commit = newStatus.commit
let issue = newStatus.issue
dispatch_group_enter(group)
self.syncer.updateCommitStatusIfNecessary(status, commit: commit, issue: issue, completion: { (error) -> () in
if let error = error {
lastGroupError = error
}
dispatch_group_leave(group)
})
}
if let startNewIntegrationBot = actions.startNewIntegrationBot {
let bot = startNewIntegrationBot
dispatch_group_enter(group)
self.syncer._xcodeServer.postIntegration(bot.id, completion: { (integration, error) -> () in
if let integration = integration where error == nil {
Log.info("Bot \(bot.name) successfully enqueued Integration #\(integration.number)")
} else {
let e = Error.withInfo("Bot \(bot.name) failed to enqueue an integration", internalError: error)
lastGroupError = e
}
dispatch_group_leave(group)
})
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
completion(error: lastGroupError)
})
}
//MARK: Utility functions
func getIntegrations(bot: Bot, completion: (integrations: [Integration], error: NSError?) -> ()) {
let syncer = self.syncer
/*
TODO: we should establish some reliable and reasonable plan for how many integrations to fetch.
currently it's always 20, but some setups might have a crazy workflow with very frequent commits
on active bots etc.
*/
let query = [
"last": "20"
]
syncer._xcodeServer.getBotIntegrations(bot.id, query: query, completion: { (integrations, error) -> () in
if let error = error {
let e = Error.withInfo("Bot \(bot.name) failed return integrations", internalError: error)
completion(integrations: [], error: e)
return
}
if let integrations = integrations {
completion(integrations: integrations, error: nil)
} else {
let e = Error.withInfo("Getting integrations", internalError: Error.withInfo("Nil integrations even after returning nil error!"))
completion(integrations: [], error: e)
}
})
}
}
| mit | 704b0bb85695452deddcd2647b36af49 | 34.28972 | 145 | 0.562235 | 5.386591 | false | false | false | false |
MetalPetal/MetalPetal | Frameworks/MetalPetal/MTIImage.swift | 1 | 8936 | //
// MTIImage.swift
// MetalPetal
//
// Created by Yu Ao on 2019/12/4.
//
import Foundation
import MetalKit
#if SWIFT_PACKAGE
import MetalPetalObjectiveC.Core
#endif
extension MTIImage {
public convenience init(cgImage: CGImage, orientation: CGImagePropertyOrientation = .up, options: MTICGImageLoadingOptions = .default, isOpaque: Bool = false) {
self.init(__cgImage: cgImage, orientation: orientation, loadingOptions: options, isOpaque: isOpaque)
}
public convenience init?(contentsOf url: URL, options: MTICGImageLoadingOptions = .default, isOpaque: Bool = false) {
self.init(__contentsOf: url, loadingOptions: options, isOpaque: isOpaque)
}
@available(*, deprecated, message: "Use init?(contentsOf:options:isOpaque:) instead.")
public convenience init?(contentsOf url: URL, options: MTICGImageLoadingOptions = .default, alphaType: MTIAlphaType? = nil) {
self.init(__contentsOf: url, loadingOptions: options, isOpaque: alphaType == .alphaIsOne ? true : false)
}
public convenience init(cgImage: CGImage, options: [MTKTextureLoader.Option: Any], isOpaque: Bool = false) {
self.init(__cgImage: cgImage, options: options, isOpaque: isOpaque)
}
public convenience init?(contentsOf url: URL, options: [MTKTextureLoader.Option: Any], alphaType: MTIAlphaType? = nil) {
if let alphaType = alphaType {
self.init(__contentsOf: url, options: options, alphaType: alphaType)
} else {
self.init(__contentsOf: url, options: options)
}
}
public convenience init?(contentsOf url: URL, size: CGSize, options: [MTKTextureLoader.Option: Any], alphaType: MTIAlphaType) {
self.init(__contentsOf: url, size: size, options: options, alphaType: alphaType)
}
public convenience init(bitmapData data: Data, width: Int, height: Int, bytesPerRow: Int, pixelFormat: MTLPixelFormat, alphaType: MTIAlphaType) {
self.init(bitmapData: data, width: UInt(width), height: UInt(height), bytesPerRow: UInt(bytesPerRow), pixelFormat: pixelFormat, alphaType: alphaType)
}
public convenience init(cvPixelBuffer pixelBuffer: CVPixelBuffer, planeIndex: Int, textureDescriptor: MTLTextureDescriptor, alphaType: MTIAlphaType) {
self.init(cvPixelBuffer: pixelBuffer, planeIndex: UInt(planeIndex), textureDescriptor: textureDescriptor, alphaType: alphaType)
}
}
extension MTIImage {
public func adjusting(saturation: Float, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage {
let filter = MTISaturationFilter()
filter.saturation = saturation
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage!
}
public func adjusting(exposure: Float, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage {
let filter = MTIExposureFilter()
filter.exposure = exposure
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage!
}
public func adjusting(brightness: Float, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage {
let filter = MTIBrightnessFilter()
filter.brightness = brightness
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage!
}
public func adjusting(contrast: Float, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage {
let filter = MTIContrastFilter()
filter.contrast = contrast
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage!
}
public func adjusting(vibrance: Float, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage {
let filter = MTIVibranceFilter()
filter.amount = vibrance
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage!
}
/// Returns a MTIImage object that specifies a subimage of the image. If the `region` parameter defines an empty area, returns nil.
public func cropped(to region: MTICropRegion, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage? {
let filter = MTICropFilter()
filter.cropRegion = region
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage
}
/// Returns a MTIImage object that specifies a subimage of the image. If the `rect` parameter defines an empty area, returns nil.
public func cropped(to rect: CGRect, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage? {
let filter = MTICropFilter()
filter.cropRegion = MTICropRegion(bounds: rect, unit: .pixel)
filter.inputImage = self
filter.outputPixelFormat = outputPixelFormat
return filter.outputImage
}
/// Returns a MTIImage object that is resized to a specified size. If the `size` parameter has zero/negative width or height, returns nil.
public func resized(to size: CGSize, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage? {
assert(size.width >= 1 && size.height >= 1)
guard size.width >= 1 && size.height >= 1 else { return nil }
return MTIUnaryImageRenderingFilter.image(byProcessingImage: self, orientation: .up, parameters: [:], outputPixelFormat: outputPixelFormat, outputImageSize: size)
}
/// Returns a MTIImage object that is resized to a specified size. If the `size` parameter has zero/negative width or height, returns nil.
public func resized(to target: CGSize, resizingMode: MTIDrawableRenderingResizingMode, outputPixelFormat: MTLPixelFormat = .unspecified) -> MTIImage? {
let size: CGSize
switch resizingMode {
case .aspect:
size = MTIMakeRect(aspectRatio: self.size, insideRect: CGRect(origin: .zero, size: target)).size
case .aspectFill:
size = MTIMakeRect(aspectRatio: self.size, fillRect: CGRect(origin: .zero, size: target)).size
case .scale:
size = target
@unknown default:
fatalError()
}
assert(size.width >= 1 && size.height >= 1)
guard size.width >= 1 && size.height >= 1 else { return nil }
return MTIUnaryImageRenderingFilter.image(byProcessingImage: self, orientation: .up, parameters: [:], outputPixelFormat: outputPixelFormat, outputImageSize: size)
}
}
#if canImport(UIKit)
import UIKit
extension UIImage.Orientation {
fileprivate var cgImagePropertyOrientation: CGImagePropertyOrientation {
let cgImagePropertyOrientation: CGImagePropertyOrientation
switch self {
case .up:
cgImagePropertyOrientation = .up
case .upMirrored:
cgImagePropertyOrientation = .upMirrored
case .left:
cgImagePropertyOrientation = .left
case .leftMirrored:
cgImagePropertyOrientation = .leftMirrored
case .right:
cgImagePropertyOrientation = .right
case .rightMirrored:
cgImagePropertyOrientation = .rightMirrored
case .down:
cgImagePropertyOrientation = .down
case .downMirrored:
cgImagePropertyOrientation = .downMirrored
@unknown default:
fatalError("Unknown UIImage.Orientation: \(self.rawValue)")
}
return cgImagePropertyOrientation
}
}
extension MTIImage {
public convenience init(image: UIImage, colorSpace: CGColorSpace? = nil, isOpaque: Bool = false) {
let cgImage: CGImage
let orientation: CGImagePropertyOrientation
if let cg = image.cgImage {
cgImage = cg
orientation = image.imageOrientation.cgImagePropertyOrientation
} else {
let format = UIGraphicsImageRendererFormat.preferred()
format.opaque = isOpaque
format.scale = image.scale
cgImage = UIGraphicsImageRenderer(size: image.size).image { _ in
image.draw(at: .zero)
}.cgImage!
orientation = .up
}
let options = MTICGImageLoadingOptions(colorSpace: colorSpace)
self.init(cgImage: cgImage, orientation: orientation, options: options, isOpaque: isOpaque)
}
}
#endif
#if canImport(AppKit)
import AppKit
extension MTIImage {
@available(macCatalyst, unavailable)
public convenience init?(image: NSImage, colorSpace: CGColorSpace? = nil, isOpaque: Bool = false) {
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
return nil
}
let options = MTICGImageLoadingOptions(colorSpace: colorSpace)
self.init(cgImage: cgImage, orientation: .up, options: options, isOpaque: isOpaque)
}
}
#endif
| mit | 3b0da132dc4d9319f065ebd67de01cf5 | 41.350711 | 170 | 0.679163 | 4.848616 | false | false | false | false |
uber/rides-ios-sdk | source/UberCore/Authentication/LoginButton.swift | 1 | 10121 | //
// UberLoginButton.swift
// UberRides
//
// Copyright © 2016 Uber Technologies, Inc. All rights reserved.
//
// 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
@objc public enum LoginButtonState : Int {
case signedIn
case signedOut
}
/**
* Protocol to listen to login button events, such as logging in / out
*/
@objc(UBSDKLoginButtonDelegate) public protocol LoginButtonDelegate {
/**
The Login Button attempted to log out
- parameter button: The LoginButton involved
- parameter success: True if log out succeeded, false otherwise
*/
@objc func loginButton(_ button: LoginButton, didLogoutWithSuccess success: Bool)
/**
THe Login Button completed a login
- parameter button: The LoginButton involved
- parameter accessToken: The access token that
- parameter error: The error that occured
*/
@objc func loginButton(_ button: LoginButton, didCompleteLoginWithToken accessToken: AccessToken?, error: NSError?)
}
/// Button to handle logging in to Uber
@objc(UBSDKLoginButton) public class LoginButton: UberButton {
let horizontalCenterPadding: CGFloat = 50
let loginVerticalPadding: CGFloat = 15
let loginHorizontalEdgePadding: CGFloat = 15
/// The LoginButtonDelegate for this button
@objc public weak var delegate: LoginButtonDelegate?
/// The LoginManager to use for log in
@objc public var loginManager: LoginManager {
didSet {
refreshContent()
}
}
/// The UberScopes to request
@objc public var scopes: [UberScope]
/// The view controller to present login over. Used
@objc public var presentingViewController: UIViewController?
/// The current LoginButtonState of this button (signed in / signed out)
@objc public var buttonState: LoginButtonState {
if let _ = TokenManager.fetchToken(identifier: accessTokenIdentifier, accessGroup: keychainAccessGroup) {
return .signedIn
} else {
return .signedOut
}
}
private var accessTokenIdentifier: String {
return loginManager.accessTokenIdentifier
}
private var keychainAccessGroup: String {
return loginManager.keychainAccessGroup
}
private var loginCompletion: ((_ accessToken: AccessToken?, _ error: NSError?) -> Void)?
@objc public init(frame: CGRect, scopes: [UberScope], loginManager: LoginManager) {
self.loginManager = loginManager
self.scopes = scopes
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
loginManager = LoginManager(loginType: .native)
scopes = []
super.init(coder: aDecoder)
setup()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
//Mark: UberButton
/**
Setup the LoginButton by adding a target to the button and setting the login completion block
*/
override public func setup() {
super.setup()
NotificationCenter.default.addObserver(self, selector: #selector(refreshContent), name: Notification.Name(rawValue: TokenManager.tokenManagerDidSaveTokenNotification), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshContent), name: Notification.Name(rawValue: TokenManager.tokenManagerDidDeleteTokenNotification), object: nil)
addTarget(self, action: #selector(uberButtonTapped), for: .touchUpInside)
loginCompletion = { token, error in
self.delegate?.loginButton(self, didCompleteLoginWithToken: token, error: error)
self.refreshContent()
}
sizeToFit()
}
/**
Updates the content of the button. Sets the image icon and font, as well as the text
*/
override public func setContent() {
super.setContent()
let buttonFont = UIFont.systemFont(ofSize: 13)
let titleText = titleForButtonState(buttonState)
let logo = getImage("ic_logo_white")
uberTitleLabel.font = buttonFont
uberTitleLabel.text = titleText
uberImageView.image = logo
uberImageView.contentMode = .center
}
/**
Adds the layout constraints for the Login button.
*/
override public func setConstraints() {
uberTitleLabel.translatesAutoresizingMaskIntoConstraints = false
uberImageView.translatesAutoresizingMaskIntoConstraints = false
uberImageView.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
uberTitleLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal)
uberTitleLabel.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .vertical)
let imageLeftConstraint = NSLayoutConstraint(item: uberImageView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: loginHorizontalEdgePadding)
let imageTopConstraint = NSLayoutConstraint(item: uberImageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: loginVerticalPadding)
let imageBottomConstraint = NSLayoutConstraint(item: uberImageView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -loginVerticalPadding)
let titleLabelRightConstraint = NSLayoutConstraint(item: uberTitleLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1.0, constant: -loginHorizontalEdgePadding)
let titleLabelCenterYConstraint = NSLayoutConstraint(item: uberTitleLabel, attribute: .centerY, relatedBy: .equal, toItem: uberImageView, attribute: .centerY, multiplier: 1.0, constant: 0.0)
let imagePaddingRightConstraint = NSLayoutConstraint(item: uberTitleLabel, attribute: .left, relatedBy: .greaterThanOrEqual , toItem: uberImageView, attribute: .right, multiplier: 1.0, constant: imageLabelPadding)
let horizontalCenterPaddingConstraint = NSLayoutConstraint(item: uberTitleLabel, attribute: .left, relatedBy: .greaterThanOrEqual , toItem: uberImageView, attribute: .right, multiplier: 1.0, constant: horizontalCenterPadding)
horizontalCenterPaddingConstraint.priority = UILayoutPriority.defaultLow
addConstraints([imageLeftConstraint, imageTopConstraint, imageBottomConstraint])
addConstraints([titleLabelRightConstraint, titleLabelCenterYConstraint])
addConstraints([imagePaddingRightConstraint, horizontalCenterPaddingConstraint])
}
//Mark: UIView
override public func sizeThatFits(_ size: CGSize) -> CGSize {
let sizeThatFits = super.sizeThatFits(size)
let iconSizeThatFits = uberImageView.image?.size ?? CGSize.zero
let labelSizeThatFits = uberTitleLabel.intrinsicContentSize
let labelMinHeight = labelSizeThatFits.height + 2 * loginVerticalPadding
let iconMinHeight = iconSizeThatFits.height + 2 * loginVerticalPadding
let height = max(iconMinHeight, labelMinHeight)
return CGSize(width: sizeThatFits.width + horizontalCenterPadding, height: height)
}
override public func updateConstraints() {
refreshContent()
super.updateConstraints()
}
//Mark: Internal Interface
@objc func uberButtonTapped(_ button: UIButton) {
switch buttonState {
case .signedIn:
let success = TokenManager.deleteToken(identifier: accessTokenIdentifier, accessGroup: keychainAccessGroup)
delegate?.loginButton(self, didLogoutWithSuccess: success)
refreshContent()
case .signedOut:
loginManager.login(requestedScopes: scopes, presentingViewController: presentingViewController, completion: loginCompletion)
}
}
//Mark: Private Interface
@objc private func refreshContent() {
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
strongSelf.uberTitleLabel.text = strongSelf.titleForButtonState(strongSelf.buttonState)
}
}
private func titleForButtonState(_ buttonState: LoginButtonState) -> String {
var titleText: String!
switch buttonState {
case .signedIn:
titleText = NSLocalizedString("Sign Out", bundle: Bundle(for: type(of: self)), comment: "Login Button Sign Out Description").uppercased()
case .signedOut:
titleText = NSLocalizedString("Sign In", bundle: Bundle(for: type(of: self)), comment: "Login Button Sign In Description").uppercased()
}
return titleText
}
private func getImage(_ name: String) -> UIImage? {
let bundle = Bundle(for: LoginButton.self)
return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
}
}
| mit | 842c95a322b4ad5339715b1e7f8eb05b | 41.521008 | 233 | 0.695158 | 5.287356 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos | Data Structures & Algorithms/Queue.playground/Contents.swift | 1 | 4258 | import UIKit
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element) -> Bool
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
public struct QueueArray<T>: Queue {
// Space Complexity: O(n)
private var array: [T] = []
public var isEmpty: Bool {
array.isEmpty
}
public var peek: Element? {
array.first
}
public init() {}
// O(1)
public mutating func enqueue(_ element: T) -> Bool {
array.append(element)
return true
}
// O(n)
public mutating func dequeue() -> T? {
isEmpty ? nil : array.removeFirst()
}
}
extension QueueArray: CustomStringConvertible {
public var description: String {
String(describing: array)
}
}
var queue = QueueArray<String>()
queue.enqueue("Hi Bob")
queue.enqueue("Marshmellow")
queue.enqueue("Itty Bitty")
queue.enqueue("Lavern")
queue.enqueue("Shirley")
queue.enqueue("Squirrel Mouse")
queue.enqueue("Arlene")
queue
queue.dequeue()
queue
queue.peek
public struct QueueLinkedList<T>: Queue {
// Space Complexity: O(n)
private var list = DoublyLinkedList<T>()
public init() {}
// O(1)
public func enqueue(_ element: T) -> Bool {
list.append(element)
return true
}
// O(1)
public func dequeue() -> T? {
guard !list.isEmpty, let element = list.first else {
return nil
}
return list.remove(element)
}
public var peek: T? {
return list.first?.value
}
public var isEmpty: Bool {
list.isEmpty
}
}
extension QueueLinkedList: CustomStringConvertible {
public var description: String {
String.init(describing: list)
}
}
var queue2 = QueueLinkedList<String>()
queue2.enqueue("Hi Bob")
queue2.enqueue("Marshmellow")
queue2.enqueue("Itty Bitty")
queue2.enqueue("Lavern")
queue2.enqueue("Shirley")
queue2.enqueue("Squirrel Mouse")
queue2.enqueue("Arlene")
print(queue2.description)
queue2.dequeue()
queue2
queue2.peek
print(queue2.description)
public struct QueueRingBuffer<T>: Queue {
// Space Complexity: O(n)
private var ringBuffer: RingBuffer<T>
public init(count: Int) {
ringBuffer = RingBuffer<T>(count: count)
}
// O(1)
public var isEmpty: Bool {
ringBuffer.isEmpty
}
// O(1)
public var peek: T? {
ringBuffer.first
}
// O(1)
public mutating func enqueue(_ element: T) -> Bool {
ringBuffer.write(element)
}
// O()
public mutating func dequeue() -> T? {
ringBuffer.read()
}
}
var queue3 = QueueLinkedList<String>()
queue3.enqueue("Hi Bob")
queue3.enqueue("Marshmellow")
queue3.enqueue("Itty Bitty")
queue3.enqueue("Lavern")
queue3.enqueue("Shirley")
queue3.enqueue("Squirrel Mouse")
queue3.enqueue("Arlene")
//print(queue3.description)
queue3.dequeue()
queue3
queue3.peek
//print(queue3.description)
public struct QueueStacks<T>: Queue {
public var leftStack: [T] = []
public var rightStack: [T] = []
public init() {}
// O(1)
public var isEmpty: Bool {
leftStack.isEmpty && rightStack.isEmpty
}
// O(1)
public var peek: T? {
!leftStack.isEmpty ? leftStack.last : rightStack.first
}
// O(1)
public mutating func enqueue(_ element: T) -> Bool {
rightStack.append(element)
return true
}
// O(1)
public mutating func dequeue() -> T? {
if leftStack.isEmpty {
leftStack = rightStack.reversed()
rightStack.removeAll()
}
return leftStack.popLast()
}
}
extension QueueStacks: CustomStringConvertible {
public var description: String {
String(describing: leftStack.reversed() + rightStack)
}
}
var queue4 = QueueLinkedList<String>()
queue4.enqueue("Hi Bob")
queue4.enqueue("Marshmellow")
queue4.enqueue("Itty Bitty")
queue4.enqueue("Lavern")
queue4.enqueue("Shirley")
queue4.enqueue("Squirrel Mouse")
queue4.enqueue("Arlene")
print(queue4.description)
queue4.dequeue()
queue4
queue4.peek
print(queue4.description)
| gpl-2.0 | 4eaddd269c762dcbd40f28b1e67a063a | 19.872549 | 62 | 0.618835 | 3.801786 | false | false | false | false |
Edovia/SwiftyDropbox | Source/OAuth.swift | 1 | 19555 | #if os(iOS)
import UIKit
#else
import AppKit
#endif
import WebKit
import Security
import Foundation
/// A Dropbox access token
public class DropboxAccessToken : CustomStringConvertible {
/// The access token string
public let accessToken: String
/// The associated user
public let uid: String
public init(accessToken: String, uid: String) {
self.accessToken = accessToken
self.uid = uid
}
public var description : String {
return self.accessToken
}
}
/// A failed authorization.
/// See RFC6749 4.2.2.1
public enum OAuth2Error {
/// The client is not authorized to request an access token using this method.
case UnauthorizedClient
/// The resource owner or authorization server denied the request.
case AccessDenied
/// The authorization server does not support obtaining an access token using this method.
case UnsupportedResponseType
/// The requested scope is invalid, unknown, or malformed.
case InvalidScope
/// The authorization server encountered an unexpected condition that prevented it from fulfilling the request.
case ServerError
/// The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.
case TemporarilyUnavailable
/// Some other error (outside of the OAuth2 specification)
case Unknown
/// Initializes an error code from the string specced in RFC6749
init(errorCode: String) {
switch errorCode {
case "unauthorized_client": self = .UnauthorizedClient
case "access_denied": self = .AccessDenied
case "unsupported_response_type": self = .UnsupportedResponseType
case "invalid_scope": self = .InvalidScope
case "server_error": self = .ServerError
case "temporarily_unavailable": self = .TemporarilyUnavailable
default: self = .Unknown
}
}
}
private let kDBLinkNonce = "dropbox.sync.nonce"
/// The result of an authorization attempt.
public enum DropboxAuthResult {
/// The authorization succeeded. Includes a `DropboxAccessToken`.
case Success(DropboxAccessToken)
/// The authorization failed. Includes an `OAuth2Error` and a descriptive message.
case Error(OAuth2Error, String)
}
class DBKeychain {
class func queryWithDict(query: [String : AnyObject]) -> CFDictionaryRef
{
let bundleId = NSBundle.mainBundle().bundleIdentifier ?? ""
var queryDict = query
queryDict[kSecClass as String] = kSecClassGenericPassword
queryDict[kSecAttrService as String] = "\(bundleId).dropbox.authv2"
return queryDict
}
class func set(key: String, value: String) -> Bool {
if let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
return set(key, value: data)
} else {
return false
}
}
class func set(key: String, value: NSData) -> Bool {
let query = DBKeychain.queryWithDict([
(kSecAttrAccount as String): key,
( kSecValueData as String): value
])
SecItemDelete(query)
return SecItemAdd(query, nil) == noErr
}
class func getAsData(key: String) -> NSData? {
let query = DBKeychain.queryWithDict([
(kSecAttrAccount as String): key,
( kSecReturnData as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitOne
])
var dataResult : AnyObject?
let status = withUnsafeMutablePointer(&dataResult) { (ptr) in
SecItemCopyMatching(query, UnsafeMutablePointer(ptr))
}
if status == noErr {
return dataResult as? NSData
}
return nil
}
class func dbgListAllItems() {
let query : CFDictionaryRef = [
(kSecClass as String) : kSecClassGenericPassword,
(kSecReturnAttributes as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitAll
]
var dataResult : AnyObject?
let status = withUnsafeMutablePointer(&dataResult) { (ptr) in
SecItemCopyMatching(query, UnsafeMutablePointer(ptr))
}
if status == noErr {
let results = dataResult as? [[String : AnyObject]] ?? []
print(results.map {d in (d["svce"] as! String, d["acct"] as! String)})
}
}
class func getAll() -> [String] {
let query = DBKeychain.queryWithDict([
( kSecReturnAttributes as String): kCFBooleanTrue,
( kSecMatchLimit as String): kSecMatchLimitAll
])
var dataResult : AnyObject?
let status = withUnsafeMutablePointer(&dataResult) { (ptr) in
SecItemCopyMatching(query, UnsafeMutablePointer(ptr))
}
if status == noErr {
let results = dataResult as? [[String : AnyObject]] ?? []
return results.map { d in d["acct"] as! String }
}
return []
}
class func get(key: String) -> String? {
if let data = getAsData(key) {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
} else {
return nil
}
}
class func delete(key: String) -> Bool {
let query = DBKeychain.queryWithDict([
(kSecAttrAccount as String): key
])
return SecItemDelete(query) == noErr
}
class func clear() -> Bool {
let query = DBKeychain.queryWithDict([:])
return SecItemDelete(query) == noErr
}
}
/// Manages access token storage and authentication
///
/// Use the `DropboxAuthManager` to authenticate users through OAuth2, save access tokens, and retrieve access tokens.
public class DropboxAuthManager {
let appKey : String
let redirectURL: NSURL
let dauthRedirectURL: NSURL
let host: String
// MARK: Shared instance
/// A shared instance of a `DropboxAuthManager` for convenience
public static var sharedAuthManager : DropboxAuthManager!
// MARK: Functions
public init(appKey: String, host: String) {
self.appKey = appKey
self.host = host
self.redirectURL = NSURL(string: "db-\(self.appKey)://2/token")!
self.dauthRedirectURL = NSURL(string: "db-\(self.appKey)://1/connect")!
}
/**
Create an instance
parameter appKey: The app key from the developer console that identifies this app.
*/
convenience public init(appKey: String) {
self.init(appKey: appKey, host: "www.dropbox.com")
}
private func conformsToAppScheme() -> Bool {
let appScheme = "db-\(self.appKey)"
let urlTypes = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleURLTypes") as? [ [String: AnyObject] ] ?? []
for urlType in urlTypes {
let schemes = urlType["CFBundleURLSchemes"] as? [String] ?? []
for scheme in schemes {
print(scheme)
if scheme == appScheme {
return true
}
}
}
return false
}
private func hasApplicationQueriesScheme() -> Bool {
let queriesSchemes = NSBundle.mainBundle().objectForInfoDictionaryKey("LSApplicationQueriesSchemes") as? [String] ?? []
for scheme in queriesSchemes {
if scheme == "dbapi-2" {
return true
}
}
return false
}
private func authURL() -> NSURL {
let components = NSURLComponents()
components.scheme = "https"
components.host = self.host
components.path = "/1/oauth2/authorize"
components.queryItems = [
NSURLQueryItem(name: "response_type", value: "token"),
NSURLQueryItem(name: "client_id", value: self.appKey),
NSURLQueryItem(name: "redirect_uri", value: self.redirectURL.URLString),
NSURLQueryItem(name: "disable_signup", value: "true"),
]
return components.URL!
}
private func dAuthURL(nonce: String?) -> NSURL {
let components = NSURLComponents()
components.scheme = "dbapi-2"
components.host = "1"
components.path = "/connect"
if let n = nonce {
let state = "oauth2:\(n)"
components.queryItems = [
NSURLQueryItem(name: "k", value: self.appKey),
NSURLQueryItem(name: "s", value: ""),
NSURLQueryItem(name: "state", value: state),
]
}
return components.URL!
}
private func canHandleURL(url: NSURL) -> Bool {
for known in [self.redirectURL, self.dauthRedirectURL] {
if (url.scheme == known.scheme && url.host == known.host && url.path == known.path) {
return true
}
}
return false
}
/// Present the OAuth2 authorization request page by presenting a web view controller modally
///
/// parameter controller: The controller to present from
#if os(iOS)
public func authorizeFromController(controller: UIViewController) {
if !self.conformsToAppScheme() {
let message = "DropboxSDK: unable to link; app isn't registered for correct URL scheme (db-\(self.appKey))"
let alertController = UIAlertController(
title: "SwiftyDropbox Error",
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
controller.presentViewController(alertController, animated: true, completion: { fatalError(message) } )
return
}
if !self.hasApplicationQueriesScheme() {
let message = "DropboxSDK: unable to link; app isn't registered to query for URL scheme dbapi-2. Add a dbapi-2 entry to LSApplicationQueriesSchemes"
let alertController = UIAlertController(
title: "SwiftyDropbox Error",
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
controller.presentViewController(alertController, animated: true, completion: { fatalError(message) } )
return
}
if UIApplication.sharedApplication().canOpenURL(dAuthURL(nil)) {
let nonce = NSUUID().UUIDString
NSUserDefaults.standardUserDefaults().setObject(nonce, forKey: kDBLinkNonce)
NSUserDefaults.standardUserDefaults().synchronize()
UIApplication.sharedApplication().openURL(dAuthURL(nonce))
} else {
let web = DropboxConnectController(
URL: self.authURL(),
tryIntercept: { url in
if self.canHandleURL(url) {
UIApplication.sharedApplication().openURL(url)
return true
} else {
return false
}
}
)
let navigationController = UINavigationController(rootViewController: web)
controller.presentViewController(navigationController, animated: true, completion: nil)
}
}
#else
// TODO Screens Mac
#endif
private func extractfromDAuthURL(url: NSURL) -> DropboxAuthResult {
switch url.path ?? "" {
case "/connect":
var results = [String: String]()
let pairs = url.query?.componentsSeparatedByString("&") ?? []
for pair in pairs {
let kv = pair.componentsSeparatedByString("=")
results.updateValue(kv[1], forKey: kv[0])
}
let state = results["state"]?.componentsSeparatedByString("%3A") ?? []
let nonce = NSUserDefaults.standardUserDefaults().objectForKey(kDBLinkNonce) as? String
if state.count == 2 && state[0] == "oauth2" && state[1] == nonce! {
let accessToken = results["oauth_token_secret"]!
let uid = results["uid"]!
return .Success(DropboxAccessToken(accessToken: accessToken, uid: uid))
} else {
return .Error(.Unknown, "Unable to verify link request")
}
default:
return .Error(.AccessDenied, "User cancelled Dropbox link")
}
}
private func extractFromRedirectURL(url: NSURL) -> DropboxAuthResult {
var results = [String: String]()
let pairs = url.fragment?.componentsSeparatedByString("&") ?? []
for pair in pairs {
let kv = pair.componentsSeparatedByString("=")
results.updateValue(kv[1], forKey: kv[0])
}
if let error = results["error"] {
let desc = results["error_description"]?.stringByReplacingOccurrencesOfString("+", withString: " ").stringByRemovingPercentEncoding
return .Error(OAuth2Error(errorCode: error), desc ?? "")
} else {
let accessToken = results["access_token"]!
let uid = results["uid"]!
return .Success(DropboxAccessToken(accessToken: accessToken, uid: uid))
}
}
/**
Try to handle a redirect back into the application
- parameter url: The URL to attempt to handle
- returns `nil` if SwiftyDropbox cannot handle the redirect URL, otherwise returns the `DropboxAuthResult`.
*/
public func handleRedirectURL(url: NSURL) -> DropboxAuthResult? {
if !self.canHandleURL(url) {
return nil
}
let result : DropboxAuthResult
if url.host == "1" { // dauth
result = extractfromDAuthURL(url)
} else {
result = extractFromRedirectURL(url)
}
switch result {
case .Success(let token):
DBKeychain.set(token.uid, value: token.accessToken)
return result
default:
return result
}
}
/**
Retrieve all stored access tokens
- returns: a dictionary mapping users to their access tokens
*/
public func getAllAccessTokens() -> [String : DropboxAccessToken] {
let users = DBKeychain.getAll()
var ret = [String : DropboxAccessToken]()
for user in users {
if let accessToken = DBKeychain.get(user) {
ret[user] = DropboxAccessToken(accessToken: accessToken, uid: user)
}
}
return ret
}
/**
Check if there are any stored access tokens
-returns: Whether there are stored access tokens
*/
public func hasStoredAccessTokens() -> Bool {
return self.getAllAccessTokens().count != 0
}
/**
Retrieve the access token for a particular user
- parameter user: The user whose token to retrieve
- returns: An access token if present, otherwise `nil`.
*/
public func getAccessToken(user: String) -> DropboxAccessToken? {
if let accessToken = DBKeychain.get(user) {
return DropboxAccessToken(accessToken: accessToken, uid: user)
} else {
return nil
}
}
/**
Delete a specific access token
- parameter token: The access token to delete
- returns: whether the operation succeeded
*/
public func clearStoredAccessToken(token: DropboxAccessToken) -> Bool {
return DBKeychain.delete(token.uid)
}
/**
Delete all stored access tokens
- returns: whether the operation succeeded
*/
public func clearStoredAccessTokens() -> Bool {
return DBKeychain.clear()
}
/**
Save an access token
- parameter token: The access token to save
- returns: whether the operation succeeded
*/
public func storeAccessToken(token: DropboxAccessToken) -> Bool {
return DBKeychain.set(token.uid, value: token.accessToken)
}
/**
Utility function to return an arbitrary access token
- returns: the "first" access token found, if any (otherwise `nil`)
*/
public func getFirstAccessToken() -> DropboxAccessToken? {
return self.getAllAccessTokens().values.first
}
}
#if os(iOS)
public class DropboxConnectController : UIViewController, WKNavigationDelegate {
var webView : WKWebView!
var onWillDismiss: ((didCancel: Bool) -> Void)?
var tryIntercept: ((url: NSURL) -> Bool)?
var cancelButton: UIBarButtonItem?
public init() {
super.init(nibName: nil, bundle: nil)
}
public init(URL: NSURL, tryIntercept: ((url: NSURL) -> Bool)) {
super.init(nibName: nil, bundle: nil)
self.startURL = URL
self.tryIntercept = tryIntercept
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Link to Dropbox"
self.webView = WKWebView(frame: self.view.bounds)
self.view.addSubview(self.webView)
self.webView.navigationDelegate = self
self.view.backgroundColor = UIColor.whiteColor()
self.cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancel:")
self.navigationItem.rightBarButtonItem = self.cancelButton
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !webView.canGoBack {
if nil != startURL {
loadURL(startURL!)
}
else {
webView.loadHTMLString("There is no `startURL`", baseURL: nil)
}
}
}
public func webView(webView: WKWebView,
decidePolicyForNavigationAction navigationAction: WKNavigationAction,
decisionHandler: (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.URL, callback = self.tryIntercept {
if callback(url: url) {
self.dismiss(true)
return decisionHandler(.Cancel)
}
}
return decisionHandler(.Allow)
}
public var startURL: NSURL? {
didSet(oldURL) {
if nil != startURL && nil == oldURL && isViewLoaded() {
loadURL(startURL!)
}
}
}
public func loadURL(url: NSURL) {
webView.loadRequest(NSURLRequest(URL: url))
}
func showHideBackButton(show: Bool) {
navigationItem.leftBarButtonItem = show ? UIBarButtonItem(barButtonSystemItem: .Rewind, target: self, action: "goBack:") : nil
}
func goBack(sender: AnyObject?) {
webView.goBack()
}
func cancel(sender: AnyObject?) {
dismiss(true, animated: (sender != nil))
}
func dismiss(animated: Bool) {
dismiss(false, animated: animated)
}
func dismiss(asCancel: Bool, animated: Bool) {
webView.stopLoading()
self.onWillDismiss?(didCancel: asCancel)
presentingViewController?.dismissViewControllerAnimated(animated, completion: nil)
}
}
#endif
| mit | b212c6876a2e6c3f1eaeae2346f51ad7 | 31.646077 | 160 | 0.590693 | 5.167812 | false | false | false | false |
wcharysz/BJSS-iOS-basket-assignment-source-code | ShoppingList/Rates.swift | 1 | 1190 | //
// Rates.swift
// ShoppingList
//
// Created by User on 18.10.2015.
// Copyright © 2015 Wojciech Charysz. All rights reserved.
//
import Foundation
enum Currency: String {
case AUD = "AUD"
case BGN = "BGN"
case BRL = "BRL"
case CAD = "CAD"
case CHF = "CHF"
case CNY = "CNY"
case CZK = "CZK"
case DKK = "DKK"
case GBP = "GBP"
case HKD = "HKD"
case HRK = "HRK"
case HUF = "HUF"
case IDR = "IDR"
case ILS = "ILS"
case INR = "INR"
case JPY = "JPY"
case KRW = "KRW"
case MXN = "MXN"
case MYR = "MYR"
case NOK = "NOK"
case NZD = "NZD"
case PHP = "PHP"
case PLN = "PLN"
case RON = "RON"
case RUB = "RUB"
case SEK = "SEK"
case SGD = "SGD"
case THB = "THB"
case TRY = "TRY"
case USD = "USD"
case ZAR = "ZAR"
}
class Rates: Mappable {
var base: String?
var date: NSDate?
var rates: [String: NSNumber]?
required init?(_ map: Map){
}
func mapping(map: Map) {
base <- map["base"]
date <- (map["date"], CustomDateFormatTransform(formatString: "yyy-MM-dd"))
rates <- map["rates"]
}
} | apache-2.0 | 9d75e4ac1e52846f9e7e09b5fe63ed02 | 18.193548 | 83 | 0.5164 | 2.943069 | false | false | false | false |
artemkalinovsky/SmashTag | Smashtag/Twitter/Tweet.swift | 1 | 9368 | //
// Tweet.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import Foundation
import UIKit
// a simple container class which just holds the data in a Tweet
// IndexedKeywords are substrings of the Tweet's text
// for example, a hashtag or other user or url that is mentioned in the Tweet
// note carefully the comments on the two range properties in an IndexedKeyword
// Tweet instances re created by fetching from Twitter using a TwitterRequest
public class Tweet : Printable
{
public let text: String!
public let user: User!
public let created: NSDate!
public let id: String?
public let media: [MediaItem]
public let hashtags: [IndexedKeyword]
public let urls: [IndexedKeyword]
public let userMentions: [IndexedKeyword]
public struct IndexedKeyword: Printable
{
public let keyword: String // will include # or @ or http:// prefix
public let range: Range<String.Index> // index into the Tweet's text property only
public let nsrange: NSRange // index into an NS[Attributed]String made from the Tweet's text
public init?(data: NSDictionary?, inText: String, prefix: String?) {
let indices = data?.valueForKeyPath(TwitterKey.Entities.Indices) as? NSArray
if let startIndex = (indices?.firstObject as? NSNumber)?.integerValue {
if let endIndex = (indices?.lastObject as? NSNumber)?.integerValue {
let length = count(inText)
if length > 0 {
let start = max(min(startIndex, length-1), 0)
let end = max(min(endIndex, length), 0)
if end > start {
var adjustedRange = advance(inText.startIndex, start)...advance(inText.startIndex, end-1)
var keywordInText = inText.substringWithRange(adjustedRange)
if prefix != nil && !keywordInText.hasPrefix(prefix!) && start > 0 {
adjustedRange = advance(inText.startIndex, start-1)...advance(inText.startIndex, end-2)
keywordInText = inText.substringWithRange(adjustedRange)
}
range = adjustedRange
keyword = keywordInText
if prefix == nil || keywordInText.hasPrefix(prefix!) {
nsrange = inText.rangeOfString(keyword, nearRange: NSMakeRange(startIndex, endIndex-startIndex))
if nsrange.location != NSNotFound {
// failable initializers are required to initialize all properties before returning failure
// (this is probably just a (temporary?) limitation of the implementation of Swift)
// however, it appears that (sometimes) you can "return" in the case of success like this
// and it avoids the warning (although "return" is sort of weird in an initializer)
// (this seems to work even though all the properties are NOT initialized for the "return nil" below)
// hopefully in future versions of Swift this will all not be an issue
// because you'll be allowed to fail without initializing all properties?
return
}
}
}
}
}
}
// it is possible we will get here without all properties being initialized
// hopefully that won't cause a problem even though the compiler does not complain? :)
return nil
}
public var description: String { get { return "\(keyword) (\(nsrange.location), \(nsrange.location+nsrange.length-1))" } }
}
public var description: String { return "\(user) - \(created)\n\(text)\nhashtags: \(hashtags)\nurls: \(urls)\nuser_mentions: \(userMentions)" + (id == nil ? "" : "\nid: \(id!)") }
public var attributedText: NSAttributedString! {
get {
var result = NSMutableAttributedString(string: self.text)
for hastag in hashtags {
result.addAttribute(NSForegroundColorAttributeName, value: self.hashTagColor, range: hastag.nsrange)
}
for url in urls {
result.addAttribute(NSForegroundColorAttributeName, value: self.urlMentionColor, range: url.nsrange)
}
for userMention in userMentions {
result.addAttribute(NSForegroundColorAttributeName, value: self.userMentionColor, range: userMention.nsrange)
}
return result
}
}
// MARK: - Private Implementation
private var hashTagColor: UIColor {
get {
return UIColor(red: 0.23,
green: 0.29,
blue: 0.99,
alpha: 1.0)
}
}
private var userMentionColor: UIColor {
get {
return UIColor(red: 1.0,
green: 0.64,
blue: 0.20,
alpha: 1.0)
}
}
private var urlMentionColor: UIColor {
get {
return UIColor(red: 0.72,
green: 0.53,
blue: 0.35,
alpha: 1.0)
}
}
init?(data: NSDictionary?) {
user = User(data: data?.valueForKeyPath(TwitterKey.User) as? NSDictionary)
text = data?.valueForKeyPath(TwitterKey.Text) as? String
created = (data?.valueForKeyPath(TwitterKey.Created) as? String)?.asTwitterDate
id = data?.valueForKeyPath(TwitterKey.ID) as? String
var accumulatedMedia = [MediaItem]()
if let mediaEntities = data?.valueForKeyPath(TwitterKey.Media) as? NSArray {
for mediaData in mediaEntities {
if let mediaItem = MediaItem(data: mediaData as? NSDictionary) {
accumulatedMedia.append(mediaItem)
}
}
}
media = accumulatedMedia
let hashtagMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.Hashtags) as? NSArray
if hashtagMentionsArray?.count > 0 {
hashtags = Tweet.getIndexedKeywords(hashtagMentionsArray, inText: text, prefix: "#")
} else {
hashtags = Array()
}
let urlMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.URLs) as? NSArray
if urlMentionsArray?.count > 0 {
urls = Tweet.getIndexedKeywords(urlMentionsArray, inText: text, prefix: "h")
} else {
urls = Array()
}
let userMentionsArray = data?.valueForKeyPath(TwitterKey.Entities.UserMentions) as? NSArray
if userMentionsArray?.count > 0 {
userMentions = Tweet.getIndexedKeywords(userMentionsArray, inText: text, prefix: "@")
} else {
userMentions = Array()
}
if user == nil || text == nil || created == nil {
return nil
}
}
private class func getIndexedKeywords(dictionary: NSArray?, inText: String, prefix: String? = nil) -> [IndexedKeyword] {
var results = [IndexedKeyword]()
if let indexedKeywords = dictionary {
for indexedKeywordData in indexedKeywords {
if let indexedKeyword = IndexedKeyword(data: indexedKeywordData as? NSDictionary, inText: inText, prefix: prefix) {
results.append(indexedKeyword)
}
}
}
return results
}
struct TwitterKey {
static let User = "user"
static let Text = "text"
static let Created = "created_at"
static let ID = "id_str"
static let Media = "entities.media"
struct Entities {
static let Hashtags = "entities.hashtags"
static let URLs = "entities.urls"
static let UserMentions = "entities.user_mentions"
static let Indices = "indices"
}
}
}
private extension NSString {
func rangeOfString(substring: NSString, nearRange: NSRange) -> NSRange {
var start = max(min(nearRange.location, length-1), 0)
var end = max(min(nearRange.location + nearRange.length, length), 0)
var done = false
while !done {
let range = self.rangeOfString(substring as String, options: NSStringCompareOptions.allZeros, range: NSMakeRange(start, end-start))
if range.location != NSNotFound {
return range
}
done = true
if start > 0 { start-- ; done = false }
if end < length { end++ ; done = false }
}
return NSMakeRange(NSNotFound, 0)
}
}
private extension String {
var asTwitterDate: NSDate? {
get {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
return dateFormatter.dateFromString(self)
}
}
}
| gpl-2.0 | c590d8495ad84bbcbc0093fd71df22f3 | 41.972477 | 183 | 0.563941 | 5.113537 | false | false | false | false |
hellogaojun/Swift-coding | swift学习教材案例/Swifter.playground/Pages/optional-chaining.xcplaygroundpage/Contents.swift | 3 | 733 |
import Foundation
class Toy {
let name: String
init(name: String) {
self.name = name
}
}
class Pet {
var toy: Toy?
}
class Child {
var pet: Pet?
}
let xiaoming = Child()
let toyName = xiaoming.pet?.toy?.name
if let toyName = xiaoming.pet?.toy?.name {
// 太好了,小明既有宠物,而且宠物还正好有个玩具
}
extension Toy {
func play() {
//...
}
}
xiaoming.pet?.toy?.play()
//let playClosure = {(child: Child) -> () in child.pet?.toy?.play()} //返回值将永远不为 nil
let playClosure = {(child: Child) -> ()? in child.pet?.toy?.play()}
if let result: () = playClosure(xiaoming) {
print("好开心~")
} else {
print("没有玩具可以玩 :(")
} | apache-2.0 | cb635a2daed6b421a89c51bc1594cfe5 | 14.209302 | 83 | 0.578867 | 2.643725 | false | false | false | false |
OmarPedraza/MZFormSheetPresentationController | Example/Swift/MZFormSheetPresentationController Swift Example/CustomTransition.swift | 1 | 2067 | //
// CustomTransition.swift
// MZFormSheetPresentationController Swift Example
//
// Created by Michal Zaborowski on 18.06.2015.
// Copyright (c) 2015 Michal Zaborowski. All rights reserved.
//
import UIKit
class CustomTransition: NSObject, MZFormSheetPresentationViewControllerTransitionProtocol {
func entryFormSheetControllerTransition(formSheetController: UIViewController, completionHandler: MZTransitionCompletionHandler) {
let bounceAnimation = CAKeyframeAnimation(keyPath: "transform")
bounceAnimation.fillMode = kCAFillModeBoth
bounceAnimation.removedOnCompletion = true
bounceAnimation.duration = 0.4
bounceAnimation.values = [
NSValue(CATransform3D: CATransform3DMakeScale(0.01, 0.01, 0.01)),
NSValue(CATransform3D: CATransform3DMakeScale(0.9, 0.9, 0.9)),
NSValue(CATransform3D: CATransform3DMakeScale(1.1, 1.1, 1.1)),
NSValue(CATransform3D: CATransform3DIdentity)
]
bounceAnimation.keyTimes = [0.0, 0.5, 0.75, 1.0]
bounceAnimation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)]
bounceAnimation.delegate = self
bounceAnimation.setValue((completionHandler as? AnyObject)!, forKey: "completionHandler")
formSheetController.view.layer.addAnimation(bounceAnimation, forKey: "bounce")
}
func exitFormSheetControllerTransition(formSheetController: UIViewController, completionHandler: MZTransitionCompletionHandler) {
var formSheetRect = formSheetController.view.frame
formSheetRect.origin.x = UIScreen.mainScreen().bounds.width
UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
formSheetController.view.frame = formSheetRect
}, completion: {(value: Bool) -> Void in
completionHandler()
})
}
}
| mit | ced22b08a78c5d7e7336309028a85556 | 48.214286 | 238 | 0.731979 | 5.219697 | false | false | false | false |
donileo/RMessage | Sources/RMController/RMController.swift | 1 | 4289 | //
// RMController.swift
// RMessage
//
// Created by Adonis Peralta on 8/2/18.
// Copyright © 2018 None. All rights reserved.
//
import Foundation
import HexColors
import UIKit
public class RMController: NSObject, RMPresenterDelegate {
/// The view controller this message is displayed in.
public var presentationViewController: UIViewController?
/// Delegate of the RMController object.
public weak var delegate: RMControllerDelegate?
// Protect access to this variable from data races
private(set) var messageOnScreen = false
private let queue: OperationQueue
public var queueCount: Int {
return queue.operationCount
}
public override init() {
queue = OperationQueue()
// Make it a serial queue
queue.maxConcurrentOperationCount = 1
}
/// Shows a notification message.
///
/// - Parameters:
/// - spec: A message spec to use for styling the message, please see *RMessageSpec for usage details.
/// - targetPosition: The position *to* which the message should be presented, (default = top).
/// - title: The title text of the message.
/// - body: The body text of the message.
/// - viewController: The view controller in which to present the message (optional).
/// - leftView: A view to show as the left view of the message.
/// - rightView: A view to show as the right view of the message.
/// - backgroundView: A view to show as the background view of the message.
/// - tapCompletion: A callback to be called when the message is tapped.
/// - presentCompletion: A callback to be called when the message is presented.
/// - dismissCompletion: A callback to be called when the message is dismissed.
public func showMessage(
withSpec spec: RMessageSpec, atPosition targetPosition: RMessagePosition = .top,
title: String, body: String? = nil, viewController: UIViewController? = nil,
leftView: UIView? = nil, rightView: UIView? = nil, backgroundView: UIView? = nil,
tapCompletion: (() -> Void)? = nil, presentCompletion: (() -> Void)? = nil,
dismissCompletion: (() -> Void)? = nil
) {
guard let message = RMessage(
spec: spec, title: title, body: body,
leftView: leftView, rightView: rightView, backgroundView: backgroundView
) else {
return
}
let animOpts = DefaultRMAnimationOptions()
let presentVC = viewController ?? presentationViewController ?? UIWindow.topViewController()
// Make sure we have a presentation view controller for the message
guard let presentationVC = presentVC else {
return
}
let animator = SlideAnimator(
targetPosition: targetPosition, view: message,
superview: presentationVC.view, contentView: message.contentView
)
let presenter = RMPresenter(
message: message, targetPosition: targetPosition, animator: animator,
animationOptions: animOpts, tapCompletion: tapCompletion, presentCompletion: presentCompletion,
dismissCompletion: dismissCompletion
)
delegate?.customize?(message: message, controller: self)
let presentOp = RMShowOperation(message: message, presenter: presenter)
queue.addOperation(presentOp)
}
/**
Fades out the currently displayed notification. If another notification is in the queue,
the next one will be displayed automatically
@return YES if the currently displayed notification was successfully dismissed. NO if no
notification was currently displayed.
*/
public func dismissOnScreenMessage(withCompletion completion: (() -> Void)? = nil) -> Bool {
if let operation = queue.operations.first as? RMShowOperation {
operation.presenter.dismiss(withCompletion: completion)
}
return true
}
public func cancelPendingDisplayMessages() {
queue.cancelAllOperations()
}
// MARK: RMessageDelegate Methods
/**
Call this method to notify any presenting or on screen messages that the interface has rotated.
Ideally should go inside the calling view controllers viewWillTransitionToSize:withTransitionCoordinator: method.
*/
public func interfaceDidRotate() {
if let operation = queue.operations.first as? RMShowOperation, operation.presenter.screenStatus == .presenting {
operation.presenter.interfaceDidRotate()
}
}
}
| mit | 965aceddb1a5684a377d0757117a00f3 | 36.286957 | 116 | 0.716418 | 4.732892 | false | false | false | false |
jeremy-pereira/EnigmaMachine | EnigmaMachine/KeyboardButton.swift | 1 | 5735 | //
// KeyboardButton.swift
// EnigmaMachine
//
// Created by Jeremy Pereira on 23/03/2015.
// Copyright (c) 2015, 2018 Jeremy Pereira. 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 Cocoa
import Toolbox
private let log = Logger.getLogger("EnigmaMachine.EnignmaMachine.KeyboardButton")
protocol KeyboardDelegate: AnyObject
{
func letterPressed(aLetter: Letter, keyboard: KeyboardView);
func letterReleased(keyboard: KeyboardView);
}
class KeyboardView: NSBox
{
weak var keyboardDelegate: KeyboardDelegate?
var timer: Timer?
@IBOutlet var singleStep: AutoKeyButton!
@IBOutlet var autoInput: NSSegmentedControl!
@IBAction func keyPressed(_ sender: AnyObject)
{
if let _ = sender as? KeyboardButton, let keyboardDelegate = keyboardDelegate
{
keyboardDelegate.letterReleased(keyboard: self)
}
}
func buttonPressed(keyboardButton : KeyboardButton)
{
if let keyboardDelegate = keyboardDelegate, let letter = keyboardButton.letter
{
keyboardDelegate.letterPressed(aLetter: letter, keyboard: self)
}
}
var timerShouldStop = false;
var timerMouseUp = false;
/// Action to perform when selecting auto input or not. The action is based
/// on the `autoInput` outlet. If its selected segment tag is 0 we turn the
/// timer off if it is running (and stop consuming characters from the
/// `AutoKeyButton`'s text field). If the tag is 1, we turn on the timer, if
/// it is not already running.
///
/// - Parameter sender: The object sending the action.
@IBAction func toggleTimer(_ sender: AnyObject)
{
let selectedSegment = autoInput.selectedSegment
guard selectedSegment != -1 else { return }
let tag = autoInput.tag(forSegment: selectedSegment)
switch tag
{
case 0:
if timer != nil
{
timerShouldStop = true;
}
case 1:
if timer == nil
{
timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true)
{
_ in
self.timerFired()
}
}
default:
log.warn("Invalid tag value for auto input: \(tag)")
}
}
func timerFired()
{
if timerMouseUp
{
timerMouseUp = false
self.keyPressed(singleStep)
if timerShouldStop
{
timer?.invalidate()
timer = nil;
timerShouldStop = false
}
}
else
{
timerMouseUp = true
singleStep.fixUpIdentifier()
self.buttonPressed(keyboardButton: singleStep)
}
}
}
class KeyboardButton: NSButton
{
var keyboard: KeyboardView?
{
get
{
var ret: KeyboardView?
var ancestorView = self.superview
while ancestorView != nil && ret == nil
{
if let keyboardView = ancestorView as? KeyboardView
{
ret = keyboardView
}
ancestorView = ancestorView?.superview
}
return ret
}
}
var letter: Letter?
{
var ret: Letter?
if self.title != ""
{
let idChar = self.title[self.title.startIndex]
if idChar != "$"
{
ret = Letter(rawValue: idChar)
}
}
return ret
}
override func mouseDown(with theEvent: NSEvent)
{
if let keyboard = keyboard
{
keyboard.buttonPressed(keyboardButton: self)
}
super.mouseDown(with: theEvent)
}
}
class AutoKeyButton: KeyboardButton
{
@IBOutlet var textField: NSTextField!
override func mouseDown(with theEvent: NSEvent)
{
fixUpIdentifier()
super.mouseDown(with: theEvent)
}
var _letter: Letter?
override var letter: Letter?
{
get
{
return _letter
}
}
/// Fix the identifier for the button
func fixUpIdentifier()
{
let rawCharacters = textField.stringValue
let charactersLeft = rawCharacters.uppercased()
var nextLetter: Letter?
var replacementString = ""
// Go through all the characters until we find the first one that
// could be a letter and make that the letter that the key thinks it has.
// All the characters after that are put back in the text field.
for character in charactersLeft
{
if nextLetter != nil
{
replacementString += [ character ]
}
else if let candidateLetter = Letter(rawValue: character),
candidateLetter != .UpperBound // Could be if they typed a $
{
nextLetter = candidateLetter
}
}
if let nextLetter = nextLetter
{
self._letter = nextLetter
}
else
{
self._letter = nil
}
textField.stringValue = replacementString
}
}
| apache-2.0 | 30f066f2f24f2e8fd99119cd2edaad32 | 24.602679 | 86 | 0.579076 | 4.910103 | false | false | false | false |
material-foundation/material-testing-ios | src/MDFTesting.swift | 1 | 1848 | /*
Copyright 2019-present Google Inc.. 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 XCTest
extension XCTestCase {
public func MDFAssertEqualColors(
_ color1: UIColor,
_ color2: UIColor,
file: StaticString = #file,
line: UInt = #line
) {
var red1: CGFloat
var green1: CGFloat
var blue1: CGFloat
var alpha1: CGFloat
(red1, green1, blue1, alpha1) = (0.0, 0.0, 0.0, 0.0)
color1.getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1)
var red2: CGFloat
var green2: CGFloat
var blue2: CGFloat
var alpha2: CGFloat
(red2, green2, blue2, alpha2) = (0.0, 0.0, 0.0, 0.0)
color2.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2)
let assertionMessage = "the first color is not equal to the second color"
XCTAssertEqual(
red1, red2, accuracy: CGFloat.ulpOfOne, "Red component: " + assertionMessage, file: file,
line: line)
XCTAssertEqual(
green1, green2, accuracy: CGFloat.ulpOfOne, "Green component: " + assertionMessage,
file: file, line: line)
XCTAssertEqual(
blue1, blue2, accuracy: CGFloat.ulpOfOne, "Blue component: " + assertionMessage, file: file,
line: line)
XCTAssertEqual(
alpha1, alpha2, accuracy: CGFloat.ulpOfOne, "Alpha component: " + assertionMessage,
file: file, line: line)
}
}
| apache-2.0 | 8949ad69bb96da9bbb8142be0f447773 | 31.421053 | 98 | 0.694805 | 3.64497 | false | false | false | false |
mshhmzh/firefox-ios | Sync/Synchronizers/Bookmarks/BookmarksDownloader.swift | 4 | 6989 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
private let log = Logger.syncLogger
let BookmarksStorageVersion = 2
/**
* This is like a synchronizer, but it downloads records bit by bit, eventually
* notifying that the local storage is up to date with the server contents.
*
* Because batches might be separated over time, it's possible for the server
* state to change between calls. These state changes might include:
*
* 1. New changes arriving. This is fairly routine, but it's worth noting that
* changes might affect existing records that have been batched!
* 2. Wipes. The collection (or the server as a whole) might be deleted. This
* should be accompanied by a change in syncID in meta/global; it's the caller's
* responsibility to detect this.
* 3. A storage format change. This should be unfathomably rare, but if it happens
* we must also be prepared to discard our existing batched data.
* 4. TTL expiry. We need to do better about TTL handling in general, but here
* we might find that a downloaded record is no longer live by the time we
* come to apply it! This doesn't apply to bookmark records, so we will ignore
* it for the moment.
*
* Batch downloading without continuation tokens is achieved as follows:
*
* * A minimum timestamp is established. This starts as zero.
* * A fetch is issued against the server for records changed since that timestamp,
* ordered by modified time ascending, and limited to the batch size.
* * If the batch is complete, we flush it to storage and advance the minimum
* timestamp to just before the newest record in the batch. This ensures that
* a divided set of records with the same modified times will be downloaded
* entirely so long as the set is never larger than the batch size.
* * Iterate until we determine that there are no new records to fetch.
*
* Batch downloading with continuation tokens is much easier:
*
* * A minimum timestamp is established.
* * Make a request with limit=N.
* * Look for an X-Weave-Next-Offset header. Supply that in the next request.
* Also supply X-If-Unmodified-Since to avoid missed modifications.
*
* We do the latter, because we only support Sync 1.5. The use of the offset
* allows us to efficiently process batches, particularly those that contain
* large sets of records with the same timestamp. We still maintain the last
* modified timestamp to allow for resuming a batch in the case of a conflicting
* write, detected via X-I-U-S.
*/
public class BookmarksMirrorer {
private let downloader: BatchingDownloader<BookmarkBasePayload>
private let storage: BookmarkBufferStorage
private let batchSize: Int
public init(storage: BookmarkBufferStorage, client: Sync15CollectionClient<BookmarkBasePayload>, basePrefs: Prefs, collection: String, batchSize: Int=100) {
self.storage = storage
self.downloader = BatchingDownloader(collectionClient: client, basePrefs: basePrefs, collection: collection)
self.batchSize = batchSize
}
// TODO
public func storageFormatDidChange() {
}
// TODO
public func onWipeWasAppliedToStorage() {
}
private func applyRecordsFromBatcher() -> Success {
let retrieved = self.downloader.retrieve()
let invalid = retrieved.filter { !$0.payload.isValid() }
if !invalid.isEmpty {
// There's nothing we can do with invalid input. There's also no point in
// tracking failing GUIDs here yet: if another client reuploads those records
// correctly, we'll encounter them routinely due to a newer timestamp.
// The only improvement we could make is to drop records from the buffer if we
// happen to see a new, invalid one before somehow syncing again, but that's
// unlikely enough that it's not worth doing.
//
// Bug 1258801 tracks recording telemetry for these invalid items, which is
// why we don't simply drop them on the ground at the download stage.
//
// We might also choose to perform certain simple recovery actions here: for example,
// bookmarks with null URIs are clearly invalid, and could be treated as if they
// weren't present on the server, or transparently deleted.
log.warning("Invalid records: \(invalid.map { $0.id }.joinWithSeparator(", ")).")
}
let mirrorItems = retrieved.flatMap { record -> BookmarkMirrorItem? in
guard record.payload.isValid() else {
return nil
}
return (record.payload as MirrorItemable).toMirrorItem(record.modified)
}
if mirrorItems.isEmpty {
log.debug("Got empty batch.")
return succeed()
}
log.debug("Applying \(mirrorItems.count) downloaded bookmarks.")
return self.storage.applyRecords(mirrorItems)
}
public func go(info: InfoCollections, greenLight: () -> Bool) -> SyncResult {
if !greenLight() {
log.info("Green light turned red. Stopping mirror operation.")
return deferMaybe(SyncStatus.NotStarted(.RedLight))
}
log.debug("Downloading up to \(self.batchSize) records.")
return self.downloader.go(info, limit: self.batchSize)
.bind { result in
guard let end = result.successValue else {
log.warning("Got failure: \(result.failureValue!)")
return deferMaybe(result.failureValue!)
}
switch end {
case .Complete:
log.info("Done with batched mirroring.")
return self.applyRecordsFromBatcher()
>>> effect(self.downloader.advance)
>>> self.storage.doneApplyingRecordsAfterDownload
>>> always(SyncStatus.Completed)
case .Incomplete:
log.debug("Running another batch.")
// This recursion is fine because Deferred always pushes callbacks onto a queue.
return self.applyRecordsFromBatcher()
>>> effect(self.downloader.advance)
>>> { self.go(info, greenLight: greenLight) }
case .Interrupted:
log.info("Interrupted. Aborting batching this time.")
return deferMaybe(SyncStatus.Partial)
case .NoNewData:
log.info("No new data. No need to continue batching.")
self.downloader.advance()
return deferMaybe(SyncStatus.Completed)
}
}
}
func advanceNextDownloadTimestampTo(timestamp: Timestamp) {
self.downloader.advanceTimestampTo(timestamp)
}
}
| mpl-2.0 | 4ec769259ec5b01869cfeffb897eaa2d | 44.679739 | 160 | 0.663042 | 4.836678 | false | false | false | false |
scootpl/Na4lapyAPI | Sources/Na4LapyCore/ShelterBackend.swift | 1 | 1540 | //
// ShelterBackend.swift
// Na4lapyAPI
//
// Created by Wojciech Bilicki on 22/02/2017.
//
//
import Foundation
public class ShelterBackend {
let db: DBLayer
public init(db: DBLayer) {
self.db = db
}
public func get(byId id: Int) throws -> JSONDictionary {
let dbresult = try db.fetch(byId: id, table: Config.shelterTable, idname: ShelterDBKey.id)
if dbresult.count == 0 {
throw ResultCode.ShelterBackendNoData
}
if dbresult.count > 1 {
throw ResultCode.ShelterBackendTooManyEntries
}
guard let shelter = Shelter(dictionary: dbresult.first!) else {
throw ResultCode.ShelterBackendBadParameters
}
return shelter.dictionaryRepresentation()
}
public func edit(withDictionary dictionary: JSONDictionary) throws -> Int {
guard let shelter = Shelter(withJSON: dictionary) else {
throw ResultCode.ShelterBackendBadParameters
}
let id = try db.editShelter(values: shelter.dbRepresentation())
return id
}
public func get() throws -> [JSONDictionary] {
let dbresult = try db.fetch(fromTable: Config.shelterTable)
if dbresult.isEmpty {
throw ResultCode.ShelterBackendNoData
}
let shelters = dbresult.flatMap({ Shelter.init(dictionary: $0) })
if shelters.isEmpty {
throw ResultCode.ShelterBackendNoData
}
return shelters.map { $0.dictionaryRepresentation() }
}
}
| apache-2.0 | 82278eaa9c211785132b776e7da6b259 | 24.245902 | 98 | 0.631818 | 4.556213 | false | false | false | false |
CaryZheng/ZWeatherServer | ZWeatherServer/App/DB/DBManager.swift | 1 | 7052 | import Foundation
import MySQL
class DBManager {
private static var mInstance: DBManager!
static func getInstance() -> DBManager {
if nil == mInstance {
mInstance = DBManager()
}
return mInstance
}
private var mysql: MySQL.Database!
init() {
setUp()
}
private func setUp() {
do {
mysql = try MySQL.Database(
host: DBConfig.HOST,
user: DBConfig.USER,
password: DBConfig.PWD,
database: DBConfig.DATABASE,
port: 3306
)
print("MySQL connect success")
} catch {
print("MySQL connect failed")
}
}
func isAccountExisted(name: String) throws -> (isOK: Bool, userID: Int?) {
do {
let results = try mysql.execute("SELECT user_id FROM user where name=\"\(name)\";")
print("isAccountExisted results = \(results)")
if results.count > 0 {
guard let value = results[0]["user_id"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .number(.int(let userID)) = value else {
throw ZException.DB_DATA_EXCEPTION
}
print("userID = \(userID)")
return (true, userID)
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
return (false, nil)
}
func signUp(name: String, pwd: String) throws -> (isOK: Bool, userID: Int?) {
do {
let accountResult = try isAccountExisted(name: name)
if accountResult.isOK {
return (false, nil)
}
var results = try mysql.execute("SELECT * FROM user ORDER BY user_id DESC LIMIT 1")
print("signUp results = \(results)")
var userID = 1
if results.count > 0 {
guard let value = results[0]["user_id"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .number(.int(let lastUserID)) = value else {
throw ZException.DB_DATA_EXCEPTION
}
userID = lastUserID + 1
}
print("userID = \(userID)")
results = try mysql.execute("INSERT INTO user(user_id, name, pwd) VALUES(\(userID), \"\(name)\", \"\(pwd)\")")
if 0 == results.count {
// sign up success
return (true, userID)
} else {
// sign up fail
return (false, nil)
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
}
func signIn(name: String, pwd: String) throws -> (isOK: Bool, userID: Int?) {
do {
let accountResult = try isAccountExisted(name: name)
if !accountResult.isOK {
return (false, nil)
}
var results = try mysql.execute("SELECT * FROM user WHERE name=\"\(name)\" AND pwd=\"\(pwd)\"")
print("signIn results = \(results)")
if results.count > 0 {
guard let userIDValue = results[0]["user_id"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .number(.int(let userID)) = userIDValue else {
throw ZException.DB_DATA_EXCEPTION
}
guard let nameValue = results[0]["name"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .string(let localName) = nameValue else {
throw ZException.DB_DATA_EXCEPTION
}
guard let pwdValue = results[0]["pwd"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .string(let localPwd) = pwdValue else {
throw ZException.DB_DATA_EXCEPTION
}
print("userID = \(userID)")
if name == localName
&& pwd == localPwd {
return (true, userID)
} else {
return (false, nil)
}
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
return (false, nil)
}
func updateSignInToken(userID: Int, token: String) throws -> Bool {
do {
var results = try mysql.execute("SELECT * FROM sign_in WHERE user_id=\(userID);")
if 0 == results.count {
// insert
results = try mysql.execute("INSERT INTO sign_in(user_id, token) VALUES(\(userID), \"\(token)\");")
if 0 == results.count {
return true
}
} else {
// update
results = try mysql.execute("UPDATE sign_in SET token=\"\(token)\" WHERE user_id=\(userID);")
if 0 == results.count {
return true
}
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
return false
}
func isSignInTokenValid(userID: Int, token: String) throws -> Bool {
do {
let results = try mysql.execute("SELECT token FROM sign_in where user_id=\"\(userID)\";")
print("isSignInTokenValid results = \(results)")
if results.count > 0 {
guard let tokenValue = results[0]["token"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .string(let localToken) = tokenValue else {
throw ZException.DB_DATA_EXCEPTION
}
if localToken == token {
return true
} else {
return false
}
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
return false
}
func getUserInfo(userID: Int) throws -> (isOK: Bool, name: String?) {
do {
let results = try mysql.execute("SELECT name FROM user WHERE user_id=\"\(userID)\";")
if results.count > 0 {
guard let nameValue = results[0]["name"] else {
throw ZException.DB_DATA_EXCEPTION
}
guard case .string(let localName) = nameValue else {
throw ZException.DB_DATA_EXCEPTION
}
return (true, localName)
}
} catch {
throw ZException.DB_QUERY_EXCEPTION
}
return (false, nil)
}
}
| mit | 53074a08c36c0f05f2e65059cd14d0c1 | 31.8 | 122 | 0.449376 | 5.173881 | false | false | false | false |
CalebeEmerick/RandomNotification | Source/RandomNotification/NotificationView.swift | 1 | 3029 | //
// NotificationView.swift
// RandomNotification
//
// Created by Calebe Emerick on 19/12/16.
// Copyright © 2016 CalebeEmerick. All rights reserved.
//
import UIKit
final class NotificationView : UIView {
@IBOutlet fileprivate weak var categoryName: UILabel!
@IBOutlet fileprivate weak var notificationButton: UIButton!
@IBOutlet fileprivate weak var cancelButton: UIButton!
@IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView!
@IBAction private func cancelAction(_ sender: UIButton) {
stopLoadingIfNeeded()
cancelDidTap?()
}
@IBAction private func sendNotification(_ sender: UIButton) {
sendDidTap?()
}
fileprivate enum ButtonState { case loading, stopped }
fileprivate var buttonState: ButtonState = .stopped
var cancelDidTap: (() -> Void)?
var sendDidTap: (() -> Void)?
var category: Category? { didSet { updateCategoryName() } }
}
extension NotificationView {
override func awakeFromNib() {
super.awakeFromNib()
notificationButtonStyle()
cancelButtonStyle()
}
}
extension NotificationView {
func showLoading() {
DispatchQueue.main.async {
self.notificationButton.isEnabled = false
self.notificationButton.setTitle("", for: .disabled)
self.activityIndicator.startAnimating()
self.buttonState = .loading
}
}
func stopLoading() {
DispatchQueue.main.async {
self.notificationButton.isEnabled = true
self.notificationButton.setTitle("Enviar Notificação", for: .normal)
self.activityIndicator.stopAnimating()
self.buttonState = .stopped
}
}
fileprivate func updateCategoryName() {
guard let category = category else { return }
self.animateNameChange(category.nameFormatted)
}
fileprivate func notificationButtonStyle() {
notificationButton.layer.cornerRadius = 5
notificationButton.clipsToBounds = true
}
fileprivate func cancelButtonStyle() {
cancelButton.layer.borderWidth = 1
cancelButton.layer.borderColor = Color(hexString: "#DE352E").cgColor
cancelButton.layer.cornerRadius = 5
cancelButton.clipsToBounds = true
}
fileprivate func stopLoadingIfNeeded() {
guard buttonState == .loading else { return }
stopLoading()
}
private func animateNameChange(_ name: String) {
animate(name: name)
}
private func animate(name: String) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animation.type = kCATransitionFade
animation.duration = 0.25
categoryName.layer.add(animation, forKey: nil)
categoryName.text = name
}
}
| mit | 053e6a5729e47d37144c3dd497427173 | 27.018519 | 99 | 0.63384 | 5.51184 | false | false | false | false |
sachin004/firefox-ios | SyncTests/DownloadTests.swift | 5 | 4730 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Sync
import XCTest
func identity<T>(x: T) -> T {
return x
}
private class MockBackoffStorage: BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp?
func clearServerBackoff() {
serverBackoffUntilLocalTimestamp = nil
}
func isInBackoff(now: Timestamp) -> Timestamp? {
return nil
}
}
// Non-encrypting 'encrypter'.
internal func getEncrypter() -> RecordEncrypter<CleartextPayloadJSON> {
let serializer: Record<CleartextPayloadJSON> -> JSON? = { $0.payload }
let factory: String -> CleartextPayloadJSON = { CleartextPayloadJSON($0) }
return RecordEncrypter(serializer: serializer, factory: factory)
}
class DownloadTests: XCTestCase {
func getClient(server: MockSyncServer) -> Sync15StorageClient? {
guard let url = server.baseURL.asURL else {
XCTFail("Couldn't get URL.")
return nil
}
let authorizer: Authorizer = identity
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
print("URL: \(url)")
return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage())
}
func getServer() -> MockSyncServer {
let server = MockSyncServer(username: "1234567")
server.storeRecords([], inCollection: "bookmarks")
server.start()
return server
}
func testBasicDownload() {
let server = getServer()
server.storeRecords([], inCollection: "bookmarks")
let storageClient = getClient(server)!
let bookmarksClient = storageClient.clientForCollection("bookmarks", encrypter: getEncrypter())
let expectation = self.expectationWithDescription("Waiting for result.")
let deferred = bookmarksClient.getSince(0)
deferred >>== { response in
XCTAssertEqual(response.metadata.status, 200)
expectation.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
func testDownloadBatches() {
let guid1: GUID = "abcdefghijkl"
let ts1: Timestamp = 1326254123650
let rec1 = MockSyncServer.makeValidEnvelope(guid1, modified: ts1)
let guid2: GUID = "bbcdefghijkl"
let ts2: Timestamp = 1326254125650
let rec2 = MockSyncServer.makeValidEnvelope(guid2, modified: ts2)
let server = getServer()
server.storeRecords([rec1], inCollection: "clients", now: ts1)
let storageClient = getClient(server)!
let bookmarksClient = storageClient.clientForCollection("clients", encrypter: getEncrypter())
let prefs = MockProfilePrefs()
let batcher = BatchingDownloader(collectionClient: bookmarksClient, basePrefs: prefs, collection: "clients")
let ic1 = InfoCollections(collections: ["clients": ts1])
let fetch1 = batcher.go(ic1, limit: 1).value
XCTAssertEqual(fetch1.successValue, DownloadEndState.Complete)
XCTAssertEqual(0, batcher.baseTimestamp) // This isn't updated until after success.
let records1 = batcher.retrieve()
XCTAssertEqual(1, records1.count)
XCTAssertEqual(guid1, records1[0].id)
batcher.advance()
XCTAssertNotEqual(0, batcher.baseTimestamp)
// Fetching again yields nothing, because the collection hasn't
// changed.
XCTAssertEqual(batcher.go(ic1, limit: 1).value.successValue, DownloadEndState.NoNewData)
// More records. Start again.
batcher.reset().value
let ic2 = InfoCollections(collections: ["clients": ts2])
server.storeRecords([rec2], inCollection: "clients", now: ts2)
let fetch2 = batcher.go(ic2, limit: 1).value
XCTAssertEqual(fetch2.successValue, DownloadEndState.Incomplete)
let records2 = batcher.retrieve()
XCTAssertEqual(1, records2.count)
XCTAssertEqual(guid1, records2[0].id)
batcher.advance()
let fetch3 = batcher.go(ic2, limit: 1).value
XCTAssertEqual(fetch3.successValue, DownloadEndState.Complete)
let records3 = batcher.retrieve()
XCTAssertEqual(1, records3.count)
XCTAssertEqual(guid2, records3[0].id)
batcher.advance()
let fetch4 = batcher.go(ic2, limit: 1).value
XCTAssertEqual(fetch4.successValue, DownloadEndState.NoNewData)
let records4 = batcher.retrieve()
XCTAssertEqual(0, records4.count)
batcher.advance()
}
} | mpl-2.0 | 2967518dfb5fd26519cae29c48407c99 | 36.251969 | 143 | 0.67315 | 4.509056 | false | false | false | false |
xeo-it/poggy | Poggy/ViewControllers/ActionsViewController.swift | 1 | 5438 | //
// ViewController.swift
// Poggy
//
// Created by Francesco Pretelli on 24/04/16.
// Copyright © 2016 Francesco Pretelli. All rights reserved.
//
import UIKit
import WatchConnectivity
import ObjectMapper
class ActionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, WCSessionDelegate {
@IBOutlet weak var noActionsLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addNewActionButton: UIButton!
var actions = [PoggyAction]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
readActions()
addNavBarButtons()
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
} else {
NSLog("WCSession not supported")
}
getSlackKeys()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.newActionHasBeenAdded(_:)), name: PoggyConstants.NEW_ACTION_CREATED, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
title = ""
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
title = "Poggy"
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
addNewActionButton.layer.cornerRadius = addNewActionButton.frame.width / 2
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "NewActionSegue" {
if let destination = segue.destinationViewController as? SlackActionViewController {
if let action = sender as? PoggyAction {
destination.updateFromActionsViewController(action)
}
}
}
}
func getSlackKeys() {
SlackHelper.instance.setSlackConsumerKey(BuddyBuildSDK.valueForDeviceKey(PoggyConstants.SLACK_CONSUMER_KEY))
SlackHelper.instance.setSlackConsumerSecret(BuddyBuildSDK.valueForDeviceKey(PoggyConstants.SLACK_CONSUMER_SECRET))
}
//MARK: WCSessionDelegate functions
func sessionDidBecomeInactive(session: WCSession) {
}
func session(session: WCSession, activationDidCompleteWithState activationState: WCSessionActivationState, error: NSError?) {
}
func sessionDidDeactivate(session: WCSession) {
}
//MARK: Actions functions
func readActions() {
if let readActions = ActionsHelper.instance.getActions() {
actions = readActions
tableView.reloadData()
}
if actions.count > 0 {
noActionsLabel.hidden = true
} else {
noActionsLabel.hidden = false
}
}
func saveActions() {
ActionsHelper.instance.setActions(actions)
updateActions()
}
func syncActionsWithWatch(){
do {
var actionsDict = [String : AnyObject]()
let actions = ActionsHelper.instance.getActions()
if let actionData = Mapper().toJSONString(actions!, prettyPrint: true) {
actionsDict[PoggyConstants.ACTIONS_DICT_ID] = actionData
try WCSession.defaultSession().updateApplicationContext(actionsDict)
}
} catch {
NSLog("Error Syncing actions with watch: \(error)")
}
}
func newActionHasBeenAdded(notification: NSNotification) {
updateActions()
}
func updateActions() {
readActions()
tableView.reloadData()
syncActionsWithWatch()
}
//MARK: TableView Delegate Functions
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("ActionCell", forIndexPath: indexPath) as! ActionCell
cell.updateData(actions[indexPath.row])
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return actions.count
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Destructive, title: NSLocalizedString("Delete", comment: "")) { [weak self] (action, indexPath) in
self?.actions.removeAtIndex(indexPath.row)
self?.saveActions()
}
return [delete]
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let action = self.actions[indexPath.row]
action.actionIndex = indexPath.row
self.performSegueWithIdentifier("NewActionSegue", sender: action)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| apache-2.0 | 8c28680d0699d90ef9140eb22e550b91 | 31.171598 | 169 | 0.645761 | 5.45336 | false | false | false | false |
kristopherjohnson/kjchess | kjchess/Position_legalMoves.swift | 1 | 17491 | //
// Position_legalMoves.swift
// kjchess
//
// Copyright © 2017 Kristopher Johnson. All rights reserved.
//
extension Position {
/// Generate sequence of legal moves for this `Position`.
///
/// This method is `mutating` because it might temporarily
/// apply a move to check whether the king is left in check.
public mutating func legalMoves() -> [Move] {
let possibles = possibleMoves()
guard let kingLocation = board.kingLocation(player: toMove) else {
return possibles
}
let isInCheck = isAttacked(location: kingLocation, by: toMove.opponent)
var result = [Move]()
result.reserveCapacity(possibles.count)
for move in possibles {
if isLegal(move: move, kingLocation: kingLocation, isInCheck: isInCheck) {
result.append(move)
}
}
return result
}
/// Generate array of possible moves for this `Position`.
///
/// The generated moves will all be valid in the sense that
/// the piece can perform the move/capture. However, this
/// method does not verify that the move will not leave
/// the player's king in check or that it doesn't result
/// in a repeated board position.
private func possibleMoves() -> [Move] {
let piecesLocations = board.pieces(player: toMove)
var moves = [Move]()
moves.reserveCapacity(200)
for (piece, location) in piecesLocations {
addMoves(piece: piece, location: location, to: &moves)
}
return moves
}
/// Add moves for a `Piece` at the given `Location` to an array.
private func addMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
switch piece.kind {
case .pawn: addPawnMoves(piece: piece, location: location, to: &moves)
case .knight: addKnightMoves(piece: piece, location: location, to: &moves)
case .rook: addRookMoves(piece: piece, location: location, to: &moves)
case .bishop: addBishopMoves(piece: piece, location: location, to: &moves)
case .queen: addQueenMoves(piece: piece, location: location, to: &moves)
case .king: addKingMoves(piece: piece, location: location, to: &moves)
}
}
private func addSlideMoves(piece: Piece, location: Location, vectors: [(Int, Int)],
to moves: inout [Move]) {
let player = piece.player
for (h, v) in vectors {
var file = location.file + h
var rank = location.rank + v
while let targetLocation = Location.ifValid(file: file, rank: rank) {
if let occupant = board[targetLocation] {
if occupant.player != player {
moves.append(.capture(piece: piece,
from: location,
to: targetLocation,
captured: occupant.kind))
}
break
}
else {
moves.append(.move(piece: piece, from: location, to: targetLocation))
file = file + h
rank = rank + v
}
}
}
}
// MARK:- Pawn
private static let whitePawnCaptureMoves = [(-1, 1), (1, 1)]
private static let blackPawnCaptureMoves = [(-1, -1), (1, -1)]
private static func pawnCaptureMoves(player: Player) -> [(Int, Int)] {
switch player {
case .white: return whitePawnCaptureMoves
case .black: return blackPawnCaptureMoves
}
}
private static func pawnMoveDirection(player: Player) -> Int {
switch player {
case .white: return 1
case .black: return -1
}
}
private static func pawnPromotionRank(player: Player) -> Int {
switch player {
case .white: return Board.maxRank
case .black: return Board.minRank
}
}
private static func pawnStartRank(player: Player) -> Int {
switch player {
case .white: return Board.minRank + 1
case .black: return Board.maxRank - 1
}
}
private func addPawnMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
let player = piece.player
let file = location.file
let rank = location.rank
if Board.minRank < rank && rank < Board.maxRank {
let promotionRank = Position.pawnPromotionRank(player: player)
let moveDirection = Position.pawnMoveDirection(player: player)
let nextRank = rank + moveDirection
if board.isEmpty(file: file, rank: nextRank) {
let to = Location(file, nextRank)
if to.rank == promotionRank {
for kind in PieceKind.promotionKinds {
moves.append(.promote(player: player,
from: location,
to: to,
promoted: kind))
}
}
else {
moves.append(.move(piece: piece, from: location, to: to))
let startRank = Position.pawnStartRank(player: player)
if rank == startRank {
let jumpRank = startRank + 2 * moveDirection
if board.isEmpty(file: file, rank: jumpRank) {
moves.append(.move(piece: piece,
from: location,
to: Location(file, jumpRank)))
}
}
}
}
let opponent = player.opponent
let captureMoves = Position.pawnCaptureMoves(player: player)
for (h, v) in captureMoves {
if let captureLocation = Location.ifValid(file: file + h, rank: rank + v) {
if let occupant = board[captureLocation] {
if occupant.player == opponent {
if captureLocation.rank == promotionRank {
for kind in PieceKind.promotionKinds {
moves.append(.promoteCapture(player: player,
from: location,
to: captureLocation,
captured: occupant.kind,
promoted: kind))
}
}
else {
moves.append(.capture(piece: piece,
from: location,
to: captureLocation,
captured: occupant.kind))
}
}
}
else if let enPassantCaptureLocation = enPassantCaptureLocation,
captureLocation == enPassantCaptureLocation {
moves.append(.enPassantCapture(player: player,
from: location,
to: enPassantCaptureLocation))
}
}
}
}
}
// MARK:- Knight
private static let knightJumps = [
( 1, 2), ( 1, -2),
(-1, 2), (-1, -2),
( 2, 1), ( 2, -1),
(-2, 1), (-2, -1)
]
private func addKnightMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
let file = location.file
let rank = location.rank
let player = piece.player
for (h, v) in Position.knightJumps {
if let targetLocation = Location.ifValid(file: file + h, rank: rank + v) {
if let occupant = board[targetLocation] {
if occupant.player != player {
moves.append(.capture(piece: piece,
from: location,
to: targetLocation,
captured: occupant.kind))
}
}
else {
moves.append(.move(piece: piece, from: location, to: targetLocation))
}
}
}
}
// MARK:- Rook
private static let rookVectors = [
(1, 0), (-1, 0),
(0, 1), ( 0, -1)
]
private static let pieceKindsWithRookVectors: [PieceKind]
= [.rook, .queen]
private func addRookMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
addSlideMoves(piece: piece,
location: location,
vectors: Position.rookVectors,
to: &moves)
}
// MARK:- Bishop
private static let bishopVectors = [
(1, 1), (-1, 1),
(1, -1), (-1, -1)
]
private static let pieceKindsWithBishopVectors: [PieceKind]
= [.bishop, .queen]
private func addBishopMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
addSlideMoves(piece: piece,
location: location,
vectors: Position.bishopVectors,
to: &moves)
}
// MARK:- Queen
private static let eightDirections = [
(1, 0), (-1, 0),
(0, 1), ( 0, -1),
(1, 1), (-1, 1),
(1, -1), (-1, -1)
]
private func addQueenMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
addSlideMoves(piece: piece,
location: location,
vectors: Position.eightDirections,
to: &moves)
}
// MARK:- King
private func addKingMoves(piece: Piece, location: Location,
to moves: inout [Move]) {
let file = location.file
let rank = location.rank
let player = piece.player
for (h, v) in Position.eightDirections {
if let targetLocation = Location.ifValid(file: file + h, rank: rank + v) {
if let occupant = board[targetLocation] {
if occupant.player != player {
moves.append(.capture(piece: piece,
from: location,
to: targetLocation,
captured: occupant.kind))
}
}
else {
moves.append(.move(piece: piece,
from: location,
to: targetLocation))
}
}
}
switch player {
case .white:
if whiteCanCastleKingside &&
board[e1] == WK &&
board[f1] == nil &&
board[g1] == nil &&
board[h1] == WR
{
moves.append(.castleKingside(player: player))
}
if whiteCanCastleQueenside &&
board[e1] == WK &&
board[d1] == nil &&
board[c1] == nil &&
board[b1] == nil &&
board[a1] == WR
{
moves.append(.castleQueenside(player: player))
}
case .black:
if blackCanCastleKingside &&
board[e8] == BK &&
board[f8] == nil &&
board[g8] == nil &&
board[h8] == BR
{
moves.append(.castleKingside(player: player))
}
if blackCanCastleQueenside &&
board[e8] == BK &&
board[d8] == nil &&
board[c8] == nil &&
board[b8] == nil &&
board[a8] == BR
{
moves.append(.castleQueenside(player: player))
}
}
}
// MARK:- Legal moves
/// Determine whether specified move is legal given the king's position.
private mutating func isLegal(move: Move, kingLocation: Location, isInCheck: Bool) -> Bool {
let from = move.from
let opponent = move.player.opponent
// If King moving, ensure it doesn't move into check.
if from == kingLocation && !move.isResignation {
if isAttacked(location: move.to, by: opponent) {
return false
}
// If castling, can't be in check or move through attacked squares
switch move {
case .castleKingside(.white):
if isInCheck || isAttacked(location: f1, by: opponent) {
return false
}
case .castleQueenside(.white):
if isInCheck || isAttacked(location: d1, by: opponent) {
return false
}
case .castleKingside(.black):
if isInCheck || isAttacked(location: f8, by: opponent) {
return false
}
case .castleQueenside(.black):
if isInCheck || isAttacked(location: d8, by: opponent) {
return false
}
default:
break
}
}
else if isInCheck
|| from.isSameDiagonal(kingLocation)
|| from.isSameRank(kingLocation)
|| from.isSameFile(kingLocation)
{
// Ensure King is not left in check.
let undo = apply(move)
let isLeftInCheck = isAttacked(location: kingLocation, by: opponent)
unapply(undo)
if isLeftInCheck {
return false
}
}
return true
}
/// Determine whether a given square is under attack by any of a player's pieces.
private func isAttacked(location: Location, by player: Player) -> Bool {
let file = location.file
let rank = location.rank
// Check for knight attack.
for (h, v) in Position.knightJumps {
if let attackerLocation = Location.ifValid(file: file + h, rank: rank + v) {
if let attacker = board[attackerLocation] {
if attacker.player == player && attacker.kind == .knight {
return true
}
}
}
}
// Check for rook or queen attack along file or rank.
for vector in Position.rookVectors {
if isAttackedBySlide(location: location,
player: player,
vector: vector,
kinds: Position.pieceKindsWithRookVectors) {
return true
}
}
// Check for bishop or queen attack along diagonals.
for vector in Position.bishopVectors {
if isAttackedBySlide(location: location,
player: player,
vector: vector,
kinds: Position.pieceKindsWithBishopVectors) {
return true
}
}
// Check for attack by king.
for (h, v) in Position.eightDirections {
if let attackerLocation = Location.ifValid(file: file + h, rank: rank + v) {
if let attacker = board[attackerLocation] {
if attacker.player == player && attacker.kind == .king {
return true
}
}
}
}
// Check for attack by pawn.
for (h, v) in Position.pawnCaptureMoves(player: player) {
if let attackerLocation = Location.ifValid(file: file - h, rank: rank - v) {
if let attacker = board[attackerLocation] {
if attacker.player == player && attacker.kind == .pawn {
return true
}
}
}
}
return false
}
private func isAttackedBySlide(location: Location,
player: Player,
vector: (Int, Int),
kinds: [PieceKind]) -> Bool
{
let (h, v) = vector
var file = location.file + h
var rank = location.rank + v
while let attackerLocation = Location.ifValid(file: file, rank: rank) {
if let attacker = board[attackerLocation] {
if attacker.player == player {
return kinds.contains(attacker.kind)
}
return false
}
else {
file = file + h
rank = rank + v
}
}
return false
}
}
| mit | 029a8bcaadf431dbbb53451deeb7f0b6 | 35.136364 | 96 | 0.45952 | 5.054913 | false | false | false | false |
qbalsdon/br.cd | brcd/brcd/ViewController/Controls/UIBarcodeScannerView.swift | 1 | 4101 | //
// UIBarcodeScannerView.swift
// brcd
//
// Created by Quintin Balsdon on 2016/01/30.
// Copyright © 2016 Balsdon. All rights reserved.
//
import UIKit
import AVFoundation
class UIBarcodeScannerView: UIView, AVCaptureMetadataOutputObjectsDelegate {
var view: UIView!
var captureSession: AVCaptureSession!
var previewLayer: AVCaptureVideoPreviewLayer!
var delegate: BarcodeScannerDelegate! = nil
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "UIBarcodeScannerView", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
setupCapture()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
setupCapture()
}
func setupCapture() {
captureSession = AVCaptureSession()
let videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
if delegate != nil {
delegate.failed()
}
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
if delegate != nil {
delegate.failed()
}
return;
}
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypeInterleaved2of5Code,
AVMetadataObjectTypeITF14Code,
AVMetadataObjectTypeDataMatrixCode
]
} else {
delegate.failed()
return
}
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
previewLayer.frame = view.layer.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
view.layer.addSublayer(previewLayer);
captureSession.startRunning();
}
func startRunning() {
if (captureSession?.running == false) {
captureSession.startRunning();
}
}
func stopRunning() {
if (captureSession?.running == true) {
captureSession.stopRunning();
}
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
captureSession.stopRunning()
if let metadataObject = metadataObjects.first {
let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
delegate.barcodeScanned(readableObject.stringValue, type: readableObject.type)
}
}
}
| mit | 052698cc49e0785afda5b622cdf639c2 | 30.538462 | 162 | 0.61561 | 6.288344 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/TextFormatEncoder.swift | 1 | 9863 | // Sources/SwiftProtobuf/TextFormatEncoder.swift - Text format encoding support
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Text format serialization engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiSpace = UInt8(ascii: " ")
private let asciiColon = UInt8(ascii: ":")
private let asciiComma = UInt8(ascii: ",")
private let asciiMinus = UInt8(ascii: "-")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiZero = UInt8(ascii: "0")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiNewline = UInt8(ascii: "\n")
private let asciiUpperA = UInt8(ascii: "A")
private let tabSize = 2
/// TextFormatEncoder has no public members.
internal struct TextFormatEncoder {
private var data = [UInt8]()
private var indentString: [UInt8] = []
var stringResult: String {
get {
return String(bytes: data, encoding: String.Encoding.utf8)!
}
}
internal mutating func append(staticText: StaticString) {
let buff = UnsafeBufferPointer(start: staticText.utf8Start, count: staticText.utf8CodeUnitCount)
data.append(contentsOf: buff)
}
internal mutating func append(name: _NameMap.Name) {
data.append(contentsOf: name.utf8Buffer)
}
private mutating func append(text: String) {
data.append(contentsOf: text.utf8)
}
init() {}
internal mutating func indent() {
data.append(contentsOf: indentString)
}
mutating func emitFieldName(name: UnsafeBufferPointer<UInt8>) {
indent()
data.append(contentsOf: name)
}
mutating func emitFieldName(name: StaticString) {
let buff = UnsafeBufferPointer(start: name.utf8Start, count: name.utf8CodeUnitCount)
emitFieldName(name: buff)
}
mutating func emitExtensionFieldName(name: String) {
indent()
data.append(asciiOpenSquareBracket)
append(text: name)
data.append(asciiCloseSquareBracket)
}
mutating func emitFieldNumber(number: Int) {
indent()
appendUInt(value: UInt64(number))
}
mutating func startRegularField() {
append(staticText: ": ")
}
mutating func endRegularField() {
data.append(asciiNewline)
}
// In Text format, a message-valued field writes the name
// without a trailing colon:
// name_of_field {key: value key2: value2}
mutating func startMessageField() {
append(staticText: " {\n")
for _ in 1...tabSize {
indentString.append(asciiSpace)
}
}
mutating func endMessageField() {
for _ in 1...tabSize {
indentString.remove(at: indentString.count - 1)
}
indent()
append(staticText: "}\n")
}
mutating func startArray() {
data.append(asciiOpenSquareBracket)
}
mutating func arraySeparator() {
append(staticText: ", ")
}
mutating func endArray() {
data.append(asciiCloseSquareBracket)
}
mutating func putEnumValue<E: Enum>(value: E) {
if let name = value.name {
data.append(contentsOf: name.utf8Buffer)
} else {
appendInt(value: Int64(value.rawValue))
}
}
mutating func putFloatValue(value: Float) {
if value.isNaN {
append(staticText: "nan")
} else if !value.isFinite {
if value < 0 {
append(staticText: "-inf")
} else {
append(staticText: "inf")
}
} else {
if let v = Int64(exactly: Double(value)) {
appendInt(value: v)
} else {
let doubleFormatter = DoubleFormatter()
let formatted = doubleFormatter.floatToUtf8(value)
data.append(contentsOf: formatted)
}
}
}
mutating func putDoubleValue(value: Double) {
if value.isNaN {
append(staticText: "nan")
} else if !value.isFinite {
if value < 0 {
append(staticText: "-inf")
} else {
append(staticText: "inf")
}
} else {
if let v = Int64(exactly: value) {
appendInt(value: v)
} else {
let doubleFormatter = DoubleFormatter()
let formatted = doubleFormatter.doubleToUtf8(value)
data.append(contentsOf: formatted)
}
}
}
private mutating func appendUInt(value: UInt64) {
if value >= 1000 {
appendUInt(value: value / 1000)
}
if value >= 100 {
data.append(asciiZero + UInt8((value / 100) % 10))
}
if value >= 10 {
data.append(asciiZero + UInt8((value / 10) % 10))
}
data.append(asciiZero + UInt8(value % 10))
}
private mutating func appendInt(value: Int64) {
if value < 0 {
data.append(asciiMinus)
// This is the twos-complement negation of value,
// computed in a way that won't overflow a 64-bit
// signed integer.
appendUInt(value: 1 + ~UInt64(bitPattern: value))
} else {
appendUInt(value: UInt64(bitPattern: value))
}
}
mutating func putInt64(value: Int64) {
appendInt(value: value)
}
mutating func putUInt64(value: UInt64) {
appendUInt(value: value)
}
mutating func appendUIntHex(value: UInt64, digits: Int) {
if digits == 0 {
append(staticText: "0x")
} else {
appendUIntHex(value: value >> 4, digits: digits - 1)
let d = UInt8(truncatingBitPattern: value % 16)
data.append(d < 10 ? asciiZero + d : asciiUpperA + d - 10)
}
}
mutating func putUInt64Hex(value: UInt64, digits: Int) {
appendUIntHex(value: value, digits: digits)
}
mutating func putBoolValue(value: Bool) {
append(staticText: value ? "true" : "false")
}
mutating func putStringValue(value: String) {
data.append(asciiDoubleQuote)
for c in value.unicodeScalars {
switch c.value {
// Special two-byte escapes
case 8:
append(staticText: "\\b")
case 9:
append(staticText: "\\t")
case 10:
append(staticText: "\\n")
case 11:
append(staticText: "\\v")
case 12:
append(staticText: "\\f")
case 13:
append(staticText: "\\r")
case 34:
append(staticText: "\\\"")
case 92:
append(staticText: "\\\\")
case 0...31, 127: // Octal form for C0 control chars
data.append(asciiBackslash)
data.append(asciiZero + UInt8(c.value / 64))
data.append(asciiZero + UInt8(c.value / 8 % 8))
data.append(asciiZero + UInt8(c.value % 8))
case 0...127: // ASCII
data.append(UInt8(truncatingBitPattern: c.value))
case 0x80...0x7ff:
data.append(0xc0 + UInt8(c.value / 64))
data.append(0x80 + UInt8(c.value % 64))
case 0x800...0xffff:
data.append(0xe0 + UInt8(truncatingBitPattern: c.value >> 12))
data.append(0x80 + UInt8(truncatingBitPattern: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(truncatingBitPattern: c.value & 0x3f))
default:
data.append(0xf0 + UInt8(truncatingBitPattern: c.value >> 18))
data.append(0x80 + UInt8(truncatingBitPattern: (c.value >> 12) & 0x3f))
data.append(0x80 + UInt8(truncatingBitPattern: (c.value >> 6) & 0x3f))
data.append(0x80 + UInt8(truncatingBitPattern: c.value & 0x3f))
}
}
data.append(asciiDoubleQuote)
}
mutating func putBytesValue(value: Data) {
data.append(asciiDoubleQuote)
value.withUnsafeBytes { (p: UnsafePointer<UInt8>) in
for i in 0..<value.count {
let c = p[i]
switch c {
// Special two-byte escapes
case 8:
append(staticText: "\\b")
case 9:
append(staticText: "\\t")
case 10:
append(staticText: "\\n")
case 11:
append(staticText: "\\v")
case 12:
append(staticText: "\\f")
case 13:
append(staticText: "\\r")
case 34:
append(staticText: "\\\"")
case 92:
append(staticText: "\\\\")
case 32...126: // printable ASCII
data.append(c)
default: // Octal form for non-printable chars
data.append(asciiBackslash)
data.append(asciiZero + UInt8(c / 64))
data.append(asciiZero + UInt8(c / 8 % 8))
data.append(asciiZero + UInt8(c % 8))
}
}
}
data.append(asciiDoubleQuote)
}
}
| mit | d243365336a52c1594b1342fb273da66 | 31.876667 | 104 | 0.537463 | 4.481145 | false | false | false | false |
edmoks/RecordBin | RecordBin/Class/Service/AuthService.swift | 1 | 3459 | //
// File.swift
// RecordBin
//
// Created by Eduardo Rangel on 11/10/2017.
// Copyright © 2017 Eduardo Rangel. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class AuthService {
//////////////////////////////////////////////////
// MARK: - Singleton
static let instance = AuthService()
//////////////////////////////////////////////////
// MARK: - Variables
let defaults = UserDefaults.standard
//////////////////////////////////////////////////
// MARK: - Functions
func getIP(completion: @escaping CompletionHandler) {
Alamofire.request(KURLs.IPAPI).responseString { (response) in
if response.result.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.result.error as Any)
}
}
}
func getLukeSkywalker(completion: @escaping CompletionHandler) {
Alamofire.request(KURLs.StarWars.LukeSkywalker).responseJSON { (response) in
if response.result.error == nil {
// Typical JSON Handling in Swift.
// if let json = response.result.value as? Dictionary<String, Any> {
// if let name = json["name"] as? String {
// print(name)
// }
// }
// SwiftyJSON Handling.
guard let data = response.data else {
return
}
let json = JSON(data: data)
print(json["name"].stringValue)
completion(true)
print(response)
} else {
completion(false)
debugPrint(response.result.error as Any)
}
}
}
// func getStores(completion: @escaping CompletionHandler) {
// do {
// if let file = Bundle.main.url(forResource: "Stores", withExtension: "json") {
// let data = try Data(contentsOf: file)
// let json = try JSONSerialization.jsonObject(with: data, options: [])
// if let object = json as? [String: Any] {
// // json is a dictionary
// print(object)
// } else if let object = json as? [Any] {
// // json is an array
// print(object)
// } else {
// print("JSON is invalid")
// }
// } else {
// print("no file")
// }
// } catch {
// print(error.localizedDescription)
// }
// }
func registerUser(email: String, password: String, completion: @escaping CompletionHandler) {
let lowerCaseEmail = email.lowercased()
let body: [String: Any] = [
"email": lowerCaseEmail,
"password": password
]
Alamofire.request(KURLs.Register, method: .post, parameters: body, encoding: JSONEncoding.default, headers: KURLs.Header).responseJSON { (response) in
if response.result.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.result.error as Any)
}
}
}
}
| mit | 6ac1a2034643a0e9b8dbcde64f6810c4 | 29.069565 | 158 | 0.461538 | 5.070381 | false | false | false | false |
rudkx/swift | test/attr/attr_specialize.swift | 1 | 18359 | // RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=verify
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module -define-availability 'SwiftStdlib 5.1:macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0' | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}},
@_specialize(where T == T1) // expected-error{{cannot find type 'T1' in scope}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-warning{{redundant same-type constraint 'T' == 'T'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == S<T>) // expected-error{{same-type constraint 'T' == 'S<T>' is recursive}}
// expected-error@-1 {{cannot build rewrite system for generic signature; concrete nesting limit exceeded}}
// expected-note@-2 {{failed rewrite rule is τ_0_0.[concrete: S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<S<τ_0_0>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] => τ_0_0}}
// expected-error@-3 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-4 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T == Int, U == Int) // expected-error{{cannot find type 'U' in scope}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note {{missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // FIXME e/xpected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}}
// expected-note@-1 {{same-type constraint 'T' == 'NonSub' implied here}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected type}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{cannot find type 'Z' in scope}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{cannot find type 'MyClass' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}}
// expected-note@-2{{same-type constraint 'X' == 'Int' written here}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{cannot find type 'X1' in scope}} expected-error{{cannot find type 'Y1' in scope}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-note{{missing constraint for 'X' in '_specialize' attribute}} expected-note{{missing constraint for 'Y' in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{cannot find type 'exported' in scope}} expected-error{{cannot find type 'kind' in scope}} expected-error{{cannot find type 'partial' in scope}} expected-error{{expected type}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}} expected-note {{use 'T == Int' to require 'T' to be 'Int'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: S1) // expected-error{{type 'T' constrained to non-protocol, non-class type 'S1'}} expected-note {{use 'T == S1' to require 'T' to be 'S1'}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: C1) // expected-error{{only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}} expected-error{{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-note{{missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject)
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}}
// expected-error@-2{{type 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}}
// expected-warning@-3{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-4 {{constraint 'T' : '_Trivial' implied here}}
// expected-note@-5 2{{constraint conflicts with 'T' : '_Trivial(32)'}}
// expected-error@-6 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-7 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial, T: _Trivial(64))
// expected-warning@-1{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-2 1{{constraint 'T' : '_Trivial' implied here}}
@_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject)
// expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}}
// expected-note@-2 1{{constraint 'T' : '_RefCountedObject' implied here}}
@_specialize(where Array<T> == Int) // expected-error{{generic signature requires types 'Array<T>' and 'Int' to be the same}}
// expected-error@-1 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-2 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T.Element == Int) // expected-error{{only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public protocol Proto: class {
}
@_specialize(where T: _RefCountedObject)
// expected-warning@-1 {{redundant constraint 'T' : '_RefCountedObject'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial)
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial' and '_NativeClass'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
@_specialize(where T: _Trivial(64))
// expected-error@-1{{type 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}}
// expected-error@-2 {{too few generic parameters are specified in '_specialize' attribute (got 0, but expected 1)}}
// expected-note@-3 {{missing constraint for 'T' in '_specialize' attribute}}
public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 {
return 44444
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@_specialize(exported: true, where S: _NativeRefCountedObject)
@_specialize(exported: true, where S: _Class)
@_specialize(exported: true, where S: _NativeClass)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few generic parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-note{{missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
public func targetFun<T>(_ t: T) {}
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) {
}
public struct Container {
public func targetFun<T>(_ t: T) {}
}
extension Container {
@_specialize(exported: true, target: targetFun(_:), where T == Int)
public func specifyTargetFunc<T>(_ t: T) { }
@_specialize(exported: true, target: targetFun2(_:), where T == Int) // expected-error{{target function 'targetFun2' could not be found}}
public func specifyTargetFunc2<T>(_ t: T) { }
}
// Make sure we don't complain that 'E' is not explicitly specialized here.
// E becomes concrete via the combination of 'S == Set<String>' and
// 'E == S.Element'.
@_specialize(where S == Set<String>)
public func takesSequenceAndElement<S, E>(_: S, _: E)
where S : Sequence, E == S.Element {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS 11, iOS 13, *; where T == Int)
// CHECK: public func testAvailability<T>(_ t: T)
@_specialize(exported: true, availability: macOS 11, iOS 13, *; where T == Int)
public func testAvailability<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int)
// CHECK: public func testAvailability2<T>(_ t: T)
@_specialize(exported: true, availability: macOS 11, *; where T == Int)
public func testAvailability2<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS, introduced: 11; where T == Int)
// CHECK: public func testAvailability3<T>(_ t: T)
@_specialize(exported: true, availability: macOS, introduced: 11; where T == Int)
public func testAvailability3<T>(_ t: T) {}
// CHECK: @_specialize(exported: true, kind: full, availability: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *; where T == Int)
// CHECK: public func testAvailability4<T>(_ t: T)
@_specialize(exported: true, availability: SwiftStdlib 5.1, *; where T == Int)
public func testAvailability4<T>(_ t: T) {}
| apache-2.0 | f562a82b1de9225058b7a7a3527296cf | 51.595989 | 393 | 0.691763 | 3.621942 | false | false | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Mapping/Serialization/MSCustomEntity+Serialize.swift | 1 | 743 | //
// MSCustomEntity+Serialize.swift
// MoyskladiOSRemapSDK
//
// Created by Антон Ефименко on 05.09.2018.
// Copyright © 2018 Andrey Parshakov. All rights reserved.
//
import Foundation
extension MSCustomEntity {
public func dictionary(metaOnly: Bool) -> Dictionary<String, Any> {
var dict = [String: Any]()
if meta.href.count > 0 {
dict["meta"] = meta.dictionary()
}
guard !metaOnly else { return dict }
dict.merge(id.dictionary())
dict["name"] = name
dict["code"] = code ?? ""
dict["externalCode"] = externalCode ?? ""
dict["description"] = description ?? ""
return dict
}
}
| mit | 79d66c73c132f152298cd9792031a254 | 23.3 | 71 | 0.554184 | 3.983607 | false | false | false | false |
haskellswift/swift-package-manager | Sources/PackageDescription/Target.swift | 2 | 1680 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// The description for an individual target.
public final class Target {
/// The description for an individual target or package dependency.
public enum Dependency {
/// A dependency on a target in the same project.
case Target(name: String)
}
/// The name of the target.
public let name: String
/// The list of dependencies.
public var dependencies: [Dependency]
/// Construct a target.
public init(name: String, dependencies: [Dependency] = []) {
self.name = name
self.dependencies = dependencies
}
}
// MARK: ExpressibleByStringLiteral
extension Target.Dependency : ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self = .Target(name: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = .Target(name: value)
}
public init(stringLiteral value: String) {
self = .Target(name: value)
}
}
// MARK: Equatable
extension Target : Equatable { }
public func ==(lhs: Target, rhs: Target) -> Bool {
return (lhs.name == rhs.name &&
lhs.dependencies == rhs.dependencies)
}
extension Target.Dependency : Equatable { }
public func ==(lhs: Target.Dependency, rhs: Target.Dependency) -> Bool {
switch (lhs, rhs) {
case (.Target(let a), .Target(let b)):
return a == b
}
}
| apache-2.0 | f80a10c157757fb934f118381e39e863 | 26.096774 | 72 | 0.679167 | 4.307692 | false | false | false | false |
AaronMT/firefox-ios | Client/Frontend/Browser/BrowserViewController/BrowserViewController+WebViewDelegates.swift | 4 | 34777 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Shared
import Photos
private let log = Logger.browserLogger
/// List of schemes that are allowed to be opened in new tabs.
private let schemesAllowedToBeOpenedAsPopups = ["http", "https", "javascript", "data", "about"]
extension BrowserViewController: WKUIDelegate {
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
guard let parentTab = tabManager[webView] else { return nil }
guard !navigationAction.isInternalUnprivileged, shouldRequestBeOpenedAsPopup(navigationAction.request) else {
print("Denying popup from request: \(navigationAction.request)")
return nil
}
if let currentTab = tabManager.selectedTab {
screenshotHelper.takeScreenshot(currentTab)
}
guard let bvc = parentTab.browserViewController else { return nil }
// If the page uses `window.open()` or `[target="_blank"]`, open the page in a new tab.
// IMPORTANT!!: WebKit will perform the `URLRequest` automatically!! Attempting to do
// the request here manually leads to incorrect results!!
let newTab = tabManager.addPopupForParentTab(bvc: bvc, parentTab: parentTab, configuration: configuration)
return newTab.webView
}
fileprivate func shouldRequestBeOpenedAsPopup(_ request: URLRequest) -> Bool {
// Treat `window.open("")` the same as `window.open("about:blank")`.
if request.url?.absoluteString.isEmpty ?? false {
return true
}
if let scheme = request.url?.scheme?.lowercased(), schemesAllowedToBeOpenedAsPopups.contains(scheme) {
return true
}
return false
}
fileprivate func shouldDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool {
// Only display a JS Alert if we are selected and there isn't anything being shown
return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil)
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler)
if shouldDisplayJSAlertForWebView(webView) {
present(messageAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(messageAlert)
} else {
// This should never happen since an alert needs to come from a web view but just in case call the handler
// since not calling it will result in a runtime exception.
completionHandler()
}
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler)
if shouldDisplayJSAlertForWebView(webView) {
present(confirmAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(confirmAlert)
} else {
completionHandler(false)
}
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText)
if shouldDisplayJSAlertForWebView(webView) {
present(textInputAlert.alertController(), animated: true, completion: nil)
} else if let promptingTab = tabManager[webView] {
promptingTab.queueJavascriptAlertPrompt(textInputAlert)
} else {
completionHandler(nil)
}
}
func webViewDidClose(_ webView: WKWebView) {
if let tab = tabManager[webView] {
// Need to wait here in case we're waiting for a pending `window.open()`.
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
self.tabManager.removeTabAndUpdateSelectedIndex(tab)
}
}
}
@available(iOS 13.0, *)
func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) {
completionHandler(UIContextMenuConfiguration(identifier: nil, previewProvider: {
guard let url = elementInfo.linkURL, self.profile.prefs.boolForKey(PrefsKeys.ContextMenuShowLinkPreviews) ?? true else { return nil }
let previewViewController = UIViewController()
previewViewController.view.isUserInteractionEnabled = false
let clonedWebView = WKWebView(frame: webView.frame, configuration: webView.configuration)
previewViewController.view.addSubview(clonedWebView)
clonedWebView.snp.makeConstraints { make in
make.edges.equalTo(previewViewController.view)
}
clonedWebView.load(URLRequest(url: url))
return previewViewController
}, actionProvider: { (suggested) -> UIMenu? in
guard let url = elementInfo.linkURL, let currentTab = self.tabManager.selectedTab,
let contextHelper = currentTab.getContentScript(name: ContextMenuHelper.name()) as? ContextMenuHelper,
let elements = contextHelper.elements else { return nil }
let isPrivate = currentTab.isPrivate
let addTab = { (rURL: URL, isPrivate: Bool) in
let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu"])
guard !self.topTabsVisible else {
return
}
var toastLabelText: String
if isPrivate {
toastLabelText = Strings.ContextMenuButtonToastNewPrivateTabOpenedLabelText
} else {
toastLabelText = Strings.ContextMenuButtonToastNewTabOpenedLabelText
}
// We're not showing the top tabs; show a toast to quick switch to the fresh new tab.
let toast = ButtonToast(labelText: toastLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in
if buttonPressed {
self.tabManager.selectTab(tab)
}
})
self.show(toast: toast)
}
let getImageData = { (_ url: URL, success: @escaping (Data) -> Void) in
makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.default).dataTask(with: url) { (data, response, error) in
if let _ = validatedHTTPResponse(response, statusCode: 200..<300), let data = data {
success(data)
}
}.resume()
}
var actions = [UIAction]()
if !isPrivate {
actions.append(UIAction(title: Strings.ContextMenuOpenInNewTab, image: UIImage.templateImageNamed("menu-NewTab"), identifier: UIAction.Identifier(rawValue: "linkContextMenu.openInNewTab")) {_ in
addTab(url, false)
})
}
actions.append(UIAction(title: Strings.ContextMenuOpenInNewPrivateTab, image: UIImage.templateImageNamed("menu-NewPrivateTab"), identifier: UIAction.Identifier("linkContextMenu.openInNewPrivateTab")) { _ in
addTab(url, true)
})
actions.append(UIAction(title: Strings.ContextMenuBookmarkLink, image: UIImage.templateImageNamed("menu-Bookmark"), identifier: UIAction.Identifier("linkContextMenu.bookmarkLink")) { _ in
self.addBookmark(url: url.absoluteString, title: elements.title)
SimpleToast().showAlertWithText(Strings.AppMenuAddBookmarkConfirmMessage, bottomContainer: self.webViewContainer)
TelemetryWrapper.recordEvent(category: .action, method: .add, object: .bookmark, value: .contextMenu)
})
actions.append(UIAction(title: Strings.ContextMenuDownloadLink, image: UIImage.templateImageNamed("menu-panel-Downloads"), identifier: UIAction.Identifier("linkContextMenu.download")) {_ in
self.pendingDownloadWebView = currentTab.webView
DownloadContentScript.requestDownload(url: url, tab: currentTab)
})
actions.append(UIAction(title: Strings.ContextMenuCopyLink, image: UIImage.templateImageNamed("menu-Copy-Link"), identifier: UIAction.Identifier("linkContextMenu.copyLink")) { _ in
UIPasteboard.general.url = url
})
actions.append(UIAction(title: Strings.ContextMenuShareLink, image: UIImage.templateImageNamed("action_share"), identifier: UIAction.Identifier("linkContextMenu.share")) { _ in
guard let tab = self.tabManager[webView], let helper = tab.getContentScript(name: ContextMenuHelper.name()) as? ContextMenuHelper else { return }
// This is only used on ipad for positioning the popover. On iPhone it is an action sheet.
let p = webView.convert(helper.touchPoint, to: self.view)
self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: p, size: CGSize(width: 10, height: 10)), arrowDirection: .unknown)
})
if let url = elements.image {
let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus()
actions.append(UIAction(title: Strings.ContextMenuSaveImage, identifier: UIAction.Identifier("linkContextMenu.saveImage")) { _ in
let handlePhotoLibraryAuthorized = {
DispatchQueue.main.async {
getImageData(url) { data in
PHPhotoLibrary.shared().performChanges({
PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: nil)
})
}
}
}
let handlePhotoLibraryDenied = {
DispatchQueue.main.async {
let accessDenied = UIAlertController(title: Strings.PhotoLibraryFirefoxWouldLikeAccessTitle, message: Strings.PhotoLibraryFirefoxWouldLikeAccessMessage, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil)
accessDenied.addAction(dismissAction)
let settingsAction = UIAlertAction(title: Strings.OpenSettingsString, style: .default ) { _ in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:])
}
accessDenied.addAction(settingsAction)
self.present(accessDenied, animated: true, completion: nil)
}
}
if photoAuthorizeStatus == .notDetermined {
PHPhotoLibrary.requestAuthorization({ status in
guard status == .authorized else {
handlePhotoLibraryDenied()
return
}
handlePhotoLibraryAuthorized()
})
} else if photoAuthorizeStatus == .authorized {
handlePhotoLibraryAuthorized()
} else {
handlePhotoLibraryDenied()
}
})
actions.append(UIAction(title: Strings.ContextMenuCopyImage, identifier: UIAction.Identifier("linkContextMenu.copyImage")) { _ in
// put the actual image on the clipboard
// do this asynchronously just in case we're in a low bandwidth situation
let pasteboard = UIPasteboard.general
pasteboard.url = url as URL
let changeCount = pasteboard.changeCount
let application = UIApplication.shared
var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)
taskId = application.beginBackgroundTask (expirationHandler: {
application.endBackgroundTask(taskId)
})
makeURLSession(userAgent: UserAgent.fxaUserAgent, configuration: URLSessionConfiguration.default).dataTask(with: url) { (data, response, error) in
guard let _ = validatedHTTPResponse(response, statusCode: 200..<300) else {
application.endBackgroundTask(taskId)
return
}
// Only set the image onto the pasteboard if the pasteboard hasn't changed since
// fetching the image; otherwise, in low-bandwidth situations,
// we might be overwriting something that the user has subsequently added.
if changeCount == pasteboard.changeCount, let imageData = data, error == nil {
pasteboard.addImageWithData(imageData, forURL: url)
}
application.endBackgroundTask(taskId)
}.resume()
})
actions.append(UIAction(title: Strings.ContextMenuCopyImageLink, identifier: UIAction.Identifier("linkContextMenu.copyImageLink")) { _ in
UIPasteboard.general.url = url as URL
})
}
return UIMenu(title: url.absoluteString, children: actions)
}))
}
}
extension WKNavigationAction {
/// Allow local requests only if the request is privileged.
var isInternalUnprivileged: Bool {
guard let url = request.url else {
return true
}
if let url = InternalURL(url) {
return !url.isAuthorized
} else {
return false
}
}
}
extension BrowserViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if tabManager.selectedTab?.webView !== webView {
return
}
updateFindInPageVisibility(visible: false)
// If we are going to navigate to a new page, hide the reader mode button. Unless we
// are going to a about:reader page. Then we keep it on screen: it will change status
// (orange color) as soon as the page has loaded.
if let url = webView.url {
if !url.isReaderModeURL {
urlBar.updateReaderModeState(ReaderModeState.unavailable)
hideReaderModeBar(animated: false)
}
}
}
// Recognize an Apple Maps URL. This will trigger the native app. But only if a search query is present. Otherwise
// it could just be a visit to a regular page on maps.apple.com.
fileprivate func isAppleMapsURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" {
if url.host == "maps.apple.com" && url.query != nil {
return true
}
}
return false
}
// Recognize a iTunes Store URL. These all trigger the native apps. Note that appstore.com and phobos.apple.com
// used to be in this list. I have removed them because they now redirect to itunes.apple.com. If we special case
// them then iOS will actually first open Safari, which then redirects to the app store. This works but it will
// leave a 'Back to Safari' button in the status bar, which we do not want.
fileprivate func isStoreURL(_ url: URL) -> Bool {
if url.scheme == "http" || url.scheme == "https" || url.scheme == "itms-apps" {
if url.host == "itunes.apple.com" {
return true
}
}
return false
}
// Use for sms and mailto links, which do not show a confirmation before opening.
fileprivate func showSnackbar(forExternalUrl url: URL, tab: Tab, completion: @escaping (Bool) -> ()) {
let snackBar = TimerSnackBar(text: Strings.ExternalLinkGenericConfirmation + "\n\(url.absoluteString)", img: nil)
let ok = SnackButton(title: Strings.OKString, accessibilityIdentifier: "AppOpenExternal.button.ok") { bar in
tab.removeSnackbar(bar)
completion(true)
}
let cancel = SnackButton(title: Strings.CancelString, accessibilityIdentifier: "AppOpenExternal.button.cancel") { bar in
tab.removeSnackbar(bar)
completion(false)
}
snackBar.addButton(ok)
snackBar.addButton(cancel)
tab.addSnackbar(snackBar)
}
// This is the place where we decide what to do with a new navigation action. There are a number of special schemes
// and http(s) urls that need to be handled in a different way. All the logic for that is inside this delegate
// method.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url, let tab = tabManager[webView] else {
decisionHandler(.cancel)
return
}
if InternalURL.isValid(url: url) {
if navigationAction.navigationType != .backForward, navigationAction.isInternalUnprivileged {
log.warning("Denying unprivileged request: \(navigationAction.request)")
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
return
}
// First special case are some schemes that are about Calling. We prompt the user to confirm this action. This
// gives us the exact same behaviour as Safari.
if ["sms", "tel", "facetime", "facetime-audio"].contains(url.scheme) {
if url.scheme == "sms" { // All the other types show a native prompt
showSnackbar(forExternalUrl: url, tab: tab) { isOk in
guard isOk else { return }
UIApplication.shared.open(url, options: [:])
}
} else {
UIApplication.shared.open(url, options: [:])
}
decisionHandler(.cancel)
return
}
if url.scheme == "about" {
decisionHandler(.allow)
return
}
// Disabled due to https://bugzilla.mozilla.org/show_bug.cgi?id=1588928
// if url.scheme == "javascript", navigationAction.request.isPrivileged {
// decisionHandler(.cancel)
// if let javaScriptString = url.absoluteString.replaceFirstOccurrence(of: "javascript:", with: "").removingPercentEncoding {
// webView.evaluateJavaScript(javaScriptString)
// }
// return
// }
// Second special case are a set of URLs that look like regular http links, but should be handed over to iOS
// instead of being loaded in the webview. Note that there is no point in calling canOpenURL() here, because
// iOS will always say yes.
if isAppleMapsURL(url) {
UIApplication.shared.open(url, options: [:])
decisionHandler(.cancel)
return
}
if isStoreURL(url) {
decisionHandler(.cancel)
// Make sure to wait longer than delaySelectingNewPopupTab to ensure selectedTab is correct
DispatchQueue.main.asyncAfter(deadline: .now() + tabManager.delaySelectingNewPopupTab + 0.1) {
guard let tab = self.tabManager.selectedTab else { return }
if tab.bars.isEmpty { // i.e. no snackbars are showing
TimerSnackBar.showAppStoreConfirmationBar(forTab: tab, appStoreURL: url) { _ in
// If a new window was opened for this URL (it will have no history), close it.
if tab.historyList.isEmpty {
self.tabManager.removeTabAndUpdateSelectedIndex(tab)
}
}
}
}
return
}
// Handles custom mailto URL schemes.
if url.scheme == "mailto" {
showSnackbar(forExternalUrl: url, tab: tab) { isOk in
guard isOk else { return }
if let mailToMetadata = url.mailToMetadata(), let mailScheme = self.profile.prefs.stringForKey(PrefsKeys.KeyMailToOption), mailScheme != "mailto" {
self.mailtoLinkHandler.launchMailClientForScheme(mailScheme, metadata: mailToMetadata, defaultMailtoURL: url)
} else {
UIApplication.shared.open(url, options: [:])
}
LeanPlumClient.shared.track(event: .openedMailtoLink)
}
decisionHandler(.cancel)
return
}
// https://blog.mozilla.org/security/2017/11/27/blocking-top-level-navigations-data-urls-firefox-59/
if url.scheme == "data" {
let url = url.absoluteString
// Allow certain image types
if url.hasPrefix("data:image/") && !url.hasPrefix("data:image/svg+xml") {
decisionHandler(.allow)
return
}
// Allow video, and certain application types
if url.hasPrefix("data:video/") || url.hasPrefix("data:application/pdf") || url.hasPrefix("data:application/json") {
decisionHandler(.allow)
return
}
// Allow plain text types.
// Note the format of data URLs is `data:[<media type>][;base64],<data>` with empty <media type> indicating plain text.
if url.hasPrefix("data:;base64,") || url.hasPrefix("data:,") || url.hasPrefix("data:text/plain,") || url.hasPrefix("data:text/plain;") {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
return
}
// This is the normal case, opening a http or https url, which we handle by loading them in this WKWebView. We
// always allow this. Additionally, data URIs are also handled just like normal web pages.
if ["http", "https", "blob", "file"].contains(url.scheme) {
if navigationAction.targetFrame?.isMainFrame ?? false {
tab.changedUserAgent = Tab.ChangeUserAgent.contains(url: url)
}
pendingRequests[url.absoluteString] = navigationAction.request
if tab.changedUserAgent {
let platformSpecificUserAgent = UserAgent.oppositeUserAgent(domain: url.baseDomain ?? "")
webView.customUserAgent = platformSpecificUserAgent
} else {
webView.customUserAgent = UserAgent.getUserAgent(domain: url.baseDomain ?? "")
}
decisionHandler(.allow)
return
}
if !(url.scheme?.contains("firefox") ?? true) {
showSnackbar(forExternalUrl: url, tab: tab) { isOk in
guard isOk else { return }
UIApplication.shared.open(url, options: [:]) { openedURL in
// Do not show error message for JS navigated links or redirect as it's not the result of a user action.
if !openedURL, navigationAction.navigationType == .linkActivated {
let alert = UIAlertController(title: Strings.UnableToOpenURLErrorTitle, message: Strings.UnableToOpenURLError, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Strings.OKString, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
decisionHandler(.cancel)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let response = navigationResponse.response
let responseURL = response.url
var request: URLRequest?
if let url = responseURL {
request = pendingRequests.removeValue(forKey: url.absoluteString)
}
// We can only show this content in the web view if this web view is not pending
// download via the context menu.
let canShowInWebView = navigationResponse.canShowMIMEType && (webView != pendingDownloadWebView)
let forceDownload = webView == pendingDownloadWebView
// Check if this response should be handed off to Passbook.
if let passbookHelper = OpenPassBookHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Clear the network activity indicator since our helper is handling the request.
UIApplication.shared.isNetworkActivityIndicatorVisible = false
// Open our helper and cancel this response from the webview.
passbookHelper.open()
decisionHandler(.cancel)
return
}
if #available(iOS 12.0, *) {
// Check if this response should be displayed in a QuickLook for USDZ files.
if let previewHelper = OpenQLPreviewHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Certain files are too large to download before the preview presents, block and use a temporary document instead
if let tab = tabManager[webView] {
if navigationResponse.isForMainFrame, response.mimeType != MIMEType.HTML, let request = request {
tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request)
previewHelper.url = tab.temporaryDocument!.getURL().value as NSURL
// Open our helper and cancel this response from the webview.
previewHelper.open()
decisionHandler(.cancel)
return
} else {
tab.temporaryDocument = nil
}
}
// We don't have a temporary document, fallthrough
}
}
// Check if this response should be downloaded.
if let downloadHelper = DownloadHelper(request: request, response: response, canShowInWebView: canShowInWebView, forceDownload: forceDownload, browserViewController: self) {
// Clear the network activity indicator since our helper is handling the request.
UIApplication.shared.isNetworkActivityIndicatorVisible = false
// Clear the pending download web view so that subsequent navigations from the same
// web view don't invoke another download.
pendingDownloadWebView = nil
// Open our helper and cancel this response from the webview.
downloadHelper.open()
decisionHandler(.cancel)
return
}
// If the content type is not HTML, create a temporary document so it can be downloaded and
// shared to external applications later. Otherwise, clear the old temporary document.
// NOTE: This should only happen if the request/response came from the main frame, otherwise
// we may end up overriding the "Share Page With..." action to share a temp file that is not
// representative of the contents of the web view.
if navigationResponse.isForMainFrame, let tab = tabManager[webView] {
if response.mimeType != MIMEType.HTML, let request = request {
tab.temporaryDocument = TemporaryDocument(preflightResponse: response, request: request)
} else {
tab.temporaryDocument = nil
}
tab.mimeType = response.mimeType
}
// If none of our helpers are responsible for handling this response,
// just let the webview handle it as normal.
decisionHandler(.allow)
}
/// Invoked when an error occurs while starting to load data for the main frame.
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
// Ignore the "Frame load interrupted" error that is triggered when we cancel a request
// to open an external application and hand it over to UIApplication.openURL(). The result
// will be that we switch to the external app, for example the app store, while keeping the
// original web page in the tab instead of replacing it with an error page.
let error = error as NSError
if error.domain == "WebKitErrorDomain" && error.code == 102 {
return
}
if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) {
return
}
if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) {
if let tab = tabManager[webView], tab === tabManager.selectedTab {
urlBar.currentURL = tab.url?.displayURL
}
return
}
if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL {
ErrorPageHelper(certStore: profile.certStore).loadPage(error, forUrl: url, inWebView: webView)
}
}
fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool {
if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" {
print("WebContent process has crashed. Trying to reload to restart it.")
webView.reload()
return true
}
return false
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// If this is a certificate challenge, see if the certificate has previously been
// accepted by the user.
let origin = "\(challenge.protectionSpace.host):\(challenge.protectionSpace.port)"
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let trust = challenge.protectionSpace.serverTrust,
let cert = SecTrustGetCertificateAtIndex(trust, 0), profile.certStore.containsCertificate(cert, forOrigin: origin) {
completionHandler(.useCredential, URLCredential(trust: trust))
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPDigest ||
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM,
let tab = tabManager[webView] else {
completionHandler(.performDefaultHandling, nil)
return
}
// If this is a request to our local web server, use our private credentials.
if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) {
completionHandler(.useCredential, WebServer.sharedInstance.credentials)
return
}
// The challenge may come from a background tab, so ensure it's the one visible.
tabManager.selectTab(tab)
let loginsHelper = tab.getContentScript(name: LoginsHelper.name()) as? LoginsHelper
Authenticator.handleAuthRequest(self, challenge: challenge, loginsHelper: loginsHelper).uponQueue(.main) { res in
if let credentials = res.successValue {
completionHandler(.useCredential, credentials.credentials)
} else {
completionHandler(.rejectProtectionSpace, nil)
}
}
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard let tab = tabManager[webView] else { return }
tab.url = webView.url
// When tab url changes after web content starts loading on the page
// We notify the contect blocker change so that content blocker status can be correctly shown on beside the URL bar
tab.contentBlocker?.notifyContentBlockingChanged()
self.scrollController.resetZoomState()
if tabManager.selectedTab === tab {
updateUIForReaderHomeStateForTab(tab)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if let tab = tabManager[webView] {
navigateInTab(tab: tab, to: navigation)
// If this tab had previously crashed, wait 5 seconds before resetting
// the consecutive crash counter. This allows a successful webpage load
// without a crash to reset the consecutive crash counter in the event
// that the tab begins crashing again in the future.
if tab.consecutiveCrashes > 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) {
if tab.consecutiveCrashes > 0 {
tab.consecutiveCrashes = 0
}
}
}
}
}
}
| mpl-2.0 | 7bdf918f621b6d33bc2f7b1f7872269a | 49.328509 | 218 | 0.6211 | 5.596556 | false | false | false | false |
OSzhou/MyTestDemo | PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-Net.git-3268755499654502659/Sources/NetEvent.swift | 1 | 11721 | //
// NetEvent.swift
// PerfectLib
//
// Created by Kyle Jessup on 2016-04-04.
// Copyright © 2016 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 PerfectThread
#if os(Linux)
import SwiftGlibc
import LinuxBridge
private let FILT_READ = EPOLLIN.rawValue
private let FILT_WRITE = EPOLLOUT.rawValue
private let FILT_TIMER = EPOLLWAKEUP.rawValue // used as marker, not actually passed into epoll
private let ERROR = EPOLLERR.rawValue
private let FLAG_NONE = 0
#else
import Darwin
private let FILT_READ = EVFILT_READ
private let FILT_WRITE = EVFILT_WRITE
private let FILT_TIMER = EVFILT_TIMER
private let ERROR = EV_ERROR
private let FLAG_NONE = KEVENT_FLAG_NONE
#endif
func logTerminal(message: String) -> Never {
print(message)
exit(-1)
}
public class NetEvent {
public enum Filter {
case none, error(Int32), read, write, timer
#if os(Linux)
var epollEvent: UInt32 {
switch self {
case .read:
return EPOLLIN.rawValue
case .write:
return EPOLLOUT.rawValue
default:
return 0
}
}
#else
var kqueueFilter: Int16 {
switch self {
case .read:
return Int16(EVFILT_READ)
case .write:
return Int16(EVFILT_WRITE)
default:
return 0
}
}
#endif
}
public typealias EventCallback = (SocketType, Filter) -> ()
private static let emptyCallback: EventCallback = { _, _ in }
#if os(Linux)
private typealias event = epoll_event
#else
private typealias event = kevent
#endif
private static let debug = false
private struct QueuedSocket {
let socket: SocketType
let what: Filter
let timeoutSeconds: Double
let callback: EventCallback
let associated: SocketType // used for epoll
}
private static var staticEvent: NetEvent!
private let kq: Int32
private let lock = Threading.Lock()
private var queuedSockets = [SocketType:QueuedSocket]()
private var numEvents = 64
private var evlist: UnsafeMutablePointer<event>
private static var initOnce: Bool = {
NetEvent.staticEvent = NetEvent()
NetEvent.staticEvent.runLoop()
return true
}()
public static let noTimeout = Threading.noTimeout
private init() {
var sa = sigaction()
#if os(Linux)
self.kq = epoll_create(0xFEC7)
sa.__sigaction_handler.sa_handler = SIG_IGN
#else
self.kq = kqueue()
sa.__sigaction_u.__sa_handler = SIG_IGN
#endif
sa.sa_flags = 0
sigaction(SIGPIPE, &sa, nil)
var rlmt = rlimit()
#if os(Linux)
getrlimit(Int32(RLIMIT_NOFILE.rawValue), &rlmt)
rlmt.rlim_cur = rlmt.rlim_max
setrlimit(Int32(RLIMIT_NOFILE.rawValue), &rlmt)
#else
getrlimit(RLIMIT_NOFILE, &rlmt)
rlmt.rlim_cur = rlim_t(OPEN_MAX)
setrlimit(RLIMIT_NOFILE, &rlmt)
#endif
guard self.kq != -1 else {
logTerminal(message: "Unable to initialize event listener.")
}
self.evlist = UnsafeMutablePointer<event>.allocate(capacity: self.numEvents)
memset(self.evlist, 0, MemoryLayout<event>.size * self.numEvents)
}
public static func initialize() {
_ = NetEvent.initOnce
}
private func runLoop() {
let q = Threading.getQueue(name: "NetEvent", type: .serial)
q.dispatch {
while true {
#if os(Linux)
var nev = Int(epoll_wait(self.kq, self.evlist, Int32(self.numEvents), -1))
#else
var nev = Int(kevent(self.kq, nil, 0, self.evlist, Int32(self.numEvents), nil))
#endif
if nev == -1 {
if errno == EINTR {
nev = 0
} else {
logTerminal(message: "event returned less than zero \(nev) \(errno).")
}
}
// process results
do {
let _ = self.lock.lock()
defer { let _ = self.lock.unlock() }
if NetEvent.debug {
print("event wait returned \(nev)")
}
for n in 0..<nev {
let evt = self.evlist[n]
#if os(Linux)
let sock = SocketType(evt.data.fd)
#else
let sock = SocketType(evt.ident)
#endif
guard let qitm = self.queuedSockets.removeValue(forKey: sock) else {
if NetEvent.debug {
#if os(Linux)
print("event socket not found \(sock) \(evt.events)")
#else
print("event socket not found \(sock) \(evt.filter)")
#endif
}
continue
}
let qitmIsTimeout = qitm.timeoutSeconds > NetEvent.noTimeout
#if os(Linux)
var filter = Filter.none
if (evt.events & EPOLLERR.rawValue) != 0 {
var errData = Int32(0)
var errLen = socklen_t(MemoryLayout<Int32>.size)
getsockopt(sock, SOL_SOCKET, SO_ERROR, &errData, &errLen)
filter = .error(errData)
} else if (evt.events & EPOLLIN.rawValue) != 0 {
if qitmIsTimeout {
// this is a timeout
filter = .timer
} else {
filter = .read
}
} else if (evt.events & EPOLLOUT.rawValue) != 0 {
filter = .write
}
if NetEvent.debug {
print("event rcv \(sock) \(filter) \(evt.events)")
}
#else
var filter = Filter.none
if evt.filter == Int16(EVFILT_TIMER) {
filter = .timer
} else if evt.filter == Int16(EV_ERROR) {
filter = .error(Int32(evt.data))
} else if evt.filter == Int16(EVFILT_READ) {
filter = .read
} else if evt.filter == Int16(EVFILT_WRITE) {
filter = .write
}
if NetEvent.debug {
print("event rcv \(sock) \(filter) \(evt.data)")
}
#endif
#if os(Linux)
epoll_ctl(self.kq, EPOLL_CTL_DEL, sock, nil)
if qitm.associated != invalidSocket {
epoll_ctl(self.kq, EPOLL_CTL_DEL, qitm.associated, nil)
self.queuedSockets.removeValue(forKey: qitm.associated)
if qitmIsTimeout {
close(sock)
} else {
close(qitm.associated)
}
}
qitm.callback(qitmIsTimeout ? qitm.associated : sock, filter)
#else
if qitmIsTimeout {
// need to either remove the timer or the failed event
// this could be optimised to do all removes at once
var tmout = timespec(tv_sec: 0, tv_nsec: 0)
if case .timer = filter {
if NetEvent.debug {
print("event del \(sock) \(qitm.what)")
}
var kvt = event(ident: UInt(sock), filter: qitm.what.kqueueFilter, flags: UInt16(EV_DELETE), fflags: 0, data: 0, udata: nil)
kevent(self.kq, &kvt, 1, nil, 0, &tmout)
} else {
if NetEvent.debug {
print("event del \(sock) EVFILT_TIMER")
}
var kvt = event(ident: UInt(sock), filter: Int16(EVFILT_TIMER), flags: UInt16(EV_DELETE), fflags: 0, data: 0, udata: nil)
kevent(self.kq, &kvt, 1, nil, 0, &tmout)
}
}
qitm.callback(sock, filter)
#endif
}
}
}
}
}
// socket can only be queued with one callback at a time
public static func add(socket newSocket: SocketType, what: Filter, timeoutSeconds: Double, callback: @escaping EventCallback) {
NetEvent.initialize()
let threadingCallback: EventCallback = {
s, f in
Threading.dispatch {
callback(s, f)
}
}
if let n = NetEvent.staticEvent {
let _ = n.lock.lock()
defer { let _ = n.lock.unlock() }
#if os(Linux)
var associated = invalidSocket
if timeoutSeconds > NetEvent.noTimeout {
associated = timerfd_create(CLOCK_MONOTONIC, Int32(TFD_NONBLOCK))
var timerspec = itimerspec()
let waitMillis = Int(timeoutSeconds * 1000.0)
timerspec.it_value.tv_sec = waitMillis / 1000
timerspec.it_value.tv_nsec = (waitMillis - (timerspec.it_value.tv_sec * 1000)) * 1000000
timerspec.it_interval.tv_sec = 0
timerspec.it_interval.tv_nsec = 0
timerfd_settime(associated, 0, &timerspec, nil)
var evt = event()
evt.events = Filter.read.epollEvent | EPOLLONESHOT.rawValue | EPOLLET.rawValue
evt.data.fd = associated
n.queuedSockets[associated] = QueuedSocket(socket: associated, what: .read, timeoutSeconds: timeoutSeconds, callback: threadingCallback, associated: newSocket)
epoll_ctl(n.kq, EPOLL_CTL_ADD, associated, &evt)
if NetEvent.debug {
print("event add \(associated) TIMER for \(newSocket)")
}
}
var evt = event()
evt.events = what.epollEvent | EPOLLONESHOT.rawValue | EPOLLET.rawValue
evt.data.fd = newSocket
n.queuedSockets[newSocket] = QueuedSocket(socket: newSocket, what: what, timeoutSeconds: NetEvent.noTimeout, callback: threadingCallback, associated: associated)
epoll_ctl(n.kq, EPOLL_CTL_ADD, newSocket, &evt)
if NetEvent.debug {
print("event add \(newSocket) \(what) \(what.epollEvent)")
}
// print("event add \(socket) \(evt.events)")
#else
n.queuedSockets[newSocket] = QueuedSocket(socket: newSocket, what: what, timeoutSeconds: timeoutSeconds, callback: threadingCallback, associated: invalidSocket)
var tmout = timespec(tv_sec: 0, tv_nsec: 0)
if timeoutSeconds > noTimeout {
var kvt = event(ident: UInt(newSocket), filter: Int16(EVFILT_TIMER), flags: UInt16(EV_ADD | EV_ENABLE | EV_ONESHOT), fflags: 0, data: Int(timeoutSeconds * 1000), udata: nil)
kevent(n.kq, &kvt, 1, nil, 0, &tmout)
if NetEvent.debug {
print("event add \(newSocket) EVFILT_TIMER")
}
}
var kvt = event(ident: UInt(newSocket), filter: what.kqueueFilter, flags: UInt16(EV_ADD | EV_ENABLE | EV_ONESHOT), fflags: 0, data: 0, udata: nil)
kevent(n.kq, &kvt, 1, nil, 0, &tmout)
if NetEvent.debug {
print("event add \(newSocket) \(what) \(what.kqueueFilter)")
}
#endif
}
}
public static func remove(socket oldSocket: SocketType) {
if let n = NetEvent.staticEvent {
let _ = n.lock.lock()
defer { let _ = n.lock.unlock() }
if let old = n.queuedSockets[oldSocket] {
#if os(Linux)
if old.associated != invalidSocket {
epoll_ctl(n.kq, EPOLL_CTL_DEL, old.associated, nil)
close(old.associated)
n.queuedSockets.removeValue(forKey: old.associated)
}
epoll_ctl(n.kq, EPOLL_CTL_DEL, oldSocket, nil)
#else
// ensure any associate timer is deleted
// these two calls could be conglomerated but would require allocation. revisit
var kvt = event(ident: UInt(oldSocket), filter: old.what.kqueueFilter, flags: UInt16(EV_DELETE), fflags: 0, data: 0, udata: nil)
var tmout = timespec(tv_sec: 0, tv_nsec: 0)
kevent(n.kq, &kvt, 1, nil, 0, &tmout)
if old.timeoutSeconds > noTimeout {
kvt = event(ident: UInt(oldSocket), filter: Int16(EVFILT_TIMER), flags: UInt16(EV_DELETE), fflags: 0, data: 0, udata: nil)
kevent(n.kq, &kvt, 1, nil, 0, &tmout)
}
#endif
n.queuedSockets.removeValue(forKey: oldSocket)
}
}
}
}
| apache-2.0 | 36ec014b41b54848c765b106c5e90e1a | 30.087533 | 189 | 0.590444 | 3.401045 | false | false | false | false |
335g/TwitterAPIKit | Sources/Models/Places.swift | 1 | 2114 | //
// Places.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/05.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
public struct Places {
public let attributes: [String: AnyObject]
public let boundingBox: BoundingBox
public let country: String
public let countryCode: String
public let fullName: String
public let id: String
public let name: String
public let placeType: String
public let url: String
public init?(dictionary _dictionary: [String: AnyObject]?){
guard let dictionary = _dictionary else {
return nil
}
guard let
attributes = dictionary["attributes"] as? [String: AnyObject],
boundingBox = BoundingBox(dictionary: dictionary["bounding_box"] as? [String: AnyObject]),
country = dictionary["country"] as? String,
countryCode = dictionary["country_code"] as? String,
fullName = dictionary["full_name"] as? String,
id = dictionary["id"] as? String,
name = dictionary["name"] as? String,
placeType = dictionary["place_type"] as? String,
url = dictionary["url"] as? String else {
return nil
}
self.attributes = attributes
self.boundingBox = boundingBox
self.country = country
self.countryCode = countryCode
self.fullName = fullName
self.id = id
self.name = name
self.placeType = placeType
self.url = url
}
}
public struct BoundingBox {
public let coordinates: [[[Float]]]
public let type: String
public init?(dictionary _dictionary: [String: AnyObject]?){
guard let dictionary = _dictionary else {
return nil
}
guard let
coordinates = dictionary["coordinates"] as? [[[Float]]],
type = dictionary["type"] as? String else {
return nil
}
self.coordinates = coordinates
self.type = type
}
} | mit | 0ce622ad39b1afe89bf7f3a9051501d2 | 28.333333 | 102 | 0.580294 | 4.955399 | false | false | false | false |
things-nyc/mapthethings-ios | MapTheThings/Transmission.swift | 1 | 11942 | //
// Transmission.swift
// MapTheThings
//
// Created by Frank on 2017/1/1.
// Copyright © 2017 The Things Network New York. All rights reserved.
//
import CoreData
import Foundation
import MapKit
import Alamofire
import PromiseKit
import ReactiveSwift
open class Transmission: NSManagedObject {
@NSManaged var created: Date
@NSManaged var latitude: Double
@NSManaged var longitude: Double
@NSManaged var altitude: Double
@NSManaged var packet: Data?
// When node reports transmission, store seq_no
@NSManaged var dev_eui: String
@NSManaged var seq_no: NSNumber?
// Date transmission was stored at server
@NSManaged var synced: Date?
static var syncWorkDisposer: Disposable?
static var syncDisposer: Disposable?
static var recordWorkDisposer: Disposable?
static var recordDisposer: Disposable?
override open func awakeFromInsert() {
super.awakeFromInsert()
created = Date()
}
open static func create(
_ dataController: DataController,
latitude: Double, longitude: Double, altitude: Double,
packet: Data, device: UUID
) throws -> Transmission {
return try dataController.performAndWaitInContext() { moc in
let tx = NSEntityDescription.insertNewObject(forEntityName: "Transmission", into: moc) as! Transmission
tx.latitude = latitude
tx.longitude = longitude
tx.altitude = altitude
tx.packet = packet
tx.dev_eui = device.uuidString
tx.seq_no = nil
try moc.save()
return tx
}
}
open static func loadTransmissions(_ data: DataController) {
// NOTE: The following code represents a pattern regarding idempotency of work
// that is emerging in the AppState logic. I expect I'll add some code to
// explicitly support the pattern when I get a chance.
// Recognize that there is work to do and flag that it should happen
self.syncWorkDisposer = appStateObservable.observeValues { (_, new) in
if new.authState != nil,
(!new.syncState.syncWorking
&& new.syncState.syncPendingCount>0) {
// Don't just start async work here. There's a chance with
// multiple enqueued updates to AppState that this method will be called
// many times in the same state of needing to start work. We wouldn't want to
// start doing the same work every time.
updateAppState({ (old) -> AppState in
var state = old
state.syncState.syncWorking = true
return state
})
}
}
// Recognize that the work flag went up and do the work.
self.syncDisposer = appStateObservable.observeValues { signal in
if (!signal.old.syncState.syncWorking && signal.new.syncState.syncWorking) {
//debugPrint("Sync one: \(signal.new.syncState)")
syncOneTransmission(data, host: signal.new.host, authorization: signal.new.authState!)
}
}
// Recognize that there is work to do and flag that it should happen
self.recordWorkDisposer = appStateObservable.observeValues { signal in
if (!signal.new.syncState.recordWorking
&& signal.new.syncState.recordLoraToObject.count>0) {
updateAppState({ (old) -> AppState in
var state = old
state.syncState.recordWorking = true
return state
})
}
}
// Recognize that the work flag went up and do the work.
self.recordDisposer = appStateObservable.observeValues { signal in
if (!signal.old.syncState.recordWorking && signal.new.syncState.recordWorking) {
//debugPrint("Record one: \(signal.new.syncState)")
recordOneLoraSeqNo(data, update: signal.new.syncState.recordLoraToObject)
}
}
data.performInContext() { moc in
do {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Transmission")
let calendar = Calendar.autoupdatingCurrent
let now = Date()
if let earlier = (calendar as NSCalendar).date(byAdding: .hour, value: -8, to: now, options: []) {
fetch.predicate = NSPredicate(format: "created > %@", earlier as CVarArg)
let transmissions = try moc.fetch(fetch) as! [Transmission]
let samples = transmissions.map { (tx) in
return TransSample(location: CLLocationCoordinate2D(latitude: tx.latitude, longitude: tx.longitude), altitude: tx.altitude, timestamp: tx.created,
device: nil, ble_seq: nil, // Not live transmission, so nil OK
lora_seq: tx.seq_no?.uint32Value, objectID: nil)
}
updateAppState({ (old) -> AppState in
var state = old
state.map.transmissions = samples
return state
})
}
fetch.predicate = NSPredicate(format: "synced = nil and seq_no != nil")
let syncReady = try moc.count(for: fetch)
updateAppState { old in
var state = old
state.syncState.syncPendingCount = syncReady
return state
}
fetch.predicate = NSPredicate(format: "synced = nil")
let unsynced = try moc.count(for: fetch)
debugPrint("Transmissions without node confirmation: \(unsynced)")
}
catch let error as NSError {
setAppError(error, fn: "loadTransmissions", domain: "database")
}
catch let error {
let nserr = NSError(domain: "database", code: 1, userInfo: [NSLocalizedDescriptionKey: "\(error)"])
setAppError(nserr, fn: "loadTransmissions", domain: "database")
}
}
}
static private func recordOneLoraSeqNo(_ data: DataController, update: [(NSManagedObjectID, UInt32)]) {
if (update.isEmpty) {
return
}
data.performInContext() { moc in
let (objID, loraSeq) = update.first!
do {
let tx = try moc.existingObject(with: objID) as! Transmission
tx.seq_no = NSNumber(value: loraSeq)
try moc.save()
}
catch let error as NSError {
setAppError(error, fn: "applicationDidFinishLaunchingWithOptions", domain: "database")
}
catch let error {
let nserr = NSError(domain: "database", code: 1, userInfo: [NSLocalizedDescriptionKey: "\(error)"])
setAppError(nserr, fn: "applicationDidFinishLaunchingWithOptions", domain: "database")
}
updateAppState({ (old) -> AppState in
var state = old
state.syncState.recordWorking = false
state.syncState.recordLoraToObject = state.syncState.recordLoraToObject.filter({ pair -> Bool in
return pair.0 != objID
})
state.syncState.syncPendingCount += 1;
return state
})
}
}
static func formatterForJSONDate() -> DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}
open static func syncOneTransmission(_ data: DataController, host: String, authorization: AuthState) {
data.performInContext() { moc in
do {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Transmission")
fetch.predicate = NSPredicate(format: "synced = nil and seq_no != nil")
fetch.fetchLimit = 1
let transmissions = try moc.fetch(fetch) as! [Transmission]
if (transmissions.count>=1) {
postTransmission(transmissions[0], data: data, host: host, authorization: authorization)
}
}
catch let error as NSError {
setAppError(error, fn: "applicationDidFinishLaunchingWithOptions", domain: "database")
}
catch let error {
let nserr = NSError(domain: "database", code: 1, userInfo: [NSLocalizedDescriptionKey: "\(error)"])
setAppError(nserr, fn: "applicationDidFinishLaunchingWithOptions", domain: "database")
}
}
}
open static func postTransmission(
_ tx: Transmission,
data: DataController,
host: String,
authorization auth: AuthState) {
let formatter = formatterForJSONDate()
let params = Promise<[String:AnyObject]>{ fulfill, reject in
data.performInContext() { _ in
// Access database object within moc queue
let parameters = [
"lat": tx.latitude,
"lon": tx.longitude,
"alt": tx.altitude,
"timestamp": formatter.string(from: tx.created),
"dev_eui": tx.dev_eui,
"msg_seq": tx.seq_no!,
] as [String : Any]
fulfill(parameters as [String : AnyObject])
}
}
params.then { parameters -> Promise<NSDictionary> in
//debugPrint("Params: \(parameters)")
let url = "http://\(host)/api/v0/transmissions"
debugPrint("URL: \(url)")
let rsp = Promise<NSDictionary> { fulfill, reject in
let authorization = "TwitterAuth username=\"\(auth.user_name)\" token=\"\(auth.oauth_token)\" token-secret=\"\(auth.oauth_secret)\" realm=\"api\""
let headers = ["Authorization" : authorization]
request(url, method: .post,
parameters: parameters,
encoding: JSONEncoding(), headers: headers)
.responseJSON(queue: nil, options: .allowFragments, completionHandler: { response in
switch response.result {
case .success(let value):
fulfill(value as! NSDictionary)
case .failure(let error):
reject(error)
}
})
}
return rsp
}.then { jsonResponse -> Void in
//debugPrint(jsonResponse)
// Write sync time to tx
try data.performAndWaitInContext() { moc in
let now = Date()
tx.synced = now
try moc.save()
updateAppState({ (old) -> AppState in
var state = old
state.syncState.lastPost = now
if (state.syncState.syncPendingCount>0) {
state.syncState.syncPendingCount -= 1;
}
state.syncState.syncWorking = false
return state
})
}
}.catch { (error) in
debugPrint("\(error)")
setAppError(error, fn: "postTransmission", domain: "web")
updateAppState({ (old) -> AppState in
var state = old
state.syncState.lastPost = Date()
state.syncState.syncWorking = false
return state
})
}
}
}
| mit | b08e995cbf87903f09b80c2bac06c98c | 41.953237 | 170 | 0.550289 | 5.120497 | false | false | false | false |
nicolastinkl/CardDeepLink | CardDeepLinkKit/CardDeepLinkKit/UIGitKit/Alamofire/ParameterEncoding.swift | 1 | 11072 | // ParameterEncoding.swift
//
// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See https://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
// MARK: ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
- `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`,
and `DELETE` requests, or set as the body for requests with any other HTTP method. The
`Content-Type` HTTP header field of an encoded request with HTTP body is set to
`application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification
for how to encode collection types, the convention of appending `[]` to the key for array
values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested
dictionary values (`foo[bar]=baz`).
- `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same
implementation as the `.URL` case, but always applies the encoded result to the URL.
- `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is
set as the body of the request. The `Content-Type` HTTP header field of an encoded request is
set to `application/json`.
- `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object,
according to the associated format and write options values, which is set as the body of the
request. The `Content-Type` HTTP header field of an encoded request is set to
`application/x-plist`.
- `Custom`: Uses the associated closure value to construct a new request given an existing request and
parameters.
*/
internal enum ParameterEncoding {
case URL
case URLEncodedInURL
case JSON
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
- parameter URLRequest: The request to have parameters applied
- parameter parameters: The parameters to apply
- returns: A tuple containing the constructed request and the error that occurred during parameter encoding,
if any.
*/
internal func encode(
URLRequest: URLRequestConvertible,
parameters: [String: AnyObject]?)
-> (NSMutableURLRequest, NSError?)
{
var mutableURLRequest = URLRequest.URLRequest
guard let parameters = parameters where !parameters.isEmpty else {
return (mutableURLRequest, nil)
}
var encodingError: NSError? = nil
switch self {
case .URL, .URLEncodedInURL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sort(<) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
func encodesParametersInURL(method: Method) -> Bool {
switch self {
case .URLEncodedInURL:
return true
default:
break
}
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
URLComponents.percentEncodedQuery = percentEncodedQuery
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue(
"application/x-www-form-urlencoded; charset=utf-8",
forHTTPHeaderField: "Content-Type"
)
}
mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding(
NSUTF8StringEncoding,
allowLossyConversion: false
)
}
case .JSON:
do {
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .PropertyList(let format, let options):
do {
let data = try NSPropertyListSerialization.dataWithPropertyList(
parameters,
format: format,
options: options
)
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
} catch {
encodingError = error as NSError
}
case .Custom(let closure):
(mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, encodingError)
}
/**
Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
- parameter key: The key of the query component.
- parameter value: The value of the query component.
- returns: The percent-escaped, URL encoded query string components.
*/
public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
public func escape(string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, OSX 10.10, *) {
escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = index.advancedBy(batchSize, limit: string.endIndex)
let range = Range(start: startIndex, end: endIndex)
let substring = string.substringWithRange(range)
escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring
index = endIndex
}
}
return escaped
}
}
| bsd-2-clause | d932b3c228f333b3ab5cafdc66555688 | 43.103586 | 124 | 0.593135 | 5.647959 | false | false | false | false |
nathantannar4/NTComponents | NTComponents Demo/TimelineTableViewController.swift | 1 | 2465 | //
// TimelineTableViewController.swift
// TimelineTableViewCell
//
// Created by Zheng-Xiang Ke on 2016/10/20.
// Copyright © 2016年 Zheng-Xiang Ke. All rights reserved.
//
import UIKit
import NTComponents
class TimelineTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(NTTimelineTableViewCell.self, forCellReuseIdentifier: "NTTimelineTableViewCell")
self.tableView.separatorStyle = .none
self.tableView.estimatedRowHeight = 300
self.tableView.rowHeight = UITableViewAutomaticDimension
let item = UIBarButtonItem(image: nil, style: .plain, target: nil, action: nil)
item.setIcon(icon: FAType.FAGithub, iconSize: 30)
navigationItem.rightBarButtonItem = item
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Day " + String(describing: section + 1)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = NTTimelineTableViewCell(style: .detailed)
cell.isInitial = indexPath.row == 0
cell.isFinal = indexPath.row + 1 == self.tableView(tableView, numberOfRowsInSection: indexPath.section)
cell.timeLabel.text = "\(indexPath.row + 8):30"
cell.titleLabel.text = Lorem.words(nbWords: 3).capitalized
cell.descriptionTextView.text = Lorem.paragraph()
cell.thumbnailImageView.image = #imageLiteral(resourceName: "Nathan")
// Becomes available if initialized with NTTimelineTableViewCell(style: .detailed)
cell.durationLabel.text = "60 Min"
cell.locationLabel.text = Lorem.words(nbWords: 2).capitalized
// cell.durationIconView.setFAIconWithName(icon: FAType.FAAdressCard, textColor: .black)
if indexPath.row == 3 {
cell.timeline.trailingColor = Color.Default.Tint.View
cell.accessoryType = .disclosureIndicator
} else if indexPath.row == 4 {
cell.timeline.leadingColor = Color.Default.Tint.View
}
return cell
}
}
| mit | b73ed45a91c60d429773b1f47cf8e223 | 37.46875 | 112 | 0.67831 | 4.771318 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/iOS Collection/Business/Business/Location/LocationViewController.swift | 1 | 9584 | //
// LocationViewController.swift
// Business
//
// Created by 朱双泉 on 2018/10/31.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
import CoreLocation
import INTULocationManager
class LocationViewController: UIViewController {
@IBOutlet weak var addressTextView: UITextView!
@IBOutlet weak var latitudeTextField: UITextField!
@IBOutlet weak var longitudeTextField: UITextField!
var lastLocation: CLLocation?
@IBOutlet weak var compassImageView: UIImageView!
@IBOutlet weak var noticeLabel: UILabel!
lazy var geoCoder: CLGeocoder = CLGeocoder()
@IBAction func geoCodingButtonClick(_ sender: UIButton) {
guard let addressStr = addressTextView.text else {return}
geoCoder.geocodeAddressString(addressStr) { (placemarks, error) in
if error == nil {
print("地理编码成功")
if let placemarks = placemarks, placemarks.count > 0, let placemark = placemarks.first, let location = placemark.location {
// print(placemark.locality)
self.addressTextView.text = placemark.name
self.latitudeTextField.text = String(describing: location.coordinate.latitude)
self.longitudeTextField.text = String(describing: location.coordinate.longitude)
}
} else {
print("地理编码失败")
}
}
}
@IBAction func reverseGeoCodingButtonClick(_ sender: UIButton) {
guard let latitudeText = latitudeTextField.text else {return}
guard let longitudeText = longitudeTextField.text else {return}
let latitude = CLLocationDegrees(latitudeText) ?? 0
let longitude = CLLocationDegrees(longitudeText) ?? 0
let location = CLLocation(latitude: latitude, longitude: longitude)
geoCoder.reverseGeocodeLocation(location) { (placemark, error) in
if error == nil {
print("逆地理编码成功")
} else {
print("逆地理编码失败")
}
}
}
lazy var locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.delegate = self
if #available(iOS 8.0, *) {
if #available(iOS 9.0, *) {
locationManager.allowsBackgroundLocationUpdates = true
}
// locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
}
locationManager.distanceFilter = 0.1
/*
public let kCLLocationAccuracyBestForNavigation: CLLocationAccuracy
public let kCLLocationAccuracyBest: CLLocationAccuracy
public let kCLLocationAccuracyNearestTenMeters: CLLocationAccuracy
public let kCLLocationAccuracyHundredMeters: CLLocationAccuracy
public let kCLLocationAccuracyKilometer: CLLocationAccuracy
public let kCLLocationAccuracyThreeKilometers: CLLocationAccuracy
*/
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
return locationManager
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Location"
if CLLocationManager.headingAvailable() {
locationManager.startUpdatingHeading()
} else {
print("你的设备当前不支持获取设备航向")
}
startUpdatingLocation()
startMonitoring()
latitudeTextField.becomeFirstResponder()
}
}
extension LocationViewController {
func getCurrentLocation() {
LocationTool.shared.getCurrentLocation { (location, errorMessage) in
if errorMessage == nil {
}
}
}
func thirdParty() {
let locationManager_ = INTULocationManager.sharedInstance()
let requestID = locationManager_.requestLocation(withDesiredAccuracy: .city, timeout: 10.0, delayUntilAuthorized: true) { (location, accuracy, status) in
if status == .success {
print("定位成功\(String(describing: location))")
} else {
print("定位失败")
}
}
locationManager_.forceCompleteLocationRequest(requestID)
locationManager_.cancelLocationRequest(requestID)
let locationManager2_ = INTULocationManager.sharedInstance()
locationManager2_.subscribeToLocationUpdates(withDesiredAccuracy: .block) { (location, accuracy, status) in
if status == .success {
print("定位成功\(String(describing: location))")
} else {
print("定位失败")
}
}
}
}
extension LocationViewController {
func startMonitoring() {
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
let latitude: CLLocationDegrees = CLLocationDegrees(latitudeTextField.text!) ?? 0
let longitude: CLLocationDegrees = CLLocationDegrees(longitudeTextField.text!) ?? 0
let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
var radius = 1000.0
if radius > locationManager.maximumRegionMonitoringDistance {
radius = locationManager.maximumRegionMonitoringDistance
}
let region: CLCircularRegion = CLCircularRegion(center: center, radius: radius, identifier: "Shanghai")
locationManager.startMonitoring(for: region)
locationManager.requestState(for: region)
}
}
func startUpdatingLocation() {
locationManager.startUpdatingLocation()
let latitude: CLLocationDegrees = CLLocationDegrees(latitudeTextField.text!) ?? 0
let longitude: CLLocationDegrees = CLLocationDegrees(longitudeTextField.text!) ?? 0
let loc1 = CLLocation(latitude: latitude, longitude: longitude)
let latitude2: CLLocationDegrees = 121.49491
let longitude2: CLLocationDegrees = 31.24169
let loc2 = CLLocation(latitude: latitude2, longitude: longitude2)
let distance = loc1.distance(from: loc2)
print(distance)
}
}
extension LocationViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
noticeLabel.text = "Enter Region---" + region.identifier
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
noticeLabel.text = "Leave Region---" + region.identifier
}
func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
if state == .inside {
noticeLabel.text = "Enter Region---" + region.identifier
} else if state == .outside {
noticeLabel.text = "Leave Region---" + region.identifier
}
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
if newHeading.headingAccuracy < 0 {
return
}
let angle = newHeading.magneticHeading
let radian = angle / 180.0 * Double.pi
UIView.animate(withDuration: 0.5) {
self.compassImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-radian))
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
latitudeTextField.text = String(location.coordinate.latitude)
longitudeTextField.text = String(location.coordinate.longitude)
if location.horizontalAccuracy < 0 {
print("数据无效")
return
}
let courseStrArr = ["北偏东", "东偏南", "南偏西", "西偏北"]
let index = Int(location.course) / 90
var courseStr = courseStrArr[index]
let angle = location.course.truncatingRemainder(dividingBy: 90)
if angle == 0.0 {
let tempStr = courseStr as NSString
courseStr = tempStr.substring(to: 1)
}
var distance = 0
if let lastLocation = lastLocation {
distance = Int(location.distance(from: lastLocation))
}
lastLocation = location
print(courseStr, angle, "方向, 移动了", distance, "米")
print("已经获取到位置信息: \(location)")
}
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("用户没有决定")
case .restricted:
print("受限制")
case .denied:
if CLLocationManager.locationServicesEnabled() {
print("真正的被拒绝")
if #available(iOS 10.0, *), let url = URL(string: UIApplication.openSettingsURLString /*prefs:root=LOCATION_SERVICES*/), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, completionHandler: nil)
}
} else {
print("请打开定位服务")
}
case .authorizedAlways:
print("前后台定位授权")
case .authorizedWhenInUse:
print("前台定位授权")
}
}
}
| mit | d10b89894d8cb0235e33c6eaf9e63952 | 38.538136 | 175 | 0.625013 | 5.514775 | false | false | false | false |
dnseitz/YAPI | YAPI/YAPI/YelpAuthentication.swift | 1 | 1617 | //
// YelpAuthentication.swift
// YAPI
//
// Created by Daniel Seitz on 9/3/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
internal enum AuthKeys {
fileprivate static var _consumerKey: String?
fileprivate static var _consumerSecret: String?
fileprivate static var _token: String?
fileprivate static var _tokenSecret: String?
static var consumerKey: String? {
get {
return _consumerKey
}
set {
guard _consumerKey == nil else {
assert(false, "Only set the consumerKey once")
return
}
_consumerKey = newValue
}
}
static var consumerSecret: String? {
get {
return _consumerSecret
}
set {
guard _consumerSecret == nil else {
assert(false, "Only set the consumerSecret once")
return
}
_consumerSecret = newValue
}
}
static var token: String? {
get {
return _token
}
set {
guard _token == nil else {
assert(false, "Only set the token once")
return
}
_token = newValue
}
}
static var tokenSecret: String? {
get {
return _tokenSecret
}
set {
guard _tokenSecret == nil else {
assert(false, "Only set the tokenSecret once")
return
}
_tokenSecret = newValue
}
}
static var areSet: Bool {
return (_consumerKey != nil) && (_consumerSecret != nil) && (_token != nil) && (_tokenSecret != nil)
}
static func clearAuthentication() {
_consumerKey = nil
_consumerSecret = nil
_token = nil
_tokenSecret = nil
}
}
| mit | 810164a186a97b8e007ec2323a527f87 | 20.263158 | 104 | 0.589109 | 4.275132 | false | false | false | false |
infinitetoken/Arcade | Sources/Protocols/Viewable.swift | 1 | 994 | //
// Viewable.swift
// Arcade
//
// Created by Paul Foster on 3/7/19.
// Copyright © 2019 A.C. Wright Design. All rights reserved.
//
import Foundation
public func !=(lhs: Viewable, rhs: Viewable) -> Bool { return lhs.persistentId != rhs.persistentId }
public func ==(lhs: Viewable, rhs: Viewable) -> Bool { return lhs.persistentId == rhs.persistentId }
public protocol Viewable: Codable {
static var table: Table { get }
var persistentId: String { get }
}
public extension Viewable {
var table: Table { return Self.table }
}
public extension Viewable {
var dictionary: [String : Any] {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(self)
guard let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] else { return [:] }
return result
} catch {
return [:]
}
}
}
| mit | 0ccc05d0137013e878bb679bdadb0531 | 21.568182 | 127 | 0.576032 | 4.280172 | false | false | false | false |
heptal/kathy | Kathy/ChatViewController.swift | 1 | 7571 | //
// ChatViewController.swift
// Kathy
//
// Created by Michael Bujol on 6/13/16.
// Copyright © 2016 heptal. All rights reserved.
//
import Cocoa
class ChatViewController: NSViewController {
override func loadView() {
let size = CGSize(width: 1024, height: 768)
view = ChatView(frame: CGRect(origin: CGPoint.zero, size: size))
}
}
class ChatView: NSView {
var session: IRCSession!
var textView: NSTextView!
var channelTableView: NSTableView!
var userTableView: NSTableView!
var historyIndex: Int!
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let userDefaults = UserDefaults.standard
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// Build the interface
let mainSplitView = NSSplitView(frame: frameRect)
mainSplitView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable]
mainSplitView.translatesAutoresizingMaskIntoConstraints = true
mainSplitView.autoresizesSubviews = true
mainSplitView.isVertical = true
mainSplitView.dividerStyle = .thin
addSubview(mainSplitView)
let stackView = NSStackView()
stackView.orientation = .vertical
mainSplitView.addSubview(stackView)
let chatTextView = ChatTextView()
stackView.addView(chatTextView, in: .top)
let inputView = NSTextField()
inputView.identifier = "inputView"
inputView.delegate = self
stackView.addView(inputView, in: .top)
let sideSplitView = NSSplitView(frame: frameRect)
sideSplitView.isVertical = false
mainSplitView.addSubview(sideSplitView)
let channelView = ChannelView()
sideSplitView.addSubview(channelView)
let userView = UserView()
sideSplitView.addSubview(userView)
NSLayoutConstraint.soloConstraint(sideSplitView, attr: .width, relation: .lessThanOrEqual, amount: 200).isActive = true
NSLayoutConstraint.soloConstraint(sideSplitView, attr: .width, relation: .greaterThanOrEqual, amount: 100).isActive = true
NSLayoutConstraint.soloConstraint(channelView, attr: .height, relation: .greaterThanOrEqual, amount: 100).isActive = true
// Start it all up
resetHistoryIndex()
session = IRCSession(delegate: self)
textView = chatTextView.subviewWithIdentifier("chatView") as? NSTextView
channelTableView = channelView.subviewWithIdentifier("channelTableView") as? NSTableView
userTableView = userView.subviewWithIdentifier("userTableView") as? NSTableView
// Bind table views
let users = NSArrayController()
users.bind("contentSet", to: session.channels, withKeyPath: "selection.users", options: nil)
users.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true, selector: #selector(NSString.caseInsensitiveCompare))]
channelTableView.bind("content", to: session.channels, withKeyPath: "arrangedObjects.name", options: nil)
channelTableView.bind("selectionIndexes", to: session.channels, withKeyPath: "selectionIndexes", options: nil)
userTableView.bind("content", to: users, withKeyPath: "arrangedObjects.description", options: nil)
userTableView.doubleAction = #selector(didDoubleClickUser)
NotificationCenter.default.addObserver(self, selector: #selector(didSelectChannel), name: NSNotification.Name.NSTableViewSelectionDidChange, object: nil)
// Connect
if let host = userDefaults.string(forKey: "defaultHost") {
if userDefaults.bool(forKey: "autoConnect") {
session?.command("/server \(host)")
}
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func didDoubleClickUser(_ tableView: NSTableView) {
if let userRow = tableView.view(atColumn: 0, row: tableView.selectedRow, makeIfNecessary: false) as? NSTextField {
if let userChannel = session.setupChannel(User(userRow.stringValue).name) {
session.channels.setSelectedObjects([userChannel])
}
}
}
func didSelectChannel(_ notification: Notification?) {
if let tableView = notification?.object as? NSTableView {
if tableView == channelTableView {
if let channelRow = tableView.view(atColumn: 0, row: tableView.selectedRow, makeIfNecessary: false) as? NSTextField {
channelRow.textColor = NSColor.black
}
}
}
if let channel = session.channels.selectedObjects.first as? Channel {
window?.title = channel.name
textView.layoutManager?.replaceTextStorage(NSTextStorage(attributedString: formatMessage(channel.log.joined(separator: ""))))
textView.scrollToEndOfDocument(nil)
}
}
func appendMessageToActiveChannel(_ message: String) {
textView.textStorage?.append(formatMessage(message))
scrollIfNeeded()
}
func scrollIfNeeded() { // autoscroll if near bottom - may be a better way to do this?
if let scrollRect = textView.enclosingScrollView?.contentView.documentVisibleRect {
let viewRect = textView.preparedContentRect
if ((viewRect.size.height - scrollRect.size.height) - scrollRect.origin.y) <= 30 {
textView.scrollToEndOfDocument(nil)
}
}
}
func formatMessage(_ message: String) -> NSMutableAttributedString {
let color = NSColor.black
let font = NSFont(name: "Menlo", size: 12)!
let textAttributes = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
let attributedText = NSMutableAttributedString(string: message, attributes: textAttributes)
detector.matches(in: message, options: [], range: NSMakeRange(0, (message as NSString).length)).forEach { (urlMatch) in
if let url = urlMatch.url {
let ext = url.pathExtension
attributedText.addAttribute(NSLinkAttributeName, value: url, range: urlMatch.range)
if "jpgjpegpnggif".contains(ext) {
let attachmentCell = NSTextAttachmentCell(imageCell: NSImage(contentsOf: url))
let attachment = NSTextAttachment()
attachment.attachmentCell = attachmentCell
attributedText.append(NSAttributedString(string: "\n"))
attributedText.append(NSAttributedString(attachment: attachment))
attributedText.append(NSAttributedString(string: "\n\n"))
}
}
}
return attributedText
}
}
extension ChatView: IRCDelegate {
func didReceiveBroadcast(_ message: String) {
(session.channels.arrangedObjects as? Array<Channel>)?.forEach { $0.log.append(message) }
appendMessageToActiveChannel(message)
}
func didReceiveMessage(_ message: String) {
appendMessageToActiveChannel(message)
}
func didReceiveUnreadMessageOnChannel(_ channel: String) {
channelTableView.enumerateAvailableRowViews { (rowView, row) in
if let channelRow = rowView.view(atColumn: 0) as? NSTextField {
if channelRow.stringValue == channel {
channelRow.textColor = NSColor.orange
}
}
}
}
func didReceiveError(_ error: NSError) {
NSAlert(error: error).runModal()
}
}
| apache-2.0 | 6df64bfea74e8e3034781ccb3b0f36c1 | 39.265957 | 161 | 0.664465 | 5.050033 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/JetpackCapabilitiesServiceTests.swift | 2 | 1776 | import Foundation
import XCTest
@testable import WordPress
class JetpackCapabilitiesServiceTests: XCTestCase {
/// Gives the correct siteIDs to the remote service
func testCallServiceRemote() {
let remoteMock = JetpackCapabilitiesServiceRemoteMock()
let service = JetpackCapabilitiesService(capabilitiesServiceRemote: remoteMock)
service.sync(blogs: [RemoteBlog.mock()], success: { _ in })
XCTAssertEqual(remoteMock.forCalledWithSiteIds, [100])
}
/// Changes the RemoteBlog to contain the returned Jetpack Capabilities
func testChangeRemoteBlogCapabilities() {
let expect = expectation(description: "Adds jetpack capabilities into the RemoteBlog")
let remoteMock = JetpackCapabilitiesServiceRemoteMock()
let service = JetpackCapabilitiesService(capabilitiesServiceRemote: remoteMock)
service.sync(blogs: [RemoteBlog.mock()], success: { blogs in
XCTAssertTrue(blogs.first!.capabilities["backup"] as! Bool)
XCTAssertTrue(blogs.first!.capabilities["scan"] as! Bool)
expect.fulfill()
})
waitForExpectations(timeout: 1, handler: nil)
}
}
class JetpackCapabilitiesServiceRemoteMock: JetpackCapabilitiesServiceRemote {
var forCalledWithSiteIds: [Int] = []
override func `for`(siteIds: [Int], success: @escaping ([String: AnyObject]) -> Void) {
forCalledWithSiteIds = siteIds
var capabilities: [String: AnyObject] = [:]
siteIds.forEach { capabilities["\($0)"] = ["backup", "scan"] as AnyObject }
success(capabilities)
}
}
private extension RemoteBlog {
static func mock() -> RemoteBlog {
return RemoteBlog(jsonDictionary: ["ID": 100, "capabilities": ["foo": true]])
}
}
| gpl-2.0 | cafa622263dc585eb4955a6aa2394bc8 | 33.153846 | 94 | 0.690315 | 4.748663 | false | true | false | false |
narner/AudioKit | AudioKit/Common/Nodes/Generators/Physical Models/Clarinet/AKClarinet.swift | 1 | 4156 | //
// AKClarinet.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// STK Clarinet
///
open class AKClarinet: AKNode, AKToggleable, AKComponent {
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(generator: "flut")
public typealias AKAudioUnitType = AKClarinetAudioUnit
// MARK: - Properties
private var internalAU: AKAudioUnitType?
private var token: AUParameterObserverToken?
fileprivate var frequencyParameter: AUParameter?
fileprivate var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
@objc open dynamic var rampTime: Double = AKSettings.rampTime {
willSet {
internalAU?.rampTime = newValue
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
@objc open dynamic var frequency: Double = 110 {
willSet {
if frequency != newValue {
if let existingToken = token {
frequencyParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Amplitude
@objc open dynamic var amplitude: Double = 0.5 {
willSet {
if amplitude != newValue {
if let existingToken = token {
amplitudeParameter?.setValue(Float(newValue), originator: existingToken)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
@objc open dynamic var isStarted: Bool {
return internalAU?.isPlaying() ?? false
}
// MARK: - Initialization
/// Initialize the mandolin with defaults
override convenience init() {
self.init(frequency: 110)
}
/// Initialize the STK Clarinet model
///
/// - Parameters:
/// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is
/// greater than that.
/// - amplitude: Amplitude
///
@objc public init(
frequency: Double = 440,
amplitude: Double = 0.5) {
self.frequency = frequency
self.amplitude = amplitude
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
self?.avAudioNode = avAudioUnit
self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
guard let tree = internalAU?.parameterTree else {
AKLog("Parameter Tree Failed")
return
}
frequencyParameter = tree["frequency"]
amplitudeParameter = tree["amplitude"]
token = tree.token(byAddingParameterObserver: { [weak self] _, _ in
guard let _ = self else {
AKLog("Unable to create strong reference to self")
return
} // Replace _ with strongSelf if needed
DispatchQueue.main.async {
// This node does not change its own values so we won't add any
// value observing, but if you need to, this is where that goes.
}
})
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Trigger the sound with an optional set of parameters
/// - frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
open func trigger(frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
internalAU?.start()
internalAU?.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
@objc open func start() {
internalAU?.start()
}
/// Function to stop or bypass the node, both are equivalent
@objc open func stop() {
internalAU?.stop()
}
}
| mit | 22de40c3e55739189f4324a7e6aaec7e | 30.961538 | 113 | 0.611793 | 5.219849 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallClipRotate.swift | 5 | 1880 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallClipRotate: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.75
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let animation = self.animation
// Draw circle
let circle = ActivityIndicatorShape.ringThirdFour.makeLayer(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallClipRotate {
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
return scaleAnimation
}
var rotateAnimation: CAKeyframeAnimation {
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
return rotateAnimation
}
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| gpl-3.0 | e29fa7f18b68628229ed3091f4d0b559 | 29.819672 | 131 | 0.712234 | 4.795918 | false | false | false | false |
pkc456/Roastbook | Roastbook/Roastbook/View Controller/Mirror view controller/MirrorCollectionViewCell.swift | 1 | 1133 | //
// MirrorCollectionViewCell.swift
// Roastbook
//
// Created by Pradeep Choudhary on 4/25/17.
// Copyright © 2017 Pardeep chaudhary. All rights reserved.
//
import UIKit
import AlamofireImage
class MirrorCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var labelCelebrityName: UILabel!
@IBOutlet weak var labelHatePercentage: UILabel!
@IBOutlet weak var labelNewPost: UILabel!
var mirrorModel: MirrorContentItem? {
didSet {
if let modelObject = mirrorModel {
labelCelebrityName.text = modelObject.name
labelHatePercentage.text = String(modelObject.percentage)
let url = URL(string: modelObject.imagePath)!
let placeholderImage = UIImage(named: "Placeholder")
imageView.af_setImage(withURL: url, placeholderImage: placeholderImage)
let randomNumber = arc4random_uniform(20) + 2
labelNewPost.text = "\(randomNumber) new posts"
}
}
}
}
| mit | ff572b4c4ed2606b3b652c6e9ac36fdd | 30.444444 | 87 | 0.623675 | 4.921739 | false | false | false | false |
chromatic-seashell/weibo | 新浪微博/新浪微博/classes/home/GDWCollectionView.swift | 1 | 9261 | //
// GDWCollectionView.swift
// 新浪微博
//
// Created by apple on 15/11/17.
// Copyright © 2015年 apple. All rights reserved.
//
import UIKit
import SDWebImage
import AFNetworking
class GDWCollectionView: UICollectionView {
/// 配图容器高度约束
@IBOutlet weak var pictureCollectionViewHeightCons: NSLayoutConstraint!
/// 配图容器宽度约束
@IBOutlet weak var pictureCollectionVeiwWidthCons: NSLayoutConstraint!
var viewModel:GDWStatusViewModel?{
didSet{
// 配图
// 1计算配图和配图容器的尺寸
let (itemSize, size) = caculateSize()
// 2设置配图容器的尺寸
pictureCollectionVeiwWidthCons.constant = size.width
pictureCollectionViewHeightCons.constant = size.height
// 3设置配图的尺寸
if itemSize != CGSizeZero
{
(collectionViewLayout as! UICollectionViewFlowLayout).itemSize = itemSize
}
//刷新collectionView控件
reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
dataSource = self
delegate = self
}
// MARK: - 内部控制方法
/// 计算配图的尺寸
/// 第一个参数: imageView的尺寸
/// 第二个参数: 配图容器的尺寸
private func caculateSize() -> (CGSize, CGSize)
{
/*
没有配图: 不显示CGSizeZero
一张配图: 图片的尺寸就是配图和配图容器的尺寸
四张配图: 田字格
其他张配图: 九宫格
*/
// 1.获取配图个数
let count = viewModel?.thumbnail_pics?.count ?? 0
// 2.判断有没有配图
if count == 0
{
return (CGSizeZero, CGSizeZero)
}
// 3.判断是否是一张配图
if count == 1
{
let urlStr = viewModel!.thumbnail_pics?.last!.absoluteString
// 加载已经下载好得图片
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlStr)
// 获取图片的size
return (image.size, image.size)
}
let imageWidth:CGFloat = 90
let imageHeight = imageWidth
let imageMargin: CGFloat = 10
// 4.判断是否是4张配图
if count == 4
{
let col:CGFloat = 2
// 计算宽度 宽度 = 列数 * 图片宽度+ (列数 - 1) * 间隙
let width = col * imageWidth + (col - 1) * imageMargin
// 计算高度
let height = width
return (CGSize(width: 90, height: 90), CGSize(width: width, height: height))
}
// 5.其它张配图 九宫格
let col: CGFloat = 3
let row = (count - 1) / 3 + 1
let width = col * imageWidth + (col - 1) * imageMargin
let height = CGFloat(row) * imageHeight + CGFloat(row - 1) * imageMargin
return (CGSize(width: 90, height: 90), CGSize(width: width, height: height))
}
}
// MARK: - GDWPhotoBroserAnimationManagerDelegate
extension GDWCollectionView : GDWPhotoBroserAnimationManagerDelegate{
/// 返回和点击的UIImageView一模一样的UIImageView
func photoBrowserImageView(path: NSIndexPath) -> UIImageView{
//1.新建一个imageVeiw
let imageView = UIImageView()
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
//2将点击的图片赋值给imageView
let url = viewModel?.thumbnail_pics![path.item]
imageView.sd_setImageWithURL(url)
return imageView
}
/// 返回被点击的UIImageView相对于keywindow的frame
func photoBrowserFromRect(path: NSIndexPath) -> CGRect{
// 1.获取被点击的cell
/*
注意: 如果直接获取cell的frame是相对于collectionview的
含义: 将cell.frame的坐标系从self转换到keyWindow
*/
guard let cell = cellForItemAtIndexPath(path) else {
return CGRectZero
}
let frame = convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
return frame
}
/// 返回被点击的UIImageView最终在图片浏览器中显示的尺寸
func photoBrowserToRect(path: NSIndexPath) -> CGRect{
// 1.取出被点击的图片
guard let key = viewModel?.thumbnail_pics![path.item].absoluteString else
{
return CGRectZero
}
// 利用SDWebImage从磁盘中获取图片
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
// 屏幕宽高
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
// 1.按照宽高比缩放图片
let scale = image.size.height / image.size.width
// 计算图片的高度
let height = scale * screenWidth
// 2.判断是长图还是短图
var offsetY: CGFloat = 0
if height < screenHeight
{
// 短图, 需要居中
//1.1计算偏移位
offsetY = (screenHeight - height) * 0.5
}
return CGRect(origin: CGPoint(x: 0, y: offsetY), size: CGSize(width: screenWidth, height: height))
}
}
// MARK: - UICollectionViewDataSource,UICollectionViewDelegate
extension GDWCollectionView :UICollectionViewDataSource,UICollectionViewDelegate{
// UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel?.thumbnail_pics?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("pictureCell", forIndexPath: indexPath) as! GDWPictureCollectionViewCell
let url = viewModel!.thumbnail_pics![indexPath.item]
cell.imageURL = url
return cell
}
// UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//1.点击图片是先下载,显示进度
guard let url = viewModel?.bmidddle_pics![indexPath.item] else
{
return
}
/*
监听网络注册是在GDWHomeViewController的viewDidLoad方法中设置的.
*/
// 获取当前的网络状态
let status = AFNetworkReachabilityManager.sharedManager().networkReachabilityStatus
// 如果没有网络直接返回
if status == AFNetworkReachabilityStatus.NotReachable{
return
}
//判断当前的网络状态
// AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status) -> Void in
//
//
// let netStatus = status as AFNetworkReachabilityStatus
//
// if netStatus == AFNetworkReachabilityStatus.ReachableViaWWAN{
// print("蜂窝网")
//
// }else if netStatus == AFNetworkReachabilityStatus.ReachableViaWiFi{
//
// print("WiFi")
// }else if netStatus == AFNetworkReachabilityStatus.NotReachable{
//
// print("没有网络")
// }
// }
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! GDWPictureCollectionViewCell
//1.1下载图片
SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (current, total) -> Void in
cell.iconImageView.progregss = CGFloat(current) / CGFloat(total)
}) { (_, error , _ , _ , _ ) -> Void in
//2.图片下载完后,给首页控制器发送通知,modal出图片游览器
NSNotificationCenter.defaultCenter().postNotificationName(GDWPhotoBrowserShow, object: self, userInfo: ["urls" : self.viewModel!.bmidddle_pics!,"indexPath" : indexPath])
}
}
}
// MARK: - 自定义cell
class GDWPictureCollectionViewCell: UICollectionViewCell {
/// 配图
@IBOutlet weak var iconImageView: ProgressImageView!
@IBOutlet weak var gifImageView: UIImageView!
/// 配图对应的URL
var imageURL: NSURL?
{
didSet{
//1.设置配图
iconImageView.sd_setImageWithURL(imageURL)
//2.是否显示gif图标
guard let urlStr = imageURL?.absoluteString else
{
return
}
gifImageView.hidden = (urlStr as NSString).pathExtension != "gif"
}
}
}
| apache-2.0 | f7d307fa217c3dbb52b35c6f7b583bcd | 29.586081 | 185 | 0.579042 | 5.008998 | false | false | false | false |
Caktuspace/iTunesCover | iTunesCover/iTunesCover/Classes/Modules/List/User Interface/Presenter/AlbumDisplayData.swift | 1 | 525 | //
// AlbumDisplayData.swift
// iTunesCover
//
// Created by Quentin Metzler on 20/12/15.
// Copyright © 2015 LocalFitness. All rights reserved.
//
import Foundation
struct AlbumDisplayData : Equatable {
var items : [AlbumDisplayItem] = []
init(items: [AlbumDisplayItem]) {
self.items = items
}
}
func == (leftSide: AlbumDisplayData, rightSide: AlbumDisplayData) -> Bool {
var hasEqualSections = false
hasEqualSections = rightSide.items == leftSide.items
return hasEqualSections
} | gpl-2.0 | 133f92885ae7bff1f1ca6698be73c3b4 | 21.826087 | 75 | 0.688931 | 4.09375 | false | false | false | false |
mohamede1945/quran-ios | SQLitePersistence/SQLitePersistence.swift | 1 | 2617 | //
// SQLitePersistence.swift
// Quran
//
// Created by Mohamed Afifi on 10/29/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// 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.
//
import SQLite
import VFoundation
public protocol SQLitePersistence: ReadonlySQLitePersistence {
var filePath: String { get }
var version: UInt { get }
func onCreate(connection: Connection) throws
func onUpgrade(connection: Connection, oldVersion: UInt, newVersion: UInt) throws
}
extension SQLitePersistence {
public func onUpgrade(connection: Connection, oldVersion: UInt, newVersion: UInt) throws {
// default implementation
}
public func openConnection() throws -> Connection {
// create the connection
let connection = try ConnectionsPool.default.getConnection(filePath: filePath)
let oldVersion = try connection.getUserVersion()
let newVersion = version
precondition(newVersion != 0, "version should be greater than 0.")
// if first time
if oldVersion <= 0 {
try connection.transaction {
do {
try onCreate(connection: connection)
} catch {
throw PersistenceError.generalError(error, info: "Cannot create database for file '\(filePath)'")
}
try connection.setUserVersion(Int(newVersion))
}
} else {
let unsignedOldVersion = UInt(oldVersion)
if newVersion != unsignedOldVersion {
try connection.transaction {
do {
try onUpgrade(connection: connection, oldVersion: unsignedOldVersion, newVersion: newVersion)
} catch {
throw PersistenceError.generalError(
error, info: "Cannot upgrade database for file '\(filePath)' from \(unsignedOldVersion) to \(newVersion)")
}
try connection.setUserVersion(Int(newVersion))
}
}
}
return connection
}
}
| gpl-3.0 | ea2640622e96e5d6afbef19571325f33 | 35.859155 | 134 | 0.625908 | 5.081553 | false | false | false | false |
xedin/swift | test/expr/capture/order.swift | 1 | 2402 | // XFAIL: enable-astscope-lookup
// RUN: %target-typecheck-verify-swift
func makeIncrementor(amount: Int) -> () -> Int {
func incrementor() -> Int {
currentTotal += amount // expected-error{{cannot capture 'currentTotal' before it is declared}}
return currentTotal // note: redundant diagnostic suppressed
}
var currentTotal = 0 // expected-note{{'currentTotal' declared here}}
currentTotal = 1; _ = currentTotal
return incrementor
}
func pingpong() {
func ping() -> Int {
return pong()
}
func pong() -> Int {
return ping()
}
_ = ping()
}
func transitiveForwardCapture() {
func ping() -> Int {
return pong() // expected-error{{cannot capture 'pong', which would use 'x' before it is declared}}
}
_ = ping()
var x = 1 // expected-note{{'x' declared here}}
func pong() -> Int { // expected-note{{'pong', declared here, captures 'x'}}
x += 1
return ping()
}
}
func transitiveForwardCapture2() {
func ping() -> Int {
_ = pong() // expected-error{{cannot capture 'pong', which would use 'x' before it is declared}}
}
_ = ping()
var x = 1 // expected-note{{'x' declared here}}
func pong() -> Int { // expected-note{{'pong', declared here, captures 'pung'}}
_ = pung()
}
func pung() -> Int { // expected-note{{'pung', declared here, captures 'x'}}
x += 1
return ping()
}
}
func transitiveForwardCapture3() {
var y = 2
func ping() -> Int {
_ = pong() // expected-error{{cannot capture 'pong', which would use 'x' before it is declared}}
}
_ = ping()
var x = 1 // expected-note{{'x' declared here}}
func pung() -> Int { // expected-note{{'pung', declared here, captures 'x'}}
x += 1
return ping()
}
func pong() -> Int { // expected-note{{'pong', declared here, captures 'pung'}}
y += 2
_ = pung()
}
}
func outOfOrderEnum() {
func f() -> Suit {
return .Club
}
enum Suit {
case Club
case Diamond
case Heart
case Spade
}
}
func captureInClosure() {
let x = { (i: Int) in
currentTotal += i // expected-error{{cannot capture 'currentTotal' before it is declared}}
}
var currentTotal = 0 // expected-note{{'currentTotal' declared here}}
_ = x
currentTotal += 1
}
class X {
func foo() { }
}
func captureLists(x: X) {
{ [unowned x] in x.foo() }();
let _: Void = { [unowned x] in x.foo() }()
let _: Void = { [weak x] in x?.foo() }()
}
| apache-2.0 | f300d9077b6c4a7e5626e3b652505079 | 23.02 | 103 | 0.596586 | 3.496361 | false | false | false | false |
goblinr/omim | iphone/Maps/UI/Search/Filters/FilterRatingCell.swift | 9 | 1156 | @objc(MWMFilterRatingCell)
final class FilterRatingCell: MWMTableViewCell {
@IBOutlet private var ratingButtons: [UIButton]! {
didSet {
ratingButtons.map { $0.layer }.forEach {
$0.cornerRadius = 4
$0.borderWidth = 1
$0.borderColor = UIColor.blackDividers().cgColor
}
}
}
@IBOutlet weak var any: UIButton!
@IBOutlet weak var good: UIButton!
@IBOutlet weak var veryGood: UIButton!
@IBOutlet weak var excellent: UIButton!
@IBAction private func tap(sender: UIButton!) {
guard !sender.isSelected else { return }
ratingButtons.forEach { $0.isSelected = false }
sender.isSelected = true
let rating: String
switch sender {
case any: rating = kStatAny
case good: rating = kStat7
case veryGood: rating = kStat8
case excellent: rating = kStat9
default:
rating = ""
assert(false)
}
Statistics.logEvent(kStatSearchFilterClick, withParameters: [
kStatCategory: kStatHotel,
kStatRating: rating,
])
}
override func awakeFromNib() {
super.awakeFromNib()
isSeparatorHidden = true
backgroundColor = UIColor.clear
}
}
| apache-2.0 | 773f6efe3fcf5306bf8a4e51bf046a35 | 24.688889 | 65 | 0.66436 | 4.329588 | false | false | false | false |
domenicosolazzo/practice-swift | Metal/metalexample/metalexample/GameViewController.swift | 1 | 3583 | //
// GameViewController.swift
// metalexample
//
// Created by Domenico on 14/07/15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
class GameViewController: UIViewController {
override func viewDidLoad() {
// get device
let device: MTLDevice = MTLCreateSystemDefaultDevice()!
// create command queue
var commandQueue: MTLCommandQueue = device.makeCommandQueue()
// Vertex
let vertexArray:[Float] = [
0.0, 0.75,
-0.75, -0.75,
0.75, -0.75]
// Vertex buffer
var vertexBuffer: MTLBuffer! = device.newBufferWithBytes(vertexArray,
length: vertexArray.count * sizeofValue(vertexArray[0]),
options: nil)
// Get the shader
let newDefaultLibrary = device.newDefaultLibrary()
let newVertexFunction = newDefaultLibrary!.makeFunction(name: "myVertexShader")
let newFragmentFunction = newDefaultLibrary!.makeFunction(name: "myFragmentShader")
// Render the pipeline
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = newVertexFunction
pipelineDescriptor.fragmentFunction = newFragmentFunction
// More format here: https://developer.apple.com/library/ios/documentation/Metal/Reference/MetalConstants_Ref/#//apple_ref/c/tdef/MTLPixelFormat
pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.bgra8Unorm
// Render pipeline state from descriptor
var pipelineState: MTLRenderPipelineState!
pipelineState = device.newRenderPipelineStateWithDescriptor(pipelineDescriptor, completionHandler: nil)
//prepare view with layer
let metalLayer = CAMetalLayer()
metalLayer.device = device //set the device
metalLayer.pixelFormat = .BGRA8Unorm
metalLayer.frame = view.layer.frame
view.layer.addSublayer(metalLayer)
//get next drawable texture
var drawable = metalLayer.nextDrawable()
//create a render descriptor
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = drawable.texture //assign drawable texture
renderPassDescriptor.colorAttachments[0].loadAction = .clear //clear with color on load
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 1.0,
green: 1.0,
blue: 0.0,
alpha: 1.0) // specify color to clear it with
//Command Buffer - get next available command buffer
let commandBuffer = commandQueue.makeCommandBuffer()
//create Encoder - converts code to machine language
let renderEncoder:MTLRenderCommandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)
//provide pipelineState and vertexBuffer
renderEncoder.setRenderPipelineState(pipelineState)
renderEncoder.setVertexBuffer(vertexBuffer, offset: 0, at: 0)
//drawing begin
renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1) //drawin
//End drawing
renderEncoder.endEncoding()
//commit to view
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
}
| mit | 47b12b15041bc7a986020629a488df1d | 35.561224 | 152 | 0.650014 | 5.741987 | false | false | false | false |
gvsucis/mobile-app-dev-book | iOS/ch13/TraxyApp/TraxyApp/DarkSkyWeatherService.swift | 3 | 2103 | //
// DarkSkyWeatherService.swift
// TraxyApp
//
// Created by Jonathan Engelsma on 10/12/17.
// Copyright © 2017 Jonathan Engelsma. All rights reserved.
//
import Foundation
let sharedDarkSkyInstance = DarkSkyWeatherService()
class DarkSkyWeatherService: WeatherService {
let API_BASE = "https://api.darksky.net/forecast/"
var urlSession = URLSession.shared
class func getInstance() -> DarkSkyWeatherService {
return sharedDarkSkyInstance
}
func getWeatherForDate(date: Date, forLocation location: (Double, Double),
completion: @escaping (Weather?) -> Void)
{
let urlStr = API_BASE + DARK_SKY_WEATHER_API_KEY +
"/\(location.0),\(location.1),\(Int(date.timeIntervalSince1970))"
let url = URL(string: urlStr)
let task = self.urlSession.dataTask(with: url!) {
(data, response, error) in
if let error = error {
print(error.localizedDescription)
} else if let _ = response {
let parsedObj : Dictionary<String,AnyObject>!
do {
parsedObj = try JSONSerialization.jsonObject(with: data!, options:
.allowFragments) as? Dictionary<String,AnyObject>
guard let currently = parsedObj["currently"],
let summary = currently["summary"] as? String,
let iconName = currently["icon"] as? String,
let temperature = currently["temperature"] as? Double
else {
completion(nil)
return
}
let weather = Weather(iconName: iconName, temperature: temperature,
summary: summary)
completion(weather)
} catch {
completion(nil)
}
}
}
task.resume()
}
}
| gpl-3.0 | d09045840bb7f4a253c3e59f0887b622 | 34.033333 | 88 | 0.509039 | 5.375959 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/Gacha/Detail/View/GachaDetailLoadingCell.swift | 1 | 1408 | //
// GachaDetailLoadingCell.swift
// DereGuide
//
// Created by zzk on 19/01/2018.
// Copyright © 2018 zzk. All rights reserved.
//
import UIKit
class GachaDetailLoadingCell: ReadableWidthTableViewCell {
override var maxReadableWidth: CGFloat {
return 824
}
let leftLabel = UILabel()
let loadingView = LoadingView()
weak var delegate: LoadingViewDelegate? {
didSet {
loadingView.delegate = delegate
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
leftLabel.font = UIFont.systemFont(ofSize: 16)
leftLabel.text = NSLocalizedString("模拟抽卡", comment: "")
readableContentView.addSubview(leftLabel)
leftLabel.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(10)
}
readableContentView.addSubview(loadingView)
loadingView.snp.makeConstraints { (make) in
make.top.equalTo(leftLabel.snp.bottom).offset(8)
make.left.equalTo(10)
make.right.equalTo(-10)
make.bottom.equalTo(-20)
}
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6ce2043abab26484d54e516a0cfc5b2f | 25.396226 | 74 | 0.611866 | 4.67893 | false | false | false | false |
nervousnet/nervousnet-iOS | nervous/Controllers/BLEController.swift | 1 | 4537 | //
// BLEController.swift
// nervousnet-iOS
//
// Created by Sam on 03 Mar 2016.
// Copyright (c) 2016 ETHZ . All rights reserved.
//
import Foundation
import UIKit
import CoreBluetooth
private let _BLE = BLEController()
class BLEController : NSObject, SensorProtocol, CBCentralManagerDelegate, CBPeripheralDelegate{
private var auth: Int = 0
private let VM = VMController.sharedInstance
var timestamp: UInt64 = 0
var activeCentralManager: CBCentralManager?
var activePeripheral: CBPeripheral?
var blepacketCommaCounter = 0
var blepacket = ""
var blepacketRaw = ""
override init() {
super.init()
print("init ble")
activeCentralManager = CBCentralManager(delegate: self, queue: nil)
activeCentralManager?.delegate = self
activePeripheral?.delegate = self
}
class var sharedInstance: BLEController {
return _BLE
}
func requestAuthorization() {
print("requesting authorization for BLE")
let val1 = self.VM.defaults.boolForKey("kill") //objectForKey("kill") as! Bool
let val2 = self.VM.defaults.boolForKey("switchBLE") //objectForKey("switchMag") as! Bool
if !val1 && val2 {
self.auth = 1
}
else {
self.auth = 0
}
}
func initializeUpdate(freq: Double) {
}
// requestAuthorization must be before this is function is called
func startSensorUpdates() {
if self.auth == 0 {
return
}
}
func stopSensorUpdates() {
self.auth = 0
}
func centralManagerDidUpdateState(central: CBCentralManager) {
let c = central
if c.state == CBCentralManagerState.PoweredOn {
print("Bluetooth ON")
central.scanForPeripheralsWithServices(nil, options: nil)
}else {
print("Bluetooth switched off or not initialized")
}
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
print(RSSI)
if(peripheral.name == "mars"){
activePeripheral = peripheral
print("connecting to mars...")
// Stop looking for more peripherals.
activeCentralManager!.stopScan()
// Connect to this peripheral.
activeCentralManager!.connectPeripheral(activePeripheral!, options: nil)
}
}
func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("connected to mars...")
activePeripheral?.delegate = self
activePeripheral?.discoverServices(nil)
}
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
//peripheral.setNotifyValue(true, forCharacteristic: nil)
print("found services")
for service:CBService in (activePeripheral?.services)! {
activePeripheral?.discoverCharacteristics(nil, forService: service)
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
for char in service.characteristics! {
activePeripheral?.setNotifyValue(true, forCharacteristic: char)
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
print("characteristic updated")
print(blepacketCommaCounter)
if let characteristicValue = characteristic.value{
let datastring = NSString(data: characteristicValue, encoding: NSUTF8StringEncoding)
let commacount = (datastring!.componentsSeparatedByString(",").count - 1)
self.blepacketCommaCounter += commacount
self.blepacketRaw += datastring as! String
//we want to see 19 commas
}
if(self.blepacketCommaCounter == 20){
print("full packet received")
self.blepacket = self.blepacketRaw
self.blepacketRaw = ""
print(self.blepacket)
self.blepacketCommaCounter = 0
}
}
}
| gpl-3.0 | 1dba4ee34bbfc853a527841cb1e33163 | 27.006173 | 157 | 0.598193 | 5.622057 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/Bonus/Scene/BubbleScalingAnimator.swift | 2 | 2569 | //
// BubbleScalingAnimator.swift
// GrandCentralBoard
//
// Created by Bartłomiej Chlebek on 07/04/16.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import SpriteKit
protocol BubbleScalingAnimatorDelegate: class {
func bubbleScalingAnimator(bubbleScalingAnimator: BubbleScalingAnimator, didScaleSpriteNodeDown spriteNode: SKSpriteNode)
}
final class BubbleScalingAnimator {
enum State {
case Idle
case ScalingUp
case ScaledUp
case ScalingDown
}
private var state: State = .Idle
private weak var spriteNode: SKSpriteNode?
private var scaleDownTimer: NSTimer?
weak var delegate: BubbleScalingAnimatorDelegate?
private let bubbleResizeDuration: NSTimeInterval
init(spriteNode: SKSpriteNode, bubbleResizeDuration: NSTimeInterval) {
self.spriteNode = spriteNode
self.bubbleResizeDuration = bubbleResizeDuration
}
func scaleUp() {
switch self.state {
case .Idle: fallthrough
case .ScalingDown: self.performScaleUpAction()
case .ScaledUp: self.rescheduleScaleDownDeferTimer()
case .ScalingUp: return
}
}
// MARK - Scale actions
private func performScaleUpAction() {
guard let spriteNode = self.spriteNode else { return }
let scaleUpAction = SKAction.scaleTo(2.3, duration: 0.5)
self.state = .ScalingUp
spriteNode.runAction(scaleUpAction, completion: {
self.state = .ScaledUp
self.rescheduleScaleDownDeferTimer()
})
}
@objc private func performScaleDownAction() {
guard let spriteNode = self.spriteNode else { return }
let scaleDownAction = SKAction.scaleTo(1, duration: 0.5)
self.state = .ScalingDown
spriteNode.runAction(scaleDownAction, completion: {
self.state = .Idle
self.delegate?.bubbleScalingAnimator(self, didScaleSpriteNodeDown: spriteNode)
})
}
// MARK - Scale down timer
private func rescheduleScaleDownDeferTimer() {
self.scaleDownTimer?.invalidate()
self.scaleDownTimer = NSTimer.scheduledTimerWithTimeInterval(bubbleResizeDuration,
target: self,
selector: #selector(performScaleDownAction),
userInfo: nil,
repeats: false)
}
}
| gpl-3.0 | f6521c5ece90803d3dbb84c0ab8e7ce8 | 31.910256 | 125 | 0.614725 | 5.033333 | false | false | false | false |
PJayRushton/stats | Stats/SaveGameStats.swift | 1 | 1180 | //
// SaveGameStats.swift
// Stats
//
// Created by Parker Rushton on 8/24/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
struct SaveGameStats: Command {
var game: Game
init(for game: Game) {
self.game = game
}
func execute(state: AppState, core: Core<AppState>) {
DispatchQueue.global().async {
var stats = self.gameStats(from: self.game, state: state)
let ref = StatsRefs.gameStatsRef(teamId: stats.teamId).childByAutoId()
stats.id = ref.key
self.networkAccess.setValue(at: ref, parameters: stats.jsonObject(), completion: { result in
if case .success = result {
core.fire(command: SaveSeasonStats())
}
})
}
}
func gameStats(from game: Game, state: AppState) -> GameStats {
var gameStats = GameStats(game)
var stats = [String: [Stat]]()
game.lineup.forEach { player in
stats[player.id] = state.statState.playerStats(for: player, game: game)
}
gameStats.stats = stats
return gameStats
}
}
| mit | 25ee1bcecf12b44554cc56700bc9f9ff | 26.418605 | 104 | 0.570823 | 4.151408 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Model/CheckinSession.swift | 1 | 1954 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
public class CheckinSession: NSObject, Decodable {
public var session: Session?
public var owner: User?
public var lastStatus: CheckinStatus?
enum CodingKeys: String, CodingKey {
case session
case owner
case lastStatus
}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
session = try container.decodeIfPresent(Session.self, forKey: .session)
owner = try container.decodeIfPresent(User.self, forKey: .owner)
lastStatus = try container.decodeIfPresent(CheckinStatus.self, forKey: .lastStatus)
}
public class Session: NSObject, Decodable {
public var id: Int = 0
public var dateTime: DateTime?
enum CodingKeys: String, CodingKey {
case id
case dateTime
}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
id = container.decodeKey(.id, ofType: Int.self)
dateTime = try container.decodeIfPresent(DateTime.self, forKey: .dateTime)
}
}
public class DateTime: NSObject, Decodable {
public var date: String = ""
public var time: String = ""
public var dateTime: String = ""
enum CodingKeys: String, CodingKey {
case date
case time
case dateTime
}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
date = container.decodeKey(.date, ofType: String.self)
time = container.decodeKey(.time, ofType: String.self)
dateTime = container.decodeKey(.dateTime, ofType: String.self)
}
}
}
| mit | 29f9566f9e47d0d0944cd75859da0060 | 33.263158 | 98 | 0.628776 | 4.798526 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Extensions/Collection+Extensions.swift | 1 | 6885 | //
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension Sequence where Iterator.Element: Hashable {
/// Return an `Array` containing only the unique elements of `self` in order.
public func uniqued() -> [Iterator.Element] {
uniqued { $0 }
}
}
extension Sequence {
/// Return an `Array` containing only the unique elements of `self`, in order,
/// where `unique` criteria is determined by the `uniqueProperty` block.
///
/// - Parameter uniqueProperty: `unique` criteria is determined by the value
/// returned by this block.
/// - Returns: Return an `Array` containing only the unique elements of `self`,
/// in order, that satisfy the predicate `uniqueProperty`.
public func uniqued<T: Hashable>(_ uniqueProperty: (Iterator.Element) -> T) -> [Iterator.Element] {
var seen: [T: Bool] = [:]
return filter { seen.updateValue(true, forKey: uniqueProperty($0)) == nil }
}
}
extension Array where Element: Hashable {
/// Modify `self` in-place such that only the unique elements of `self` in order
/// are remaining.
public mutating func unique() {
self = uniqued()
}
/// Modify `self` in-place such that only the unique elements of `self` in order
/// are remaining, where `unique` criteria is determined by the `uniqueProperty`
/// block.
///
/// - Parameter uniqueProperty: `unique` criteria is determined by the value
/// returned by this block.
public mutating func unique<T: Hashable>(_ uniqueProperty: (Element) -> T) {
self = uniqued(uniqueProperty)
}
}
extension Collection {
/// Returns the number of elements of the sequence that satisfy the given
/// predicate.
///
/// ```swift
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNamesCount = cast.count { $0.count < 5 }
/// print(shortNamesCount)
/// // Prints "2"
/// ```
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the element
/// should be included in the returned count.
/// - Returns: A count of elements that satisfy the given predicate.
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
public func count(where predicate: (Element) throws -> Bool) rethrows -> Int {
try filter(predicate).count
}
}
extension RangeReplaceableCollection {
/// Returns an array by removing all the elements that satisfy the given
/// predicate.
///
/// Use this method to remove every element in a collection that meets
/// particular criteria. This example removes all the odd values from an array
/// of numbers:
///
/// ```swift
/// var numbers = [5, 6, 7, 8, 9, 10, 11]
/// let removedNumbers = numbers.removingAll(where: { $0 % 2 == 1 })
///
/// // numbers == [6, 8, 10]
/// // removedNumbers == [5, 7, 9, 11]
/// ```
////
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the element
/// should be removed from the collection.
/// - Returns: A collection of the elements that are removed.
public mutating func removingAll(where predicate: (Element) throws -> Bool) rethrows -> Self {
let result = try filter(predicate)
try removeAll(where: predicate)
return result
}
}
extension RangeReplaceableCollection where Element: Equatable, Index == Int {
/// Removes given element by value from the collection.
///
/// - Returns: `true` if removed; `false` otherwise
@discardableResult
public mutating func remove(_ element: Element) -> Bool {
for (index, elementToCompare) in enumerated() where element == elementToCompare {
remove(at: index)
return true
}
return false
}
/// Removes given elements by value from the collection.
public mutating func remove(_ elements: [Element]) {
elements.forEach { remove($0) }
}
// MARK: - Non-mutating
/// Removes given element by value from the collection.
public func removing(_ element: Element) -> Self {
var copy = self
copy.remove(element)
return copy
}
/// Removes given elements by value from the collection.
public func removing(_ elements: [Element]) -> Self {
var copy = self
copy.remove(elements)
return copy
}
/// Move an element in `self` to a specific index.
///
/// - Parameters:
/// - element: The element in `self` to move.
/// - index: An index locating the new location of the element in `self`.
/// - Returns: `true` if moved; otherwise, `false`.
@discardableResult
public mutating func move(_ element: Element, to index: Int) -> Bool {
guard remove(element) else {
return false
}
insert(element, at: index)
return true
}
}
extension Sequence {
/// Returns the first element of the sequence that satisfies the given
/// predicate.
///
/// - Parameter keyPaths: A list of `keyPaths` that are used to find an element
/// in the sequence.
/// - Returns: The first element of the sequence that satisfies predicate, or
/// `nil` if there is no element that satisfies predicate.
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
func first(_ keyPaths: KeyPath<Element, Bool>...) -> Element? {
first { element in
keyPaths.allSatisfy {
element[keyPath: $0]
}
}
}
/// Returns the first element of the sequence that satisfies the given
/// predicate.
///
/// - Parameter keyPaths: A list of `keyPaths` that are used to find an element
/// in the sequence.
/// - Returns: The first element of the sequence that satisfies predicate, or
/// `nil` if there is no element that satisfies predicate.
/// - Complexity: O(_n_), where _n_ is the length of the sequence.
func first(_ keyPaths: [KeyPath<Element, Bool>]) -> Element? {
first { element in
keyPaths.allSatisfy {
element[keyPath: $0]
}
}
}
}
// MARK: - NSPredicate
extension Collection {
/// Returns an array containing, in order, the elements of the sequence that
/// satisfy the given predicate.
public func filter(with predicate: NSPredicate) -> [Element] {
filter(predicate.evaluate(with:))
}
/// Returns the first element of the sequence that satisfies the given
/// predicate.
public func first(with predicate: NSPredicate) -> Element? {
first(where: predicate.evaluate(with:))
}
}
| mit | 602422b11950e4efb39d9eae0ba8754f | 34.302564 | 103 | 0.621586 | 4.438427 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Layers/PreCompLayerModel.swift | 1 | 1499 | //
// PreCompLayer.swift
// lottie-swift
//
// Created by Brandon Withrow on 1/8/19.
//
import Foundation
/// A layer that holds another animation composition.
final class PreCompLayerModel: LayerModel {
/// The reference ID of the precomp.
let referenceID: String
/// A value that remaps time over time.
let timeRemapping: KeyframeGroup<Vector1D>?
/// Precomp Width
let width: Double
/// Precomp Height
let height: Double
private enum CodingKeys : String, CodingKey {
case referenceID = "refId"
case timeRemapping = "tm"
case width = "w"
case height = "h"
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PreCompLayerModel.CodingKeys.self)
self.referenceID = try container.decode(String.self, forKey: .referenceID)
self.timeRemapping = try container.decodeIfPresent(KeyframeGroup<Vector1D>.self, forKey: .timeRemapping)
self.width = try container.decode(Double.self, forKey: .width)
self.height = try container.decode(Double.self, forKey: .height)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(referenceID, forKey: .referenceID)
try container.encode(timeRemapping, forKey: .timeRemapping)
try container.encode(width, forKey: .width)
try container.encode(height, forKey: .height)
}
}
| mit | 2da518848b4de56cb6243429a65f7d05 | 28.98 | 108 | 0.710474 | 3.85347 | false | false | false | false |
pengpengCoder/Refresher | RefresherDemo/ViewController.swift | 1 | 1684 | //
// ViewController.swift
// Refresher
//
// Created by MingChen on 2017/10/20.
// Copyright © 2017年 MingChen. All rights reserved.
//
import UIKit
let refreshViews = ["IndicatorHeader", "TextHeader", "SmallGIFHeader", "GIFTextHeader", "BigGIFHeader", "IndicatorFooter", "TextFooter", "IndicatorAutoFooter", "TextAutoFooter"]
class ViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate {
var tableView: UITableView!
private let cellID = "ViewController-cellId"
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 60
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return refreshViews.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
cell.selectionStyle = .none
cell.textLabel?.text = refreshViews[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = DemoViewController()
vc.style = DemoViewController.Style(rawValue: indexPath.row) ?? .indicatorHeader
navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 7db26c5621b21e83db8e5b90536dcffc | 33.306122 | 177 | 0.69304 | 4.915205 | false | false | false | false |
chrisellsworth/LookingAtThings | Sources/App/NetworkService.swift | 1 | 582 | import Foundation
import HTTP
import Vapor
class NetworkService {
enum NetworkServiceError: Error {
case invalid(URL)
}
let drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
func resolve(url: URL) throws -> URL {
let response = try drop.client.get(url.absoluteString)
let location = response.headers[HeaderKey.location]
if let location = location, let locationURL = URL(string: location) {
return locationURL
} else {
throw NetworkServiceError.invalid(url)
}
}
}
| mit | 418dbf940a403d1ddd9308b6c1be7592 | 20.555556 | 77 | 0.616838 | 4.476923 | false | false | false | false |
aleckretch/Bloom | iOS/Bloom/Bloom/Components/Add Card/Cells/AddCardBillingTableViewCell.swift | 1 | 7381 | //
// AddCardBillingTableViewCell.swift
// Bloom
//
// Created by Alec Kretch on 10/22/17.
// Copyright © 2017 Alec Kretch. All rights reserved.
//
import Foundation
import UIKit
class AddCardBillingTableViewCell: UITableViewCell {
@IBOutlet weak var emailAddressTextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
emailAddressTextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var phoneNumberTextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
phoneNumberTextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var line1TextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
line1TextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var line2TextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
line2TextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var line3TextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
line3TextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var cityTextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
cityTextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var stateTextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
stateTextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var zipTextFieldWidthConstraint: NSLayoutConstraint! {
didSet {
zipTextFieldWidthConstraint.constant = (UIScreen.main.bounds.size.width/2)-16-8
}
}
@IBOutlet weak var emailAddressTextField: UITextField! {
didSet {
emailAddressTextField.font = UIFont.boldSystemFont(ofSize: 14.0)
emailAddressTextField.textColor = Constant.Color.lightGray
emailAddressTextField.borderStyle = .none
emailAddressTextField.returnKeyType = .next
emailAddressTextField.autocorrectionType = .no
emailAddressTextField.keyboardType = .emailAddress
emailAddressTextField.placeholder = "Email"
emailAddressTextField.delegate = self
}
}
@IBOutlet weak var phoneNumberTextField: UITextField! {
didSet {
phoneNumberTextField.font = UIFont.boldSystemFont(ofSize: 14.0)
phoneNumberTextField.textColor = Constant.Color.lightGray
phoneNumberTextField.borderStyle = .none
phoneNumberTextField.returnKeyType = .next
phoneNumberTextField.autocorrectionType = .no
phoneNumberTextField.keyboardType = .phonePad
phoneNumberTextField.placeholder = "Phone"
phoneNumberTextField.delegate = self
}
}
@IBOutlet weak var line1TextField: UITextField! {
didSet {
line1TextField.font = UIFont.boldSystemFont(ofSize: 14.0)
line1TextField.textColor = Constant.Color.lightGray
line1TextField.borderStyle = .none
line1TextField.returnKeyType = .next
line1TextField.autocorrectionType = .no
line1TextField.autocapitalizationType = .words
line1TextField.placeholder = "Address"
line1TextField.delegate = self
}
}
@IBOutlet weak var line2TextField: UITextField! {
didSet {
line2TextField.font = UIFont.boldSystemFont(ofSize: 14.0)
line2TextField.textColor = Constant.Color.lightGray
line2TextField.borderStyle = .none
line2TextField.returnKeyType = .next
line2TextField.autocorrectionType = .no
line2TextField.autocapitalizationType = .words
line2TextField.placeholder = "Address (cont.)"
line2TextField.delegate = self
}
}
@IBOutlet weak var line3TextField: UITextField! {
didSet {
line3TextField.font = UIFont.boldSystemFont(ofSize: 14.0)
line3TextField.textColor = Constant.Color.lightGray
line3TextField.borderStyle = .none
line3TextField.returnKeyType = .next
line3TextField.autocorrectionType = .no
line3TextField.keyboardType = .decimalPad
line3TextField.autocapitalizationType = .words
line3TextField.placeholder = "Address (cont.)"
line3TextField.delegate = self
}
}
@IBOutlet weak var cityTextField: UITextField! {
didSet {
cityTextField.font = UIFont.boldSystemFont(ofSize: 14.0)
cityTextField.textColor = Constant.Color.lightGray
cityTextField.borderStyle = .none
cityTextField.returnKeyType = .next
cityTextField.autocorrectionType = .no
cityTextField.autocapitalizationType = .words
cityTextField.placeholder = "City"
cityTextField.delegate = self
}
}
@IBOutlet weak var stateTextField: UITextField! {
didSet {
stateTextField.font = UIFont.boldSystemFont(ofSize: 14.0)
stateTextField.textColor = Constant.Color.lightGray
stateTextField.borderStyle = .none
stateTextField.returnKeyType = .next
stateTextField.autocorrectionType = .no
stateTextField.autocapitalizationType = .allCharacters
stateTextField.placeholder = "State"
stateTextField.delegate = self
}
}
@IBOutlet weak var zipTextField: UITextField! {
didSet {
zipTextField.font = UIFont.boldSystemFont(ofSize: 14.0)
zipTextField.textColor = Constant.Color.lightGray
zipTextField.borderStyle = .none
zipTextField.returnKeyType = .next
zipTextField.autocorrectionType = .no
zipTextField.keyboardType = .decimalPad
zipTextField.placeholder = "Zip"
zipTextField.delegate = self
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .none
// Initialization code
}
}
extension AddCardBillingTableViewCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if emailAddressTextField.isFirstResponder {
phoneNumberTextField.becomeFirstResponder()
} else if phoneNumberTextField.isFirstResponder {
line1TextField.becomeFirstResponder()
} else if line1TextField.isFirstResponder {
line2TextField.becomeFirstResponder()
} else if line2TextField.isFirstResponder {
line3TextField.becomeFirstResponder()
} else if line3TextField.isFirstResponder {
cityTextField.becomeFirstResponder()
} else if cityTextField.isFirstResponder {
stateTextField.becomeFirstResponder()
} else if stateTextField.isFirstResponder {
zipTextField.becomeFirstResponder()
} else if zipTextField.isFirstResponder {
zipTextField.resignFirstResponder()
}
return false
}
}
| mit | 226b4ce9ff49890f18d889c658e36bfe | 37.638743 | 100 | 0.651355 | 5.371179 | false | false | false | false |
Dougly/2For1 | 2for1/InfoView.swift | 1 | 2707 | //
// InfoView.swift
// 2for1
//
// Created by Douglas Galante on 2/8/17.
// Copyright © 2017 Flatiron. All rights reserved.
//
import UIKit
class InfoView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var firstInstructionLabel: UILabel!
@IBOutlet weak var secondInstructionLabel: UILabel!
@IBOutlet weak var thirdInstructionLabel: UILabel!
@IBOutlet weak var rollsHigherDescriptionLabel: UILabel!
@IBOutlet weak var rollsLowerDescriptionLabel: UILabel!
@IBOutlet weak var tiesDescriptionLabel: UILabel!
@IBOutlet weak var fourthInstructionLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
Bundle.main.loadNibNamed("InfoView", owner: self, options: nil)
self.addSubview(contentView)
self.constrain(contentView)
setText()
}
func setText() {
let firstInstruction = "A player starts the game by rolling a single die. This sets the initial score."
let secondInstruction = "After rolling, the die is passed to the next player. When the die is passed to a new player the drink wager goes up by 1."
let thirdInstruction = "The next player then roles the dice. There are three outcomes:"
let one = "In the case of the player rolling higher than the score their roll becomes the new score to beat and they can pass the die on to the next player. Passing the die incrtements the drink wager by 1."
let two = "In the case of the player rolling lower than the score the player has the option to drink the current number of drinks, or add an additional die and double the drinking wager. The player can only add one die during their turn and adds the single die roll onto their previous roll. If the player fails to roll higher than the current score with the additional die they must drink the now doubled number of drinks."
let three = "If the player ties the current score it is an automatic loss and they must drink the current number of drinks."
let fourthInstruction = "The game continues until a player drinks and restarts the game."
firstInstructionLabel.text = firstInstruction
secondInstructionLabel.text = secondInstruction
thirdInstructionLabel.text = thirdInstruction
rollsHigherDescriptionLabel.text = one
rollsLowerDescriptionLabel.text = two
tiesDescriptionLabel.text = three
fourthInstructionLabel.text = fourthInstruction
}
}
| mit | 061600b2940ec0b889f2daa63af995d6 | 41.952381 | 432 | 0.701035 | 4.858169 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Utils/ENUtil.swift | 1 | 2221 | //
// ENUtil.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/19/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
let EN_WEEKDAY_OFFSET = [
"sunday": 0,
"sun": 0,
"monday": 1,
"mon": 1,
"tuesday": 2,
"tue":2,
"wednesday": 3,
"wed": 3,
"thursday": 4,
"thurs": 4,
"thur": 4,
"thu": 4,
"friday": 5,
"fri": 5,
"saturday": 6,
"sat": 6
]
let EN_WEEKDAY_OFFSET_PATTERN = "(?:" + EN_WEEKDAY_OFFSET.keys.joined(separator: "|") + ")"
let EN_MONTH_OFFSET = [
"january": 1,
"jan": 1,
"jan.": 1,
"february": 2,
"feb": 2,
"feb.": 2,
"march": 3,
"mar": 3,
"mar.": 3,
"april": 4,
"apr": 4,
"apr.": 4,
"may": 5,
"june": 6,
"jun": 6,
"jun.": 6,
"july": 7,
"jul": 7,
"jul.": 7,
"august": 8,
"aug": 8,
"aug.": 8,
"september": 9,
"sep": 9,
"sep.": 9,
"sept": 9,
"sept.": 9,
"october": 10,
"oct": 10,
"oct.": 10,
"november": 11,
"nov": 11,
"nov.": 11,
"december": 12,
"dec": 12,
"dec.": 12
]
let EN_INTEGER_WORDS = [
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
"ten": 10,
"eleven": 11,
"twelve": 12
]
let EN_INTEGER_WORDS_PATTERN = "(?:" + EN_INTEGER_WORDS.keys.joined(separator: "|") + ")"
let EN_ORDINAL_WORDS = [
"first": 1,
"second": 2,
"third": 3,
"fourth": 4,
"fifth": 5,
"sixth": 6,
"seventh": 7,
"eighth": 8,
"ninth": 9,
"tenth": 10,
"eleventh": 11,
"twelfth": 12,
"thirteenth": 13,
"fourteenth": 14,
"fifteenth": 15,
"sixteenth": 16,
"seventeenth": 17,
"eighteenth": 18,
"nineteenth": 19,
"twentieth": 20,
"twenty first": 21,
"twenty second": 22,
"twenty third": 23,
"twenty fourth": 24,
"twenty fifth": 25,
"twenty sixth": 26,
"twenty seventh": 27,
"twenty eighth": 28,
"twenty ninth": 29,
"thirtieth": 30,
"thirty first": 31
]
let EN_ORDINAL_WORDS_PATTERN = "(?:\(EN_ORDINAL_WORDS.keys.joined(separator: "|").replacingOccurrences(of: " ", with: "[ -]")))"
| mit | 7622b65b3356c58508d09e8513ef08e4 | 17.5 | 128 | 0.471171 | 2.665066 | false | false | false | false |
tache/SwifterSwift | Sources/Extensions/SwiftStdlib/ArrayExtensions.swift | 1 | 19145 | //
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
// MARK: - Methods (Integer)
public extension Array where Element: Numeric {
/// SwifterSwift: Sum of all elements in array.
///
/// [1, 2, 3, 4, 5].sum() -> 15
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total
}
}
// MARK: - Methods (FloatingPoint)
public extension Array where Element: FloatingPoint {
/// SwifterSwift: Average of all elements in array.
///
/// [1.2, 2.3, 4.5, 3.4, 4.5].average() = 3.18
///
/// - Returns: average of the array's elements.
public func average() -> Element {
guard !isEmpty else { return 0 }
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total / Element(count)
}
}
// MARK: - Methods
public extension Array {
/// SwifterSwift: Element at the given index if it exists.
///
/// [1, 2, 3, 4, 5].item(at: 2) -> 3
/// [1.2, 2.3, 4.5, 3.4, 4.5].item(at: 3) -> 3.4
/// ["h", "e", "l", "l", "o"].item(at: 10) -> nil
///
/// - Parameter index: index of element.
/// - Returns: optional element (if exists).
public func item(at index: Int) -> Element? {
guard startIndex..<endIndex ~= index else { return nil }
return self[index]
}
/// SwifterSwift: Remove last element from array and return it.
///
/// [1, 2, 3, 4, 5].pop() // returns 5 and remove it from the array.
/// [].pop() // returns nil since the array is empty.
///
/// - Returns: last element in array (if applicable).
@discardableResult public mutating func pop() -> Element? {
return popLast()
}
/// SwifterSwift: Insert an element at the beginning of array.
///
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5]
/// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Insert an element to the end of array.
///
/// [1, 2, 3, 4].push(5) -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l"].push("o") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func push(_ newElement: Element) {
append(newElement)
}
/// SwifterSwift: Safely Swap values at index positions.
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func safeSwap(from index: Int, to otherIndex: Int) {
guard index != otherIndex,
startIndex..<endIndex ~= index,
startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// SwifterSwift: Swap values at index positions.
///
/// [1, 2, 3, 4, 5].swap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].swap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func swap(from index: Int, to otherIndex: Int) {
swapAt(index, otherIndex)
}
/// SwifterSwift: Get first index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 6].firstIndex { $0 % 2 == 0 } -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: first index where the specified condition evaluates to true. (optional)
public func firstIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get last index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].lastIndex { $0 % 2 == 0 } -> 6
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: last index where the specified condition evaluates to true. (optional)
public func lastIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get all indices where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].indices(where: { $0 == 1 }) -> [0, 2, 5]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: all indices where the specified condition evaluates to true. (optional)
public func indices(where condition: (Element) throws -> Bool) rethrows -> [Int]? {
var indicies: [Int] = []
for (index, value) in lazy.enumerated() {
if try condition(value) { indicies.append(index) }
}
return indicies.isEmpty ? nil : indicies
}
/// SwifterSwift: Check if all elements in array match a conditon.
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
public func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: Check if no elements in array match a conditon.
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: Get last element that satisfies a conditon.
///
/// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: the last element in the array matching the specified condition. (optional)
public func last(where condition: (Element) throws -> Bool) rethrows -> Element? {
for element in reversed() {
if try condition(element) { return element }
}
return nil
}
/// SwifterSwift: Filter elements based on a rejection condition.
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
public func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: Get element count based on condition.
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try condition(element) { count += 1 }
}
return count
}
/// SwifterSwift: Iterate over a collection in reverse order. (right to left)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> //Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
public func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach { try body($0) }
}
/// SwifterSwift: Calls given closure with each element where condition is true.
///
/// [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -> //print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// SwifterSwift: Reduces an array while returning each interim combination.
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
public func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: Filtered and map in a single operation.
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try flatMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
}
/// SwifterSwift: Keep elements of Array while condition is true.
///
/// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
public mutating func keep(while condition: (Element) throws -> Bool) rethrows {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
self = Array(self[startIndex..<index])
break
}
}
}
/// SwifterSwift: Take element of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[startIndex..<index])
}
}
return self
}
/// SwifterSwift: Skip elements of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -> [6, 8]
///
/// - Parameter condition: condition to eveluate each element against.
/// - Returns: All elements after the condition evaluates to false.
public func skip(while condition: (Element) throws-> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[index..<endIndex])
}
}
return [Element]()
}
/// SwifterSwift: Calls given closure with an array of size of the parameter slice where condition is true.
///
/// [0, 2, 4, 7].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7]
/// [0, 2, 4, 7, 6].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7], [6]
///
/// - Parameters:
/// - slice: size of array in each interation.
/// - body: a closure that takes an array of slice size as a parameter.
public func forEach(slice: Int, body: ([Element]) throws -> Void) rethrows {
guard slice > 0, !isEmpty else { return }
var value: Int = 0
while value < count {
try body(Array(self[Swift.max(value, startIndex)..<Swift.min(value + slice, endIndex)]))
value += slice
}
}
/// SwifterSwift: Returns an array of slices of length "size" from the array. If array can't be split evenly, the final slice will be the remaining elements.
///
/// [0, 2, 4, 7].group(by: 2) -> [[0, 2], [4, 7]]
/// [0, 2, 4, 7, 6].group(by: 2) -> [[0, 2], [4, 7], [6]]
///
/// - Parameters:
/// - size: The size of the slices to be returned.
public func group(by size: Int) -> [[Element]]? {
//Inspired by: https://lodash.com/docs/4.17.4#chunk
guard size > 0, !isEmpty else { return nil }
var value: Int = 0
var slices: [[Element]] = []
while value < count {
slices.append(Array(self[Swift.max(value, startIndex)..<Swift.min(value + size, endIndex)]))
value += size
}
return slices
}
/// SwifterSwift: Group the elements of the array in a dictionary.
///
/// [0, 2, 5, 4, 7].groupByKey { $0%2 ? "evens" : "odds" } -> [ "evens" : [0, 2, 4], "odds" : [5, 7] ]
///
/// - Parameter getKey: Clousure to define the key for each element.
/// - Returns: A dictionary with values grouped with keys.
public func groupByKey<K: Hashable>(keyForValue: (_ element: Element) throws -> K) rethrows -> [K: [Element]] {
var group = [K: [Element]]()
for value in self {
let key = try keyForValue(value)
group[key] = (group[key] ?? []) + [value]
}
return group
}
/// SwifterSwift: Returns a new rotated array by the given places.
///
/// [1, 2, 3, 4].rotated(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotated(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
/// - Returns: The new rotated array
public func rotated(by places: Int) -> [Element] {
//Inspired by: https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate
guard places != 0 && places < count else {
return self
}
var array: [Element] = self
if places > 0 {
let range = (array.count - places)..<array.endIndex
let slice = array[range]
array.removeSubrange(range)
array.insert(contentsOf: slice, at: 0)
} else {
let range = array.startIndex..<(places * -1)
let slice = array[range]
array.removeSubrange(range)
array.append(contentsOf: slice)
}
return array
}
/// SwifterSwift: Rotate the array by the given places.
///
/// [1, 2, 3, 4].rotate(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotate(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
public mutating func rotate(by places: Int) {
self = rotated(by: places)
}
/// SwifterSwift: Shuffle array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffle() // shuffles array
///
public mutating func shuffle() {
//http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
guard count > 1 else { return }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { swapAt(index, randomIndex) }
}
}
/// SwifterSwift: Shuffled version of array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffled // return a shuffled version from given array e.g. [2, 4, 1, 3, 5].
///
/// - Returns: the array with its elements shuffled.
public func shuffled() -> [Element] {
var array = self
array.shuffle()
return array
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// SwifterSwift: All indexes of specified item.
///
/// [1, 2, 2, 3, 4, 2, 5].indexes(of 2) -> [1, 2, 5]
/// [1.2, 2.3, 4.5, 3.4, 4.5].indexes(of 2.3) -> [1]
/// ["h", "e", "l", "l", "o"].indexes(of "l") -> [2, 3]
///
/// - Parameter item: item to check.
/// - Returns: an array with all indexes of the given item.
public func indexes(of item: Element) -> [Int] {
var indexes: [Int] = []
for index in startIndex..<endIndex where self[index] == item {
indexes.append(index)
}
return indexes
}
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
public mutating func removeAll(_ item: Element) {
self = filter { $0 != item }
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
public mutating func removeAll(_ items: [Element]) {
guard !items.isEmpty else { return }
self = filter { !items.contains($0) }
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
public mutating func removeDuplicates() {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicatesRemoved() -> [1, 2, 3, 4, 5])
/// ["h", "e", "l", "l", "o"].duplicatesRemoved() -> ["h", "e", "l", "o"])
///
/// - Returns: an array of unique elements.
///
public func duplicatesRemoved() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the property
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: First index of a given item in an array.
///
/// [1, 2, 2, 3, 4, 2, 5].firstIndex(of: 2) -> 1
/// [1.2, 2.3, 4.5, 3.4, 4.5].firstIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].firstIndex(of: "l") -> 2
///
/// - Parameter item: item to check.
/// - Returns: first index of item in array (if exists).
public func firstIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated() where value == item {
return index
}
return nil
}
/// SwifterSwift: Last index of element in array.
///
/// [1, 2, 2, 3, 4, 2, 5].lastIndex(of: 2) -> 5
/// [1.2, 2.3, 4.5, 3.4, 4.5].lastIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].lastIndex(of: "l") -> 3
///
/// - Parameter item: item to check.
/// - Returns: last index of item in array (if exists).
public func lastIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated().reversed() where value == item {
return index
}
return nil
}
}
| mit | 9d8d671917d3c576fb52fe8354a7e3cf | 33.599638 | 173 | 0.596576 | 3.083468 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/DataSources/ApplicationDataManager.swift | 1 | 14725 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
import UIKit
import CoreData
import ReactiveCocoa
class ApplicationDataManager: NSObject {
static let sharedInstance = ApplicationDataManager()
let appDelegate: AppDelegate
let managedContext: NSManagedObjectContext
var jsonVersionNumber: Int
var appVersionNumber: String
dynamic var isDoneLoading: Bool
private override init() {
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext
isDoneLoading = false
// temporarly set to zero for super init
jsonVersionNumber = 0
if let appVersionNumber = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
self.appVersionNumber = appVersionNumber
}
else {
print("Error reading app number")
appVersionNumber = "0"
}
print(appVersionNumber)
super.init()
// check for saved version numbers of json and app
guard let jsonVersionNumber = NSUserDefaults.standardUserDefaults().objectForKey("jsonVersionNumber") as? Int else {
guard let filePath = NSBundle.mainBundle().pathForResource("OfflineData", ofType: "json") else {
return
}
if let jsonDictionary = loadDataFromJsonFile(filePath) {
saveVersionNumber(jsonDictionary)
}
return
}
self.jsonVersionNumber = jsonVersionNumber
}
// MARK: - JSON file management
/**
Method that starts data retrival, sends app and json info to server to see if json needs to be updated
*/
func fetchApplicationDataFromServer() {
let url = "/adapters/demoAdapter/updateCheck/"
let manHelper = ManagerHelper(URLString: url, delegate: self)
manHelper.addProcedureParams("['\(appVersionNumber)', \(jsonVersionNumber)]")
manHelper.getResource()
}
/**
Wipes out Core Data and reloads with json file. This insures a clean setup for demo purposes
*/
func saveJsonFileToCoreData() {
clearAllEntriesFromCoreData()
guard let filePath = NSBundle.mainBundle().pathForResource("OfflineData", ofType: "json") else {
return
}
if let jsonObject = loadDataFromJsonFile(filePath) {
parseJsonObjectIntoCoreData(jsonObject)
}
fetchApplicationDataFromServer()
}
func loadDataFromJsonFile(filePath: String) -> [String: AnyObject]? {
let data = NSData(contentsOfFile: filePath)
if let data = data {
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String: AnyObject]
return jsonData
}
catch {
MQALogger.log("Error loading data from Json file: \(error)", withLevel: MQALogLevelError)
print("Error loading data from Json file: \(error)")
}
}
return nil
}
/**
Method that updates saved json file with new json data
*/
private func saveDataToJsonFile(jsonData: [String: AnyObject]) {
guard let filePath = NSBundle.mainBundle().pathForResource("OfflineData", ofType: "json") else {
return
}
do {
let data = try NSJSONSerialization.dataWithJSONObject(jsonData, options: NSJSONWritingOptions.PrettyPrinted)
data.writeToFile(filePath, atomically: true)
}
catch {
MQALogger.log("Error writing Json to file: \(error)", withLevel: MQALogLevelError)
print("Error writing Json to file: \(error)")
}
}
// MARK: - Version number management
private func saveVersionNumber(jsonObject: [String: AnyObject]) {
guard let vNumber = jsonObject["revision"] as? Int else {
return
}
jsonVersionNumber = vNumber
NSUserDefaults.standardUserDefaults().setValue(jsonVersionNumber, forKey: "jsonVersionNumber")
}
private func isNewVersion(jsonObject: [String: AnyObject]) -> Bool {
return !(jsonObject["isUpToDate"] as! Bool)
}
// MARK: - Create methods for managed objects
func createInvitation(timeToMeet: NSDate, location: POI, recipients: [User], from: Int = UserDataManager.sharedInstance.currentUser.id) {
guard let managedInvitation = createManagedObject("Invitation") else {
return
}
let fromManagedUser = fetchFromCoreData("User", id: from)
// Assume ids are serial
let count = fetchAllFromCoreData("Invitation").count
managedInvitation.setValue(count, forKey: "id")
managedInvitation.setValue(NSDate(), forKey: "timestamp_sent")
managedInvitation.setValue(timeToMeet, forKey: "timestamp_to_meet")
managedInvitation.setValue(fetchFromCoreData("POI", id: location.id), forKey: "location")
// extract ids of recipents for query of core data
let recipientIds = recipients.map({$0.id})
managedInvitation.setValue(Set<NSManagedObject>(fetchFromCoreData("User", ids: recipientIds)), forKey: "recipients")
managedInvitation.setValue(fromManagedUser, forKey: "sender")
saveToCoreData()
let currentUser = UserDataManager.sharedInstance.currentUser
if from == currentUser.id {
UserDataManager.sharedInstance.currentUser.invitationsSent.append(Invitation(managedInvitation: managedInvitation))
}
else {
// if the invite is not sent from the current user, assume current user is a recipient and add to cached user object
UserDataManager.sharedInstance.currentUser.invitationsRecieved.append(Invitation(managedInvitation: managedInvitation))
}
}
func createFavoritedPOI(toFavorite: POI) {
guard let managedFavoritedPOI = createManagedObject("FavoritedPOI") else {
return
}
// assume current user is favoriting the poi
let currentUser = UserDataManager.sharedInstance.currentUser
let currentManagedUser = fetchFromCoreData("User", id: currentUser.id)
// Assume ids are serial
let count = fetchAllFromCoreData("Invitation").count
managedFavoritedPOI.setValue(count, forKey: "id")
managedFavoritedPOI.setValue(false, forKey: "complete")
let managedPOI = fetchFromCoreData("POI", id: toFavorite.id)
managedFavoritedPOI.setValue(managedPOI, forKey: "poi_favorited")
managedFavoritedPOI.setValue(currentManagedUser, forKeyPath: "favorited_by")
saveToCoreData()
currentUser.favorites.append(FavoritedPOI(managedFavoritedPOI: managedFavoritedPOI))
}
func createNotificationFromInvite(invitation: Invitation) -> Notification? {
guard let managedNotification = createManagedObject("Notification") else {
return nil
}
let count = fetchAllFromCoreData("Notification").count
managedNotification.setValue(count, forKey: "id")
managedNotification.setValue(invitation.location.descriptionDetail, forKey: "message")
managedNotification.setValue(false, forKey: "unread")
managedNotification.setValue("invitation", forKey: "type")
managedNotification.setValue(invitation.timestampSent, forKey: "timestamp")
// Find the User that sent this invitation
UserDataManager.sharedInstance.getHostForInvitation(invitation.id) { (user: User?) in
let invitationText = NSLocalizedString(" Has Sent You An Invitation", comment: "")
var title = ""
if let user = user {
title = user.name + invitationText
}
managedNotification.setValue(title, forKey: "title")
}
// Set inverse relationship for new notification
var userSet = Set<NSManagedObject>()
userSet.insert(fetchFromCoreData("User", id: UserDataManager.sharedInstance.currentUser.id)!)
managedNotification.setValue(userSet, forKey: "user")
saveToCoreData()
return Notification(managedNotification: managedNotification)
}
// MARK: - Save From Objects to CoreData
func saveNotification(notification: Notification) {
let managedNotification = fetchFromCoreData("Notification", id: notification.id)
managedNotification?.setValue(notification.unread, forKey: "unread")
saveToCoreData()
}
// MARK: - Remove From CoreData
func clearAllEntriesFromCoreData() {
var fetchArray = [NSFetchRequest]()
fetchArray.append(NSFetchRequest(entityName: "Type"))
fetchArray.append(NSFetchRequest(entityName: "Detail"))
fetchArray.append(NSFetchRequest(entityName: "Notification"))
fetchArray.append(NSFetchRequest(entityName: "ChallengeTask"))
fetchArray.append(NSFetchRequest(entityName: "Challenge"))
fetchArray.append(NSFetchRequest(entityName: "User"))
fetchArray.append(NSFetchRequest(entityName: "POI"))
fetchArray.append(NSFetchRequest(entityName: "FavoritedPOI"))
fetchArray.append(NSFetchRequest(entityName: "Invitation"))
fetchArray.append(NSFetchRequest(entityName: "Group"))
fetchArray.append(NSFetchRequest(entityName: "Ad"))
for fetchRequest in fetchArray {
do {
let entries = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
for entry in entries! {
managedContext.deleteObject(entry)
}
} catch let error as NSError {
MQALogger.log("Error clearing core data entries: \(error)", withLevel: MQALogLevelError)
print("Error clearing core data entries: \(error)")
}
}
saveToCoreData()
}
func removeFavoritedPOI(toRemove: POI) {
let currentUser = UserDataManager.sharedInstance.currentUser
if let favoritedPOIIndex = currentUser.favorites.indexOf({$0.favoritedPOI.id == toRemove.id}) {
let favoritedPOI = currentUser.favorites[favoritedPOIIndex]
let managedFavoritedPOI = fetchFromCoreData("FavoritedPOI", id: favoritedPOI.id)
managedContext.deleteObject(managedFavoritedPOI!)
currentUser.favorites.removeAtIndex(favoritedPOIIndex)
saveToCoreData()
}
}
// MARK: - Utility Functions
func createManagedObject(objectName: String) -> NSManagedObject? {
guard let entity = NSEntityDescription.entityForName(objectName, inManagedObjectContext: managedContext) else {
MQALogger.log("Error in CoreData creating managed object", withLevel: MQALogLevelError)
print("Error in CoreData creating managed object")
return nil
}
return NSManagedObject(entity: entity, insertIntoManagedObjectContext: managedContext)
}
func saveToCoreData() {
do {
try managedContext.save()
}
catch {
MQALogger.log("Error creating managed object: \(error)", withLevel: MQALogLevelError)
print("Error creating managed object: \(error)")
}
}
/**
Convenience method that queries a selected fetch for an id
*/
func fetchFromCoreData(entity: String, id: Int) -> NSManagedObject? {
let predicate = NSPredicate(format: "id = %@", String(id))
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.predicate = predicate
fetchRequest.returnsObjectsAsFaults = false
do {
let fetchResults = try managedContext.executeFetchRequest(fetchRequest)
return fetchResults.first as? NSManagedObject
}
catch {
MQALogger.log("Error fetching from Core Data: \(error)", withLevel: MQALogLevelError)
print("Error fetching from Core Data: \(error)")
return nil
}
}
/**
Convenience method that calls fetchFromCoreData for each id given
*/
func fetchFromCoreData(entity: String, ids: [Int]) -> [NSManagedObject] {
var fetchResults = [NSManagedObject]()
for id in ids {
if let fetchResult = fetchFromCoreData(entity, id: id) {
fetchResults.append(fetchResult)
}
}
return fetchResults
}
/**
Convenience method that fetches all of the given entity
*/
func fetchAllFromCoreData(entity: String) -> [NSManagedObject] {
let fetchRequest = NSFetchRequest(entityName: entity)
do {
let fetchResults = try managedContext.executeFetchRequest(fetchRequest)
if let fetchResults = fetchResults as? [NSManagedObject] {
return fetchResults
}
else {
return [NSManagedObject]()
}
}
catch {
MQALogger.log("Error fetching all Core Data entries: \(error)", withLevel: MQALogLevelError)
print("Error fetching all Core Data entries: \(error)")
return [NSManagedObject]()
}
}
}
// MARK: - Helper Delegate methods
extension ApplicationDataManager: HelperDelegate {
/**
Method to send user data from a WLResponse if the resource request is successful
:param: response WLResponse containing data
*/
func resourceSuccess(response: WLResponse!) {
guard let response = response.getResponseJson() as? [String : AnyObject], let data = response["data"] as? [String: AnyObject] else {
return
}
if(isNewVersion(data)) {
if let blob = data["blob"] as? [String : AnyObject] {
saveDataToJsonFile(blob)
saveVersionNumber(blob)
}
}
}
/**
Method to send error message if the resource request fails
:param: error error message for resource request failure
*/
func resourceFailure(error: String!) {
MQALogger.log("Failure grabbing ApplicationDataManager resource \(error)", withLevel: MQALogLevelError)
print("Failure grabbing ApplicationDataManager resource \(error)")
}
} | epl-1.0 | 5475453d790aeabd2932743764b151b8 | 37.75 | 152 | 0.638481 | 5.508418 | false | false | false | false |
ethanal/Nimbus | NimbusMenuBarApp/Nimbus/Nimbus/AppDelegate.swift | 1 | 2386 | //
// AppDelegate.swift
// Nimbus
//
// Created by Ethan Lowman on 7/25/14.
// Copyright (c) 2014 Ethanal. All rights reserved.
//
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, NSMetadataQueryDelegate {
var statusView = StatusItemView()
var prefs = PreferencesManager()
var api = APIClient()
var sw: ScreenshotWatcher?
override init() {
super.init()
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
sw = ScreenshotWatcher(uploadFileCallback: uploadFile);
sw!.startWatchingPath(screenCaptureLocation())
}
func screenCaptureLocation() -> String {
let screenCapturePrefs: NSDictionary? = NSUserDefaults.standardUserDefaults().persistentDomainForName("com.apple.screencapture")
let location: String? = screenCapturePrefs?.valueForKey("location")?.stringByExpandingTildeInPath as String?
if let loc = location {
return loc.hasSuffix("/") ? loc : (loc + "/")
}
return ("~/Desktop" as NSString).stringByExpandingTildeInPath + "/"
}
func uploadFile(fileData: NSData!, filename: String!) {
print(filename);
// NSMetadataItem *metadata = NSMetadataItem(URL: filename)
// BOOL isScreenshot = [[metadata valueForAttribute:@"kMDItemIsScreenCapture"] integerValue] == 1;
statusView.status = .Working
api.addFile(fileData, filename: filename, successCallback: {(shareURL: NSURL!) -> Void in
let pb = NSPasteboard.generalPasteboard()
pb.clearContents()
pb.writeObjects([shareURL.absoluteString])
self.statusView.status = .Success
}, errorCallback: {() -> Void in
print("Error uploading file")
self.statusView.status = .Error
})
}
func uploadLink(link: NSURL) {
statusView.status = .Working
api.addLink(link, successCallback: {(shareURL: NSURL!) -> Void in
let pb = NSPasteboard.generalPasteboard()
pb.clearContents()
pb.writeObjects([shareURL.absoluteString])
self.statusView.status = .Success
}, errorCallback: {() -> Void in
print("Error uploading link")
self.statusView.status = .Error
})
}
}
| mit | 676955228c814f31e03fb8f3e12d7161 | 34.088235 | 136 | 0.615256 | 5.164502 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/ViewControllers/ErrorViewController.swift | 1 | 4785 | //
// ErrorViewController.swift
// StripeIdentity
//
// Created by Mel Ludowise on 11/4/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
@_spi(STP) import StripeUICore
import UIKit
final class ErrorViewController: IdentityFlowViewController {
enum Model {
case error(Error)
case inputError(StripeAPI.VerificationPageDataRequirementError)
}
private let errorView = ErrorView()
let model: Model
init(
sheetController: VerificationSheetControllerProtocol,
error model: Model,
filePath: StaticString = #filePath,
line: UInt = #line
) {
self.model = model
super.init(sheetController: sheetController, analyticsScreenName: .error)
logError(filePath: filePath, line: line)
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
errorView.configure(
with: .init(
titleText: model.title ?? String.Localized.error,
bodyText: model.body
)
)
// This error screen will be the first screen in the navigation
// stack if the only screen before it is the loading screen. The loading
// screen will be removed from the stack after the animation has finished.
let isFirstViewController =
navigationController?.viewControllers.first === self
|| (navigationController?.viewControllers.first is LoadingViewController
&& navigationController?.viewControllers.stp_boundSafeObject(at: 1) === self)
configure(
backButtonTitle: String.Localized.error,
viewModel: .init(
headerViewModel: nil,
contentViewModel: .init(view: errorView, inset: .zero),
buttons: [
.init(
text: model.buttonText(
isFirstViewController: isFirstViewController
),
state: .enabled,
isPrimary: true,
didTap: { [weak self] in
self?.didTapButton()
}
)
]
)
)
}
}
extension ErrorViewController {
fileprivate func didTapButton() {
// If this is the only view in the stack, dismiss the nav controller
guard navigationController?.viewControllers.first !== self else {
dismiss(animated: true, completion: nil)
return
}
switch model {
case .inputError(let inputError):
if sheetController?.flowController.canPopToScreen(withField: inputError.requirement)
== true
{
// Attempt to go back to the view that has the error
sheetController?.flowController.popToScreen(
withField: inputError.requirement,
shouldResetViewController: true
)
} else {
// Go back to the previous view
navigationController?.popViewController(animated: true)
}
case .error:
// Go back to the previous view
navigationController?.popViewController(animated: true)
}
}
fileprivate func logError(filePath: StaticString, line: UInt) {
guard case .error(let error) = model else {
return
}
sheetController?.analyticsClient.logGenericError(
error: error,
filePath: filePath,
line: line
)
}
}
extension ErrorViewController.Model {
var title: String? {
switch self {
case .error:
return nil
case .inputError(let inputError):
return inputError.title
}
}
var body: String {
switch self {
case .error(let error):
return error.localizedDescription
case .inputError(let inputError):
return inputError.body
}
}
func buttonText(isFirstViewController: Bool) -> String {
switch self {
case .inputError(let inputError):
guard let buttonText = inputError.backButtonText else {
fallthrough
}
return buttonText
case .error:
if isFirstViewController {
return String.Localized.close
} else {
return STPLocalizedString(
"Go Back",
"Button to go back to the previous screen"
)
}
}
}
}
| mit | f6ee4e6c769b028b25cd898e83dfd40e | 29.278481 | 96 | 0.552258 | 5.562791 | false | false | false | false |
JDGan/JDGFrameworks | JDGFrameworks/Classes/Base/JDGLog.swift | 1 | 7145 | //
// JDGLog.swift
// JDGFrameworks
//
// Created by JDG on 2020/12/25.
// Copyright © 2020年 JDG. All rights reserved.
//
import Foundation
public class JDGLog {
/// 单例创建的Log配置对象,默认level:information,space:all
public static let `default` = JDGLog()
private init() {
self.displayLevel = .information
self.displaySpace = []
self._logDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
}
/// 默认时间格式为:yyyy-MM-dd HH:mm:ss.SSS
public var logDateFormatter : String {
set {
_logDateFormatter.dateFormat = newValue
}
get {
return _logDateFormatter.dateFormat
}
}
/// 设置需要输出的最高Level
public var displayLevel : Level
/// 设置需要输出的的Space,当数组为空时以及包含all时,默认为all
public var displaySpace : [Space] {
didSet {
var containAll = false
_spaceNames = displaySpace.reduce([]) { (arr, obj) -> [String] in
if containAll {return []}
if case .all = obj {
containAll = true
return []
}
var array : [String] = []
array.append(contentsOf: arr)
if case .specific(let name) = obj {
array.append(name)
}
return array
}
}
}
/// 需要输出的Space的文本数组,在displaySpace修改后会自动更新
fileprivate var _spaceNames : [String] = []
/// 日志输出的时间格式器
private let _logDateFormatter = DateFormatter()
/// 输出日志的主方法
/// - Parameters:
/// - items: 本次需要输出的对象数组
/// - level: 本次输出的等级,如果大于需要输出的level,则会忽略掉
/// - space: 本次输出所属的space,如果不在需要输出的space中,则会忽略掉
/// - style: 本次输出的方式,自定义方式需要满足JDGLogCustomizeProtocol
/// - time: 本次输出的时间,默认为当前时间,nil时不会输出
/// - file: 调用本次输出的代码所在文件,nil时不会输出
/// - selector: 调用本次输出的代码所在方法,nil时不会输出
/// - line: 调用本次输出的代码所在文件的行数,nil时不会输出
public func logOutput(_ items: CustomStringConvertible...
, level: Level
, space: Space
, style: Style
, time: Date? = Date()
, file: String? = #file
, selector: String? = #function
, line: Int? = #line
) {
// 如果日志level超过需要显示的level,忽略该条日志
guard level.rawValue <= displayLevel.rawValue else {return}
guard displaySpace.containSpace(space) else {return}
var logToShow = ""
if let t = time {
logToShow += _logDateFormatter.string(from: t)
logToShow += " "
}
// 判断是否需要显示文件
if let f = file {
logToShow += "\(f.components(separatedBy: "/").last ?? "NOT FOUND") "
}
// 判断是否需要显示方法
if let s = selector {
logToShow += "[\(s.components(separatedBy: "(").first ?? "NOT FOUND")] "
}
// 判断是否需要显示行数
if let l = line {
logToShow += "(\(l)) "
}
// 遍历组装输出的日志
logToShow += items.reduce(""){ (result, obj) -> String in
return result + obj.description
}
// 根据style实现输出
switch style {
case .customize(let customizeStyle):
customizeStyle.showJDGLogOutput(logToShow)
case .file(let path):
do {
try logToShow.write(toFile: path, atomically: true, encoding: .utf8)
} catch let err {
print(err.localizedDescription)
}
case .alert:
UIAlertController(title: nil, message: nil, preferredStyle: .alert).showJDGLogOutput(logToShow)
default:
print(logToShow)
}
}
}
extension JDGLog {
public enum Level : Int {
case off = 0
case critical
case error
case warning
case information
case trace
case verbose
}
public enum Space {
case all
case specific(name:String)
}
public enum Style {
case console
case alert
case file(path:String)
case customize(customizeStyle: JDGLogUICustomizeProtocol)
}
}
extension Array where Element == JDGLog.Space {
fileprivate func containSpace(_ target: JDGLog.Space) -> Bool {
var contain = false
// spaceNames为空时,默认为all
if JDGLog.default._spaceNames.count == 0 {
contain = true
} else {
if case .specific(let name) = target {
contain = JDGLog.default._spaceNames.contains(name)
} else {
contain = false
}
}
return contain
}
}
public func JLError(_ items: CustomStringConvertible...
, level: JDGLog.Level = .error
, space: JDGLog.Space = .all
, style: JDGLog.Style = .console
, time: Date? = Date()
, file: String? = #file
, selector: String? = #function
, line: Int? = #line) {
let logToShow = items.reduce(""){ (result, obj) -> String in
return result + obj.description
}
JDGLog.default.logOutput(logToShow, level: level, space: space, style: style, time: time, file: file, selector: selector, line: line)
}
public func JLMessage(_ items: CustomStringConvertible...
, level: JDGLog.Level = .information
, space: JDGLog.Space = .all
, style: JDGLog.Style = .console
, time: Date? = Date()
, file: String? = #file
, selector: String? = #function
, line: Int? = #line) {
let logToShow = items.reduce(""){ (result, obj) -> String in
return result + obj.description
}
JDGLog.default.logOutput(logToShow, level: level, space: space, style: style, time: time, file: file, selector: selector, line: line)
}
public protocol JDGLogUICustomizeProtocol {
func showJDGLogOutput(_ logToShow: String)
}
extension UIAlertController : JDGLogUICustomizeProtocol {
public func showJDGLogOutput(_ logToShow: String) {
message = logToShow
addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) in
self.dismiss(animated: true, completion: nil)
}))
UIApplication.shared.keyWindow?.rootViewController?.present(self, animated: true, completion: nil)
}
}
| mit | c7fbaedc6a41787f772d9f379978ea3f | 32.045685 | 137 | 0.536406 | 4.141221 | false | false | false | false |
oisdk/Rational | Sources/Source.swift | 1 | 3487 | infix operator /% {associativity right precedence 100 }
/// A rational number type, which stores the numerator and denominator
/// for a fraction.
///
/// The only exposed initialiser for the struct automatically simplifies
/// before storing. The user cannot manually adjust the numerator and
/// denominator. This ensures that the fraction is always stored in its
/// simplest form:
///
/// ```swift
/// String(6 /% 8) == 3/4
/// ```
///
/// The numerator is stored as the maximum-sized signed integer type,
/// and the denominator is stored as the maximum-sized unsigned integer
/// type.
public struct Rational {
public let num: IntMax
public let den: UIntMax
}
extension Rational {
public init(_ num: IntMax, _ den: UIntMax) {
let unum = UIntMax(abs(num))
let g = gcd(unum,den)
let n = unum / g
self.num = num < 0 ? -IntMax(n) : IntMax(n)
self.den = den / g
}
public init(_ n: Int) {
num = IntMax(n)
den = 1
}
}
public func /%(lhs: IntMax, rhs: UIntMax) -> Rational {
return Rational(lhs,rhs)
}
public func /%(lhs: Int, rhs: Int) -> Rational {
return rhs < 0 ? -IntMax(lhs) /% UIntMax(-rhs) : IntMax(lhs) /% UIntMax(rhs)
}
private func gcd<I: protocol<IntegerArithmeticType, IntegerLiteralConvertible>>(x: I, _ y: I) -> I {
var (a,b) = (x,y)
while b != 0 { (a,b) = (b,a%b) }
return a
}
extension Rational: CustomStringConvertible {
public var description: String {
if den == 1 { return String(num) }
return String(num) + "/" + String(den)
}
}
extension Rational: Equatable {}
public func ==(lhs: Rational, rhs: Rational) -> Bool {
return lhs.num == rhs.num && lhs.den == rhs.den
}
public func +(lhs: Rational, rhs: Rational) -> Rational {
let g = gcd(lhs.den, rhs.den)
let d = (lhs.den * rhs.den) / g
return (lhs.num * IntMax(rhs.den/g) + rhs.num * IntMax(lhs.den/g)) /% d
}
public func *(lhs: Rational, rhs: Rational) -> Rational {
return (lhs.num*rhs.num) /% (lhs.den*rhs.den)
}
public func /(lhs: Rational, rhs: Rational) -> Rational {
if rhs < 0 { return -lhs / -rhs }
return (lhs.num*IntMax(rhs.den)) /% (lhs.den*UIntMax(rhs.num))
}
public func -(lhs: Rational, rhs: Rational) -> Rational {
return lhs + -rhs
}
extension Rational: Comparable {}
public func <(lhs: Rational, rhs: Rational) -> Bool {
switch (lhs.num < 0, rhs.num < 0) {
case (true ,true ): return -rhs < -lhs
case (false,true ): return false
case (true ,false): return true
case (false,false): return UIntMax(lhs.num) * rhs.den < UIntMax(rhs.num) * lhs.den
}
}
extension Rational: IntegerLiteralConvertible {
public init(integerLiteral value: IntMax) {
self.init(num: value, den: 1)
}
}
extension Rational: SignedNumberType {}
public prefix func -(x: Rational) -> Rational {
return Rational(num: -x.num, den: x.den)
}
extension Rational: Strideable {
public func distanceTo(other: Rational) -> Rational {
return other - self
}
public func advancedBy(n: Rational) -> Rational {
return self + n
}
}
extension Rational {
/// The `Double` representation of `self`.
public var double: Double {
return Double(num) / Double(den)
}
}
extension Rational {
/// The reciprocal of self
///
/// ```swift
/// String((3 /% 4).reciprocal) == 4/3
/// ```
public var reciprocal: Rational {
if num < 0 {
return Rational(num: -IntMax(den), den: UIntMax(abs(num)))
} else {
return Rational(num: IntMax(den), den: UIntMax(num))
}
}
}
| mit | 41d30f9161a708364d8e6c7772393c9a | 23.907143 | 100 | 0.636937 | 3.340038 | false | false | false | false |
plivesey/SwiftGen | Pods/Stencil/Sources/Expression.swift | 1 | 6880 | protocol Expression: CustomStringConvertible {
func evaluate(context: Context) throws -> Bool
}
protocol InfixOperator: Expression {
init(lhs: Expression, rhs: Expression)
}
protocol PrefixOperator: Expression {
init(expression: Expression)
}
final class StaticExpression: Expression, CustomStringConvertible {
let value: Bool
init(value: Bool) {
self.value = value
}
func evaluate(context: Context) throws -> Bool {
return value
}
var description: String {
return "\(value)"
}
}
final class VariableExpression: Expression, CustomStringConvertible {
let variable: Variable
init(variable: Variable) {
self.variable = variable
}
var description: String {
return "(variable: \(variable.variable))"
}
/// Resolves a variable in the given context as boolean
func resolve(context: Context, variable: Variable) throws -> Bool {
let result = try variable.resolve(context)
var truthy = false
if let result = result as? [Any] {
truthy = !result.isEmpty
} else if let result = result as? [String:Any] {
truthy = !result.isEmpty
} else if let result = result as? Bool {
truthy = result
} else if let result = result as? String {
truthy = !result.isEmpty
} else if let value = result, let result = toNumber(value: value) {
truthy = result > 0
} else if result != nil {
truthy = true
}
return truthy
}
func evaluate(context: Context) throws -> Bool {
return try resolve(context: context, variable: variable)
}
}
final class NotExpression: Expression, PrefixOperator, CustomStringConvertible {
let expression: Expression
init(expression: Expression) {
self.expression = expression
}
var description: String {
return "not \(expression)"
}
func evaluate(context: Context) throws -> Bool {
return try !expression.evaluate(context: context)
}
}
final class OrExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) or \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
let lhs = try self.lhs.evaluate(context: context)
if lhs {
return lhs
}
return try rhs.evaluate(context: context)
}
}
final class AndExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) and \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
let lhs = try self.lhs.evaluate(context: context)
if !lhs {
return lhs
}
return try rhs.evaluate(context: context)
}
}
class EqualityExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
required init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) == \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
if let lhs = lhs as? VariableExpression, let rhs = rhs as? VariableExpression {
let lhsValue = try lhs.variable.resolve(context)
let rhsValue = try rhs.variable.resolve(context)
if let lhs = lhsValue, let rhs = rhsValue {
if let lhs = toNumber(value: lhs), let rhs = toNumber(value: rhs) {
return lhs == rhs
} else if let lhs = lhsValue as? String, let rhs = rhsValue as? String {
return lhs == rhs
} else if let lhs = lhsValue as? Bool, let rhs = rhsValue as? Bool {
return lhs == rhs
}
} else if lhsValue == nil && rhsValue == nil {
return true
}
}
return false
}
}
class NumericExpression: Expression, InfixOperator, CustomStringConvertible {
let lhs: Expression
let rhs: Expression
required init(lhs: Expression, rhs: Expression) {
self.lhs = lhs
self.rhs = rhs
}
var description: String {
return "(\(lhs) \(op) \(rhs))"
}
func evaluate(context: Context) throws -> Bool {
if let lhs = lhs as? VariableExpression, let rhs = rhs as? VariableExpression {
let lhsValue = try lhs.variable.resolve(context)
let rhsValue = try rhs.variable.resolve(context)
if let lhs = lhsValue, let rhs = rhsValue {
if let lhs = toNumber(value: lhs), let rhs = toNumber(value: rhs) {
return compare(lhs: lhs, rhs: rhs)
}
}
}
return false
}
var op: String {
return ""
}
func compare(lhs: Number, rhs: Number) -> Bool {
return false
}
}
class MoreThanExpression: NumericExpression {
override var op: String {
return ">"
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs > rhs
}
}
class MoreThanEqualExpression: NumericExpression {
override var op: String {
return ">="
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs >= rhs
}
}
class LessThanExpression: NumericExpression {
override var op: String {
return "<"
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs < rhs
}
}
class LessThanEqualExpression: NumericExpression {
override var op: String {
return "<="
}
override func compare(lhs: Number, rhs: Number) -> Bool {
return lhs <= rhs
}
}
class InequalityExpression: EqualityExpression {
override var description: String {
return "(\(lhs) != \(rhs))"
}
override func evaluate(context: Context) throws -> Bool {
return try !super.evaluate(context: context)
}
}
func toNumber(value: Any) -> Number? {
if let value = value as? Float {
return Number(value)
} else if let value = value as? Double {
return Number(value)
} else if let value = value as? UInt {
return Number(value)
} else if let value = value as? Int {
return Number(value)
} else if let value = value as? Int8 {
return Number(value)
} else if let value = value as? Int16 {
return Number(value)
} else if let value = value as? Int32 {
return Number(value)
} else if let value = value as? Int64 {
return Number(value)
} else if let value = value as? UInt8 {
return Number(value)
} else if let value = value as? UInt16 {
return Number(value)
} else if let value = value as? UInt32 {
return Number(value)
} else if let value = value as? UInt64 {
return Number(value)
} else if let value = value as? Number {
return value
} else if let value = value as? Float64 {
return Number(value)
} else if let value = value as? Float32 {
return Number(value)
}
return nil
}
| mit | 449c96fcfbca7ded36e43d2f379c5431 | 21.933333 | 83 | 0.638372 | 4.144578 | false | false | false | false |
pyconjp/pyconjp-ios | PyConJP/ViewController/More/MoreListViewController.swift | 1 | 2949 | //
// MoreListViewController.swift
// PyConJP
//
// Created by Yutaro Muta on 3/7/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
import SafariServices
class MoreListViewController: UITableViewController {
private lazy var dataStore: MoreListDataStore = MoreListDataStore { [weak self] in
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
// MARK: - Table View Controller DataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return dataStore.sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataStore.sections[section].rows.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataStore.sections[section].title
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MoreCell", for: indexPath)
cell.textLabel?.text = dataStore.sections[indexPath.section].rows[indexPath.row].title
return cell
}
// MARK: - Table View Controller Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = dataStore.sections[indexPath.section].rows[indexPath.row]
switch row {
case .whatsPyConJP, .codeOfConduct, .summary, .license, .staffList:
guard let identifier = row.identifier, let viewController = self.storyboard?.instantiateViewController(withIdentifier: identifier) else { return }
self.navigationController?.pushViewController(viewController, animated: true)
case .participantsInformation, .sponsor, .repository:
guard let url = row.url else { return }
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true, completion: nil)
case .survey(let url):
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true, completion: nil)
case .conferenceMap:
let mapListViewController = MapListViewController.build()
self.navigationController?.pushViewController(mapListViewController, animated: true)
case .sprintMap:
let mapViewController = MapViewController.build(venue: MapViewController.Venue.microsoft)
self.navigationController?.pushViewController(mapViewController, animated: true)
case .feedback:
guard let urlSheme = row.urlSheme else { return }
UIApplication.shared.open(urlSheme, options: [:], completionHandler: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
| mit | 2194dc0379b253586336515ed64adc5d | 42.352941 | 158 | 0.688602 | 5.236234 | false | false | false | false |
kzin/swift-testing | swift-testing/swift-testing/LoginView.swift | 1 | 4039 | //
// LoginView.swift
// swift-testing
//
// Created by Rodrigo Cavalcante on 03/03/17.
// Copyright © 2017 Rodrigo Cavalcante. All rights reserved.
//
import UIKit
import Cartography
class LoginView: UIView {
var tapLoginButton: ((_ username: String, _ password: String) -> ())?
let textLabel = { () -> UILabel in
let label = UILabel()
label.text = "Formulário de login"
label.font = UIFont.systemFont(ofSize: 15.0)
label.isHidden = false
return label
}()
let userNameTextField = { () -> UITextField in
let textField = UITextField()
textField.placeholder = "Username"
textField.accessibilityLabel = "Username"
textField.borderStyle = .roundedRect
textField.font = UIFont.systemFont(ofSize: 15.0)
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
textField.autocapitalizationType = .none
textField.isHidden = false
return textField
}()
let passwordTextField = { () -> UITextField in
let textField = UITextField()
textField.placeholder = "Password"
textField.accessibilityLabel = "Password"
textField.font = UIFont.systemFont(ofSize: 15.0)
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
textField.autocapitalizationType = .none
textField.borderStyle = .roundedRect
textField.isSecureTextEntry = true
textField.isHidden = false
return textField
}()
let loginButton = { () -> UIButton in
let button = UIButton()
button.accessibilityLabel = "Login"
button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
button.setTitle("Login", for: .normal)
button.setTitleColor(.gray, for: .normal)
button.isHidden = false
return button
}()
init() {
super.init(frame: CGRect.zero)
build()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func build() {
buildViewHierarchy()
buildConstrains()
setup()
}
func buildViewHierarchy() {
addSubview(textLabel)
addSubview(userNameTextField)
addSubview(passwordTextField)
addSubview(loginButton)
}
func buildConstrains() {
let verticalMargin: CGFloat = 16.0
let horizontalMargin: CGFloat = 8.0
constrain(self, textLabel, userNameTextField, passwordTextField, loginButton) { view, label, username, password, login in
label.top == view.top + verticalMargin
label.left == view.left + horizontalMargin
label.right == view.right - horizontalMargin
username.top == label.bottom + verticalMargin
username.left == label.left
username.right == label.right
password.top == username.baseline + 21.0
password.left == username.left
password.right == username.right
login.top == password.bottom + verticalMargin
login.left == password.left
login.right == password.right
login.bottom == view.bottom - verticalMargin
}
}
func setup() {
self.loginButton.addTarget(self, action: #selector(tapLogin), for: .touchUpInside)
self.backgroundColor = .white
}
func tapLogin() {
guard let username = userNameTextField.text, let password = passwordTextField.text else {
return
}
self.tapLoginButton?(username, password)
}
func textFieldDidChange(_ textField: UITextField) {
if self.userNameTextField.isEmpty() || self.passwordTextField.isEmpty() {
self.loginButton.isHidden = true
} else {
self.loginButton.isHidden = false
}
}
}
| mit | 860d8dd7739b964806903d4ea0ef07af | 30.539063 | 129 | 0.599207 | 5.142675 | false | false | false | false |
shaps80/InkKit | Pod/Classes/Platform.swift | 1 | 1604 | //
// CGContext+Extension.swift
// InkKit
//
// Created by Shaps Benkau on 03/10/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
#if os(OSX)
import AppKit
public typealias Image = NSImage
public typealias BezierPath = NSBezierPath
public typealias EdgeInsets = NSEdgeInsets
public typealias Screen = NSScreen
public typealias Font = NSFont
extension NSImage {
public func pngRepresentation() -> Data? {
return NSBitmapImageRep(data: tiffRepresentation!)?.representation(using: .png, properties: [:])
}
public func jpgRepresentation(quality: CGFloat) -> Data? {
return NSBitmapImageRep(data: tiffRepresentation!)?.representation(using: .jpeg, properties: [NSBitmapImageRep.PropertyKey.compressionFactor: quality])
}
}
#else
import UIKit
public typealias Image = UIImage
public typealias EdgeInsets = UIEdgeInsets
public typealias BezierPath = UIBezierPath
public typealias Screen = UIScreen
public typealias Font = UIFont
extension UIImage {
public func pngRepresentation() -> Data? {
return UIImagePNGRepresentation(self)
}
public func jpgRepresentation(quality: CGFloat) -> Data? {
return UIImageJPEGRepresentation(self, quality)
}
}
#endif
extension CGContext {
public static var current: CGContext? {
#if os(OSX)
return NSGraphicsContext.current!.cgContext
#else
return UIGraphicsGetCurrentContext()
#endif
}
}
| mit | ead11777b7c08f5fa33b91a60e722422 | 28.145455 | 163 | 0.653774 | 5.325581 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01109-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 1 | 942 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct e : d {
class a<f : b, g : b where f.d == g> {
}
protocol b {
}
struct c<h : b> : b {
}
func a(b: Int = 0) {
}
let c = a
func a<T>() {
enum b {
}
}
struct A<T> {
}
func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? {
for (mx : e?) in c {
}
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
protocol a : a {
}
class A : A {
}
class B : C {
}
protocol A {
}
struct B<T : A> {
}
protocol C {
}
struct D : C {
func g<T where T.E == F>(f: B<T>) {
}
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a
| apache-2.0 | e9e4d9d48d869afa55c769314d717b43 | 17.470588 | 79 | 0.605096 | 2.616667 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | watchOS2/Heart Rate/v1 Health Watch Example/HealthWatchExample WatchKit Extension/InterfaceController.swift | 1 | 1471 | //
// InterfaceController2.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/1/16.
// Copyright © 2016 LC. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var table: WKInterfaceTable!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
print("awakeWithContext \(self)")
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
self.tableSetup()
print("willActivate \(self)")
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
print("didDeactivate \(self)")
}
//MARK: - Table setup
func tableSetup() {
let options = ["stream", "request"]
self.table.setRowTypes(options)
}//eom
override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int)
{
if rowIndex == 0
{
self.pushControllerWithName("streamController", context: nil)
}
else if rowIndex == 1
{
self.pushControllerWithName("requestController", context: nil)
}
}//eom
}
| mit | 9ac599e1d337308367f4f25e8c02e381 | 21.96875 | 90 | 0.6 | 5.194346 | false | false | false | false |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 6.可以很酷的转场动画/1.cook/1.Cook/Cook/PopAnimator.swift | 1 | 1253 | //
// PopAnimator.swift
// Cook
//
// Created by Dariel on 16/7/25.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
// 遵守协议
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
// 动画持续时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
//
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 获得容器
let containerView = transitionContext.containerView()!
// 获得目标view
// viewForKey 获取新的和老的控制器的view
// viewControllerForKey 获取新的和老的控制器
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
containerView.addSubview(toView)
toView.alpha = 0.0
UIView.animateWithDuration(duration, animations: { () -> Void in
toView.alpha = 1.0
}) { (_) -> Void in
// 转场动画完成
transitionContext.completeTransition(true)
}
}
}
| mit | 538bd4b54e5ed9e8f03d6d442834d9dd | 24.777778 | 105 | 0.624138 | 5.272727 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Splitting Nodes.xcplaygroundpage/Contents.swift | 1 | 1130 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Splitting Nodes
//: ### All nodes in AudioKit can have multiple destinations, the only caveat is that all of the destinations do have to eventually be mixed back together and none of the parallel signal paths can have any time stretching.
import XCPlayground
import AudioKit
import AVFoundation
//: Prepare the source audio player
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
//: The following nodes are both acting on the original player node
var ringMod = AKRingModulator(player)
var delay = AKDelay(player)
delay.time = 0.01
delay.feedback = 0.8
delay.dryWetMix = 1
//: Any number of inputs can be equally summed into one output, including the original player, allowing us to create dry/wet mixes even for effects that don't have that property by default
let mixer = AKMixer(player, delay)
AudioKit.output = mixer
AudioKit.start()
player.play()
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | ed2cb7ff88e06221b650fb55b8d2c83a | 34.3125 | 222 | 0.742478 | 3.937282 | false | false | false | false |
karthik-ios-dev/MySwiftExtension | Pod/Classes/Array-Extension.swift | 1 | 2603 | //
// Array-Extension.swift
// DateHelper
//
// Created by Karthik on 18/11/15.
// Copyright © 2015 Karthik. All rights reserved.
//
import UIKit
//MARK:My Extension
public extension Array{
var isEmpty : Bool{
return self.isEmpty
}
mutating func addElements(new : Element){
self.append(new)
}
mutating func removeLastObj() -> Element{
return self.removeLast()
}
mutating func removeFirstObj() ->Element{
return self.removeFirst()
}
mutating func flushArray(){
// will give empty Arr
return self.removeAll()
}
func joinArrayBySeperator(separator:String) -> String {
return self.map({ String($0) }).joinWithSeparator(separator)
}
}
// MARK:ARRAY protocol extension
public extension Array where Element: Equatable {
func removeObject(object: Element) -> [Element] {
return filter { $0 != object }
}
func removeObjectsInArray(objects : [Element]){
for obj in objects{
self.removeObject(obj)
}
}
func containsObj(obj : Element)-> Bool{
return self.contains(obj) == true
}
func findObj (obj: Element) -> Bool {
return (indexOf(obj) != nil) ? true : false
}
func contains<T where T : Equatable>(object: T) -> Bool {
return self.filter({$0 as? T == object}).count > 0
}
}
extension Array where Element : StringType{
// ["test","123"] -> "test123"
func combineAllStrInArr() -> String {
return String(self.map{$0.characters}.reduce(String.CharacterView(), combine: {$0 + $1}))
}
}
//MARK:Github Extension
public extension Array {
/// Filter array, deleting all objects, that do not match block
///
/// - parameter block: matching block.
mutating func ck_performSelect(block: (Element) -> Bool) {
var indexes = [Int]()
for (index,element) in self.enumerate() {
if !block(element) { indexes.append(index)}
}
self.removeAtIndexes(indexes)
}
/// Filter array, deleting all objects, that match block
///
/// - parameter block: matching block
mutating func ck_performReject(block: (Element) -> Bool) {
return self.ck_performSelect({ (element) -> Bool in
return !block(element)
})
}
}
private extension Array
{
mutating func removeAtIndexes( indexes: [Int]) {
for index in indexes.sort(>) {
self.removeAtIndex(index)
}
}
}
| mit | 1d025b2d74e199462263f7b82ff89064 | 21.431034 | 97 | 0.579939 | 4.251634 | false | false | false | false |
Rochester-Ting/XMLY | XMLY/Pods/DGElasticPullToRefresh/DGElasticPullToRefresh/DGElasticPullToRefreshLoadingViewCircle.swift | 12 | 4407 | /*
The MIT License (MIT)
Copyright (c) 2015 Danil Gontovnik
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
// MARK: -
// MARK: (CGFloat) Extension
public extension CGFloat {
public func toRadians() -> CGFloat {
return (self * CGFloat(M_PI)) / 180.0
}
public func toDegrees() -> CGFloat {
return self * 180.0 / CGFloat(M_PI)
}
}
// MARK: -
// MARK: DGElasticPullToRefreshLoadingViewCircle
open class DGElasticPullToRefreshLoadingViewCircle: DGElasticPullToRefreshLoadingView {
// MARK: -
// MARK: Vars
fileprivate let kRotationAnimation = "kRotationAnimation"
fileprivate let shapeLayer = CAShapeLayer()
fileprivate lazy var identityTransform: CATransform3D = {
var transform = CATransform3DIdentity
transform.m34 = CGFloat(1.0 / -500.0)
transform = CATransform3DRotate(transform, CGFloat(-90.0).toRadians(), 0.0, 0.0, 1.0)
return transform
}()
// MARK: -
// MARK: Constructors
public override init() {
super.init(frame: .zero)
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = tintColor.cgColor
shapeLayer.actions = ["strokeEnd" : NSNull(), "transform" : NSNull()]
shapeLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
layer.addSublayer(shapeLayer)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Methods
override open func setPullProgress(_ progress: CGFloat) {
super.setPullProgress(progress)
shapeLayer.strokeEnd = min(0.9 * progress, 0.9)
if progress > 1.0 {
let degrees = ((progress - 1.0) * 200.0)
shapeLayer.transform = CATransform3DRotate(identityTransform, degrees.toRadians(), 0.0, 0.0, 1.0)
} else {
shapeLayer.transform = identityTransform
}
}
override open func startAnimating() {
super.startAnimating()
if shapeLayer.animation(forKey: kRotationAnimation) != nil { return }
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = CGFloat(2 * M_PI) + currentDegree()
rotationAnimation.duration = 1.0
rotationAnimation.repeatCount = Float.infinity
rotationAnimation.isRemovedOnCompletion = false
rotationAnimation.fillMode = kCAFillModeForwards
shapeLayer.add(rotationAnimation, forKey: kRotationAnimation)
}
override open func stopLoading() {
super.stopLoading()
shapeLayer.removeAnimation(forKey: kRotationAnimation)
}
fileprivate func currentDegree() -> CGFloat {
return shapeLayer.value(forKeyPath: "transform.rotation.z") as! CGFloat
}
override open func tintColorDidChange() {
super.tintColorDidChange()
shapeLayer.strokeColor = tintColor.cgColor
}
// MARK: -
// MARK: Layout
override open func layoutSubviews() {
super.layoutSubviews()
shapeLayer.frame = bounds
let inset = shapeLayer.lineWidth / 2.0
shapeLayer.path = UIBezierPath(ovalIn: shapeLayer.bounds.insetBy(dx: inset, dy: inset)).cgPath
}
}
| mit | 6e2e7c3f9e3dbaa09974e05dd0fa662e | 30.934783 | 109 | 0.66644 | 4.811135 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.