id
int64
0
3.46k
description
stringlengths
5
3.38k
readme
stringlengths
6
512k
โŒ€
100
Flexible framework for workflow and decision automation with BPMN and DMN. Integration with Spring, Spring Boot, CDI.
# Camunda Platform 7 - The open source BPMN platform [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.camunda.bpm/camunda-parent/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.camunda.bpm/camunda-parent) [![camunda manual latest](https://img.shields.io/badge/manual-latest-brown.svg)](https://docs.camunda.org/manual/latest/) [![License](https://img.shields.io/github/license/camunda/camunda-bpm-platform?color=blue&logo=apache)](https://github.com/camunda/camunda-bpm-platform/blob/master/LICENSE) [![Forum](https://img.shields.io/badge/forum-camunda-green)](https://forum.camunda.org/) Camunda Platform 7 is a flexible framework for workflow and process automation. It's core is a native BPMN 2.0 process engine that runs inside the Java Virtual Machine. It can be embedded inside any Java application and any Runtime Container. It integrates with Java EE 6 and is a perfect match for the Spring Framework. On top of the process engine, you can choose from a stack of tools for human workflow management, operations & monitoring. - Web Site: https://www.camunda.org/ - Getting Started: https://docs.camunda.org/get-started/ - User Forum: https://forum.camunda.org/ - Issue Tracker: https://github.com/camunda/camunda-bpm-platform/issues - Contribution Guidelines: https://camunda.org/contribute/ ## Components Camunda Platform 7 provides a rich set of components centered around the BPM lifecycle. #### Process Implementation and Execution - Camunda Engine - The core component responsible for executing BPMN 2.0 processes. - REST API - The REST API provides remote access to running processes. - Spring, CDI Integration - Programming model integration that allows developers to write Java Applications that interact with running processes. #### Process Design - Camunda Modeler - A [standalone desktop application](https://github.com/camunda/camunda-modeler) that allows business users and developers to design & configure processes. #### Process Operations - Camunda Engine - JMX and advanced Runtime Container Integration for process engine monitoring. - Camunda Cockpit - Web application tool for process operations. - Camunda Admin - Web application for managing users, groups, and their access permissions. #### Human Task Management - Camunda Tasklist - Web application for managing and completing user tasks in the context of processes. #### And there's more... - [bpmn.io](https://bpmn.io/) - Toolkits for BPMN, CMMN, and DMN in JavaScript (rendering, modeling) - [Community Extensions](https://docs.camunda.org/manual/7.5/introduction/extensions/) - Extensions on top of Camunda Platform 7 provided and maintained by our great open source community ## A Framework In contrast to other vendor BPM platforms, Camunda Platform 7 strives to be highly integrable and embeddable. We seek to deliver a great experience to developers that want to use BPM technology in their projects. ### Highly Integrable Out of the box, Camunda Platform 7 provides infrastructure-level integration with Java EE Application Servers and Servlet Containers. ### Embeddable Most of the components that make up the platform can even be completely embedded inside an application. For instance, you can add the process engine and the REST API as a library to your application and assemble your custom BPM platform configuration. ## Contributing Please see our [contribution guidelines](CONTRIBUTING.md) for how to raise issues and how to contribute code to our project. ## Tests To run the tests in this repository, please see our [testing tips and tricks](TESTING.md). ## License The source files in this repository are made available under the [Apache License Version 2.0](./LICENSE). Camunda Platform 7 uses and includes third-party dependencies published under various licenses. By downloading and using Camunda Platform 7 artifacts, you agree to their terms and conditions. Refer to https://docs.camunda.org/manual/latest/introduction/third-party-libraries/ for an overview of third-party libraries and particularly important third-party licenses we want to make you aware of.
101
Lightweight, high performance Java caching
[![License](https://x.h7e.eu/badges/xz/txt/license/apache)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Stack Overflow](https://x.h7e.eu/badges/xz/txt/stackoverflow/cache2k)](https://stackoverflow.com/questions/tagged/cache2k) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.cache2k/cache2k-core/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.cache2k/cache2k-core) [![CircleCI](https://circleci.com/gh/cache2k/cache2k/tree/master.svg?style=shield)](https://circleci.com/gh/cache2k/cache2k/tree/master) # cache2k Java Caching cache2k is an in-memory high performance Java Caching library. ````java Cache<String,String> cache = new Cache2kBuilder<String, String>() {} .expireAfterWrite(5, TimeUnit.MINUTES) // expire/refresh after 5 minutes .setupWith(UniversalResiliencePolicy::enable, b -> b // enable resilience policy .resilienceDuration(30, TimeUnit.SECONDS) // cope with at most 30 seconds // outage before propagating // exceptions ) .refreshAhead(true) // keep fresh when expiring .loader(this::expensiveOperation) // auto populating function .build(); ```` For a detailed introduction continue with [Getting Started](https://cache2k.org/docs/latest/user-guide.html#getting-started). ## Features at a glance * Small jar file (less than 400k) with no external dependencies * Fastest access times, due to non blocking and wait free access of cached values, [Blog article](https://cruftex.net/2017/09/01/Java-Caching-Benchmarks-Part-3.html) * Pure Java code, no use of `sun.misc.Unsafe` * Thread safe, with a complete set of [atomic operations](https://cache2k.org/docs/latest/user-guide.html#atomic-operations) * [Resilience and smart exception handling](https://cache2k.org/docs/latest/user-guide.html#resilience) * Null value support, see [User Guide - Null Values](https://cache2k.org/docs/latest/user-guide.html#null-values) * Automatic [Expiry and Refresh](https://cache2k.org/docs/latest/user-guide.html#expiry-and-refresh): duration or point in time, variable expiry per entry, delta calculations * CacheLoader with blocking read through, see [User Guide - Loading and Read Through](https://cache2k.org/docs/latest/user-guide.html#loading-read-through) * CacheWriter * [Event listeners](https://cache2k.org/docs/latest/user-guide.html#event-listeners) * [Refresh ahead](https://cache2k.org/docs/latest/user-guide.html#refresh-ahead) reduces latency * [Low Overhead Statistics](https://cache2k.org/docs/latest/user-guide.html#statistics) and JMX support * [Separate API](https://cache2k.org/docs/latest/apidocs/cache2k-api/index.html) with stable and concise interface * [complete JCache / JSR107 support](https://cache2k.org/docs/latest/user-guide.html#jcache) * [XML based configuration](https://cache2k.org/docs/latest/user-guide.html#xml-configuration), to separate cache tuning from logic ## Integrations * [Spring Framework](https://cache2k.org/docs/latest/user-guide.html#spring) * [Scala Cache](https://github.com/cb372/scalacache) * Datanucleus (via JCache) * Hibernate (via JCache) ## More... For more documentation and latest news, see the [cache2k homepage](https://cache2k.org). ## Contributing See the [Contributor Guide](CONTRIBUTING.md).
102
Fast computer vision library for SFM, calibration, fiducials, tracking, image processing, and more.
null
103
openHAB client for Android
<p align="center"> <a href="https://github.com/openhab/openhab-android/actions?query=workflow%3A%22Build+App%22"><img alt="GitHub Action" src="https://github.com/openhab/openhab-android/workflows/Build%20App/badge.svg"></a> <a href="https://crowdin.com/project/openhab-android"><img alt="Crowdin" src="https://d322cqt584bo4o.cloudfront.net/openhab-android/localized.svg"></a> <a href="https://www.bountysource.com/teams/openhab/issues?tracker_ids=968858"><img alt="Bountysource" src="https://www.bountysource.com/badge/tracker?tracker_id=968858"></a> <br> <img alt="Logo" src="fastlane/metadata/android/en-US/images/icon.png" width="100"> <br> <b>openHAB client for Android</b> </p> ## Introduction This app is a native client for openHAB which allows easy access to your sitemaps. The documentation is available at [www.openhab.org/docs/](https://www.openhab.org/docs/apps/android.html). <a href="https://play.google.com/store/apps/details?id=org.openhab.habdroid"><img src="https://play.google.com/intl/en_us/badges/images/generic/en_badge_web_generic.png" alt="Get it on Play Store" height="80"></a> <a href="https://f-droid.org/app/org.openhab.habdroid"><img src="docs/images/get-it-on-fdroid.png" alt="Get it on F-Droid" height="80"></a> <a href="https://github.com/openhab/openhab-android/releases"><img src="assets/direct-apk-download.png" alt="Get it on GitHub" height="80"></a> ## Features * Control your openHAB server and/or [openHAB Cloud instance](https://github.com/openhab/openhab-cloud), e.g., an account with [myopenHAB](http://www.myopenhab.org/) * Receive notifications through an openHAB Cloud connection, [read more](https://www.openhab.org/docs/configuration/actions.html#cloud-notification-actions) * Change items via NFC tags * Send voice commands to openHAB * [Send alarm clock time to openHAB](https://www.openhab.org/docs/apps/android.html#alarm-clock) * [Supports wall mounted tablets](https://www.openhab.org/docs/apps/android.html#permanent-deployment) * [Tasker](https://play.google.com/store/apps/details?id=net.dinglisch.android.taskerm) action plugin included <img src="docs/images/main-menu.png" alt="Demo Overview" width=200px> <img src="docs/images/widget-overview.png" alt="Widget Overview" width=200px> <img src="docs/images/main-ui.png" alt="Main UI" width=200px> ## Beta builds Beta builds are distributed via [GitHub](https://github.com/openhab/openhab-android/releases) and [F-Droid](https://f-droid.org/packages/org.openhab.habdroid.beta). Those builds can be installed alongside the stable version. On Google Play you can opt-in to get updates of stable versions before others: https://play.google.com/apps/testing/org.openhab.habdroid ## Localization Concerning all `strings.xml` files at [mobile/src/\*/res/values-\*/](mobile/src/main/res/) All language/regional translations are managed with [Crowdin](https://crowdin.com/). Please do NOT contribute translations as pull requests against the `mobile/src/*/res/values-*/strings.xml` files directly, but submit them through the Crowdin web service: - [https://crowdin.com/project/openhab-android](https://crowdin.com/project/openhab-android) Thanks for your consideration and contribution! ## Setting up development environment If you want to contribute to Android application we are here to help you to set up development environment. openHAB client for Android is developed using Android Studio. - Download and install [Android Studio](https://developer.android.com/studio) - Check out the latest code from GitHub via Android Studio - Install SDKs and Gradle if you get asked - Click on "Build Variants" on the left side and change the build variant of the module "mobile" to "fullStableDebug". You are ready to contribute! Before producing any amount of code please have a look at [contribution guidelines](CONTRIBUTING.md) ## Build flavors An optional build flavor "foss" is available for distribution through F-Droid. This build has FCM and crash reporting removed and will not be able to receive push notifications from openHAB Cloud. For using map view support in the "full" build flavor, you need to visit the [Maps API page](https://developers.google.com/maps/android) and generate an API key via the 'Get a key' button at the top. Then add a line in the following format to the 'gradle.properties' file (either in the same directory as this readme file, or in $HOME/.gradle): `mapsApiKey=<key>`, replacing `<key>` with the API key you just obtained. ## Trademark Disclaimer Product names, logos, brands and other trademarks referred to within the openHAB website are the property of their respective trademark holders. These trademark holders are not affiliated with openHAB or our website. They do not sponsor or endorse our materials. Google Play and the Google Play logo are trademarks of Google Inc.
104
A powerful flow control component enabling reliability, resilience and monitoring for microservices. (้ขๅ‘ไบ‘ๅŽŸ็”ŸๅพฎๆœๅŠก็š„้ซ˜ๅฏ็”จๆตๆŽง้˜ฒๆŠค็ป„ไปถ)
<img src="https://user-images.githubusercontent.com/9434884/43697219-3cb4ef3a-9975-11e8-9a9c-73f4f537442d.png" alt="Sentinel Logo" width="50%"> # Sentinel: The Sentinel of Your Microservices [![Sentinel CI](https://github.com/alibaba/Sentinel/actions/workflows/ci.yml/badge.svg)](https://github.com/alibaba/Sentinel/actions/workflows/ci.yml) [![Codecov](https://codecov.io/gh/alibaba/Sentinel/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/Sentinel) [![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.csp/sentinel-core.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:com.alibaba.csp%20AND%20a:sentinel-core) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Gitter](https://badges.gitter.im/alibaba/Sentinel.svg)](https://gitter.im/alibaba/Sentinel) [![Leaderboard](https://img.shields.io/badge/Sentinel-Check%20Your%20Contribution-orange)](https://opensource.alibaba.com/contribution_leaderboard/details?projectValue=sentinel) ## Introduction As distributed systems become increasingly popular, the reliability between services is becoming more important than ever before. Sentinel takes "flow" as breakthrough point, and works on multiple fields including **flow control**, **traffic shaping**, **concurrency limiting**, **circuit breaking** and **system adaptive overload protection**, to guarantee reliability and resilience for microservices. Sentinel has the following features: - **Rich applicable scenarios**: Sentinel has been wildly used in Alibaba, and has covered almost all the core-scenarios in Double-11 (11.11) Shopping Festivals in the past 10 years, such as โ€œSecond Killโ€ which needs to limit burst flow traffic to meet the system capacity, message peak clipping and valley fills, circuit breaking for unreliable downstream services, cluster flow control, etc. - **Real-time monitoring**: Sentinel also provides real-time monitoring ability. You can see the runtime information of a single machine in real-time, and the aggregated runtime info of a cluster with less than 500 nodes. - **Widespread open-source ecosystem**: Sentinel provides out-of-box integrations with commonly-used frameworks and libraries such as Spring Cloud, gRPC, Apache Dubbo and Quarkus. You can easily use Sentinel by simply add the adapter dependency to your services. - **Polyglot support**: Sentinel has provided native support for Java, [Go](https://github.com/alibaba/sentinel-golang), [C++](https://github.com/alibaba/sentinel-cpp) and [Rust](https://github.com/sentinel-group/sentinel-rust). - **Various SPI extensions**: Sentinel provides easy-to-use SPI extension interfaces that allow you to quickly customize your logic, for example, custom rule management, adapting data sources, and so on. Features overview: ![features-of-sentinel](./doc/image/sentinel-features-overview-en.png) The community is also working on **the specification of traffic governance and fault-tolerance**. Please refer to [OpenSergo](https://opensergo.io/) for details. ## Documentation See the [Sentinel Website](https://sentinelguard.io/) for the official website of Sentinel. See the [ไธญๆ–‡ๆ–‡ๆกฃ](https://sentinelguard.io/zh-cn/docs/introduction.html) for document in Chinese. See the [Wiki](https://github.com/alibaba/Sentinel/wiki) for full documentation, examples, blog posts, operational details and other information. Sentinel provides integration modules for various open-source frameworks (e.g. Spring Cloud, Apache Dubbo, gRPC, Quarkus, Spring WebFlux, Reactor) and service mesh. You can refer to [the document](https://sentinelguard.io/en-us/docs/open-source-framework-integrations.html) for more information. If you are using Sentinel, please [**leave a comment here**](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better. It's also encouraged to add the link of your blog post, tutorial, demo or customized components to [**Awesome Sentinel**](./doc/awesome-sentinel.md). ## Ecosystem Landscape ![ecosystem-landscape](./doc/image/sentinel-opensource-eco-landscape-en.png) ## Quick Start Below is a simple demo that guides new users to use Sentinel in just 3 steps. It also shows how to monitor this demo using the dashboard. ### 1. Add Dependency **Note:** Sentinel requires JDK 1.8 or later. If you're using Maven, just add the following dependency in `pom.xml`. ```xml <!-- replace here with the latest version --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> <version>1.8.6</version> </dependency> ``` If not, you can download JAR in [Maven Center Repository](https://mvnrepository.com/artifact/com.alibaba.csp/sentinel-core). ### 2. Define Resource Wrap your code snippet via Sentinel API: `SphU.entry(resourceName)`. In below example, it is `System.out.println("hello world");`: ```java try (Entry entry = SphU.entry("HelloWorld")) { // Your business logic here. System.out.println("hello world"); } catch (BlockException e) { // Handle rejected request. e.printStackTrace(); } // try-with-resources auto exit ``` So far the code modification is done. We've also provided [annotation support module](https://github.com/alibaba/Sentinel/blob/master/sentinel-extension/sentinel-annotation-aspectj/README.md) to define resource easier. ### 3. Define Rules If we want to limit the access times of the resource, we can **set rules to the resource**. The following code defines a rule that limits access to the resource to 20 times per second at the maximum. ```java List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); // set limit qps to 20 rule.setCount(20); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); rules.add(rule); FlowRuleManager.loadRules(rules); ``` For more information, please refer to [How To Use](https://sentinelguard.io/en-us/docs/basic-api-resource-rule.html). ### 4. Check the Result After running the demo for a while, you can see the following records in `~/logs/csp/${appName}-metrics.log.{date}` (When using the default `DateFileLogHandler`). ``` |--timestamp-|------date time----|-resource-|p |block|s |e|rt |occupied 1529998904000|2018-06-26 15:41:44|HelloWorld|20|0 |20|0|0 |0 1529998905000|2018-06-26 15:41:45|HelloWorld|20|5579 |20|0|728 |0 1529998906000|2018-06-26 15:41:46|HelloWorld|20|15698|20|0|0 |0 1529998907000|2018-06-26 15:41:47|HelloWorld|20|19262|20|0|0 |0 1529998908000|2018-06-26 15:41:48|HelloWorld|20|19502|20|0|0 |0 1529998909000|2018-06-26 15:41:49|HelloWorld|20|18386|20|0|0 |0 p stands for incoming request, block for blocked by rules, s for success handled by Sentinel, e for exception count, rt for average response time (ms), occupied stands for occupiedPassQps since 1.5.0 which enable us booking more than 1 shot when entering. ``` This shows that the demo can print "hello world" 20 times per second. More examples and information can be found in the [How To Use](https://sentinelguard.io/en-us/docs/basic-api-resource-rule.html) section. The working principles of Sentinel can be found in [How it works](https://sentinelguard.io/en-us/docs/basic-implementation.html) section. Samples can be found in the [sentinel-demo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo) module. ### 5. Start Dashboard > Note: Java 8 is required for building or running the dashboard. Sentinel also provides a simple dashboard application, on which you can monitor the clients and configure the rules in real time. ![dashboard](https://user-images.githubusercontent.com/9434884/55449295-84866d80-55fd-11e9-94e5-d3441f4a2b63.png) For details please refer to [Dashboard](https://github.com/alibaba/Sentinel/wiki/Dashboard). ## Trouble Shooting and Logs Sentinel will generate logs for troubleshooting and real-time monitoring. All the information can be found in [logs](https://sentinelguard.io/en-us/docs/logs.html). ## Bugs and Feedback For bug report, questions and discussions please submit [GitHub Issues](https://github.com/alibaba/sentinel/issues). Contact us via [Gitter](https://gitter.im/alibaba/Sentinel) or [Email](mailto:[email protected]). ## Contributing Contributions are always welcomed! Please refer to [CONTRIBUTING](./CONTRIBUTING.md) for detailed guidelines. You can start with the issues labeled with [`good first issue`](https://github.com/alibaba/Sentinel/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). ## Credits Thanks [Guava](https://github.com/google/guava), which provides some inspiration on rate limiting. And thanks for all [contributors](https://github.com/alibaba/Sentinel/graphs/contributors) of Sentinel! ## Who is using These are only part of the companies using Sentinel, for reference only. If you are using Sentinel, please [add your company here](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better :) ![Alibaba Group](https://docs.alibabagroup.com/assets2/images/en/global/logo_header.png) ![AntFin](https://user-images.githubusercontent.com/9434884/90598732-30961c00-e226-11ea-8c86-0b1d7f7875c7.png) ![Taiping Renshou](http://www.cntaiping.com/tplresource/cms/www/taiping/img/home_new/tp_logo_img.png) ![ๆ‹ผๅคšๅคš](http://cdn.pinduoduo.com/assets/img/pdd_logo_v3.png) ![็ˆฑๅฅ‡่‰บ](https://user-images.githubusercontent.com/9434884/90598445-a51c8b00-e225-11ea-9327-3543525f3f2a.png) ![Shunfeng Technology](https://user-images.githubusercontent.com/9434884/48463502-2f48eb80-e817-11e8-984f-2f9b1b789e2d.png) ![ไบŒ็ปด็ซ](https://user-images.githubusercontent.com/9434884/49358468-bc43de00-f70d-11e8-97fe-0bf05865f29f.png) ![Mandao](https://user-images.githubusercontent.com/9434884/48463559-6cad7900-e817-11e8-87e4-42952b074837.png) ![ๆ–‡่ฝฉๅœจ็บฟ](http://static.winxuancdn.com/css/v2/images/logo.png) ![ๅฎขๅฆ‚ไบ‘](https://www.keruyun.com/static/krynew/images/logo.png) ![ไบฒๅฎๅฎ](https://stlib.qbb6.com/wclt/img/home_hd/version1/title_logo.png) ![้‡‘ๆฑ‡้‡‘่ž](https://res.jinhui365.com/r/images/logo2.png?v=1.527) ![้—ช็”ต่ดญ](http://cdn.52shangou.com/shandianbang/official-source/3.1.1/build/images/logo.png)
105
Java Agent is a Java application probe of DongTai IAST, which collects method invocation data during runtime of Java application by dynamic hooks.
## DongTai-agent-java ------ [ไธญๆ–‡็‰ˆๆœฌ(Chinese version)](README_CN.md) [![license Apache-2.0](https://img.shields.io/github/license/HXSecurity/DongTai-agent-java)](https://github.com/HXSecurity/DongTai-agent-java/blob/main/LICENSE) [![GitHub stars](https://img.shields.io/github/stars/HXSecurity/DongTai-agent-java.svg?label=Stars&logo=github)](https://github.com/HXSecurity/DongTai-agent-java) [![GitHub forks](https://img.shields.io/github/forks/HXSecurity/DongTai-Agent-Java?label=Forks&logo=github)](https://github.com/HXSecurity/DongTai-agent-java) [![GitHub Contributors](https://img.shields.io/github/contributors-anon/HXSecurity/DongTai-agent-java?label=Contributors&logo=github)](https://github.com/HXSecurity/DongTai-agent-java) [![CI](https://github.com/HXSecurity/DongTai-agent-java/actions/workflows/release-agent.yml/badge.svg)](https://github.com/HXSecurity/DongTai-agent-java/actions/workflows/release-agent.yml) [![Github Version](https://img.shields.io/github/v/release/HXSecurity/DongTai-agent-java?display_name=tag&include_prereleases&sort=semver)](https://github.com/HXSecurity/DongTai-agent-java/releases) [![Release downloads](https://shields.io/github/downloads/HXSecurity/DongTai-Agent-Java/total)](https://github.com/HXSecurity/DongTai-agent-java/releases) ## Project Introduction Dongtai-agent-java is DongTai Iast's data acquisition tool for Java applications. In a Java application with the iast agent added, the required data is collected by rewriting class bytecode, and then the data is sent to dongtai-OpenAPI service, and then the cloud engine processes the data to determine whether there are security holes. Dongtai-agent-java consists of `agent.jar`, `dongtai-core-jar`, `dongtai-spy. Jar` and `dongtai-servlet.jar`: - `agent.jar` It is used to manage agent life cycle and configuration. The life cycle of the Agent includes downloading, installing, starting, stopping, restarting, and uninstalling the agent. Agent configuration includes application startup mode, vulnerability verification mode, whether to enable agent, etc. - `dongtai-core.jar ` The main functions of dongtai-core.jar are: bytecode piling, data collection, data preprocessing, data reporting, third-party component management, etc. - `dongtai-inject.jar` It is used to inject into the BootStrap ClassLoader. The data collection method in 'iast-core.jar' is then invoked in the target application. - `dongtai-servlet.jar` It is used to obtain the requests sent by the application and the responses received. It is used for data display and request replay. ## Application Scenarios - DevOps - Security test the application before it goes online - Third-party Component Management - Code audit - 0 Day digging ## Quick Start Please refer to the [Quick Start](https://doc.dongtai.io). ## Quick Development 1. Fork the [DongTai-agent-java](https://github.com/HXSecurity/DongTai-agent-java) , clone your fork: ``` git clone https://github.com/<your-username>/DongTai-agent-java ``` 2. Write code to your needs. 3. Compile Dongtai-agent-Java using Maven: ``` mvn clean package -Dmaven.test.skip=true ``` - notice: JDK version is 1.8. 4. folder `./release` is generated in the project root directory after compilation: ``` release โ”œโ”€โ”€ dongtai-agent.jar โ””โ”€โ”€ lib โ”œโ”€โ”€ dongtai-servlet.jar โ”œโ”€โ”€ dongtai-core.jar โ””โ”€โ”€ dongtai-spy.jar ``` 5. Copy `dongtai-core.jar`ใ€`dongtai-spy.jar`ใ€`dongtai-servlet.jar` to the system temporary directory. Get the system temporary directory to run the following Java code: ``` System.getProperty("java.io.tmpdir.dongtai"); ``` 6. Run the application and test the code (for example, SpringBoot) : `java -javaagent:/path/to/dongtai-agent.jar -Ddongtai.debug=true -jar app.jar` 7. Contribute code. If you want to contribute code to the DongTai IAST team, please read the full [contribution guide](https://github.com/HXSecurity/DongTai/blob/main/CONTRIBUTING.md). ### Supported Java versions and middleware - Java 1.8+ - Tomcat, Jetty, WebLogic, WebSphere, SpringBoot and Mainstream software and middleware.
106
Java libraries for writing composable microservices
Apollo ====== [![Circle Status](https://circleci.com/gh/spotify/apollo.svg?style=shield&circle-token=5a9eb086ae3cec87e62fc8b6cdeb783cb318e3b9)](https://circleci.com/gh/spotify/apollo) [![Codecov](https://img.shields.io/codecov/c/github/spotify/apollo.svg)](https://codecov.io/gh/spotify/apollo) [![Maven Central](https://img.shields.io/maven-central/v/com.spotify/apollo-parent.svg)](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.spotify%22%20apollo*) [![License](https://img.shields.io/github/license/spotify/apollo.svg)](LICENSE) Apollo is a set of Java libraries that we use at Spotify when writing microservices. Apollo includes modules such as an HTTP server and a URI routing system, making it trivial to implement restful API services. Apollo has been used in production at Spotify for a long time. As a part of the work to release version 1.0.0 we moved the development of Apollo into the open. There are three main libraries in Apollo: * [apollo-http-service](apollo-http-service) * [apollo-api](apollo-api) * [apollo-core](apollo-core) If you need to solve a problem where the main APIs aren't powerful enough, [apollo-environment](apollo-environment) provides more hooks, allowing you to modify the core behaviours of Apollo. ### Apollo HTTP Service The [apollo-http-service](apollo-http-service) library is a standardized assembly of Apollo modules. It incorporates both apollo-api and apollo-core and ties them together with other modules to get a standard api service using http for incoming and outgoing communication. ### Apollo API The [apollo-api](apollo-api) library is the Apollo library you are most likely to interact with. It gives you the tools you need to define your service routes and your request/reply handlers. Here, for example, we define that our service will respond to a GET request on the path `/` with the string `"hello world"`: ```java public static void init(Environment environment) { environment.routingEngine() .registerAutoRoute(Route.sync("GET", "/", requestContext -> "hello world")); } ``` The apollo-api library provides several ways to help you define your request/reply handlers. You can specify how responses should be serialized (such as JSON). Read more about this library in the [Apollo API Readme](apollo-api). ### Apollo Core The [apollo-core](apollo-core) library manages the lifecycle (loading, starting, and stopping) of your service. You do not usually need to interact directly with apollo-core; think of it merely as "plumbing". For more information about this library, see the [Apollo Core Readme](apollo-core). ### Apollo Test In addition to the three main Apollo libraries listed above, to help you write tests for your service we have an additional library called [apollo-test](apollo-test). It has helpers to set up a service for testing, and to mock outgoing request responses. ### Getting Started with Apollo Apollo will be distributed as a set of Maven artifacts, which makes it easy to get started no matter the build tool; Maven, Ant + Ivy or Gradle. Below is a very simple but functional service โ€” more extensive examples are available in the [examples](examples) directory. Until these are released, you can build and install Apollo from source by running `mvn install`. ```java public final class App { public static void main(String... args) throws LoadingException { HttpService.boot(App::init, "my-app", args); } static void init(Environment environment) { environment.routingEngine() .registerAutoRoute(Route.sync("GET", "/", rc -> "hello world")); } } ``` ### Apollo Metadata [Metadata](apollo-api-impl/src/main/java/com/spotify/apollo/meta/model) about an Apollo-based service, such as endpoints, is generated at runtime. At Spotify we use this to keep track of our running services. More info can be found [here](https://apidays.nz/slides/iglesias_service_metadata.pdf). Examples from [spotify-api-example](examples/spotify-api-example): `$ curl http://localhost:8080/_meta/0/endpoints` ```json { "result": { "docstring": null, "endpoints":[ { "docstring": "Get the latest albums on Spotify.\n\nUses the public Spotify API https://api.spotify.com to get 'new' albums.", "method": [ "GET" ], "methodName": "/albums/new[GET]", "queryParameters":[], "uri": "/albums/new" }, { "docstring": "Responds with a 'pong!' if the service is up.\n\nUseful endpoint for doing health checks.", "method": [ "GET" ], "methodName": "/ping[GET]", "queryParameters": [], "uri": "/ping" }, ... ] } } ``` `$ curl http://localhost:8080/_meta/0/info` ```json { "result": { "buildVersion": "spotify-api-example-service 1.3.1", "componentId": "spotify-api-example-service", "containerVersion": "apollo-http2.0.0-SNAPSHOT", "serviceUptime": 778.249, "systemVersion": "java 1.8.0_111" } } ``` ### Links [Introduction Website](https://spotify.github.io/apollo)<br /> [JavaDocs](https://spotify.github.io/apollo/maven/apidocs)<br /> [Maven site](https://spotify.github.io/apollo/maven) ### Diagrams [![Apollo set-up](https://cdn.rawgit.com/spotify/apollo/master/website/source/set-up.svg)](website/source/set-up.svg) [![Apollo in runtime](https://cdn.rawgit.com/spotify/apollo/master/website/source/runtime.svg)](website/source/runtime.svg) ## Code of conduct This project adheres to the [Open Code of Conduct][code-of-conduct]. By participating, you are expected to honor this code. [code-of-conduct]: https://github.com/spotify/code-of-conduct/blob/master/code-of-conduct.md
107
Alibaba Dragonwell8 JDK
![Dragonwell Logo](https://raw.githubusercontent.com/wiki/alibaba/dragonwell8/images/dragonwell_std_txt_horiz.png) [Alibaba Dragonwell8 User Guide](https://github.com/alibaba/dragonwell8/wiki/Alibaba-Dragonwell8-User-Guide) [Alibaba Dragonwell8 Extended Edition Release Notes](https://github.com/alibaba/dragonwell8/wiki/Alibaba-Dragonwell8-Extended-Edition-Release-Notes) [Alibaba Dragonwell8 Standard Edition Release Notes](https://github.com/alibaba/dragonwell8/wiki/Alibaba-Dragonwell8-Standard-Edition-Release-Notes) # Introduction Over the years, Java has proliferated in Alibaba. Many applications are written in Java and many our Java developers have written more than one billion lines of Java code. Alibaba Dragonwell, as a downstream version of OpenJDK, is the in-house OpenJDK implementation at Alibaba optimized for online e-commerce, financial, logistics applications running on 100,000+ servers. Alibaba Dragonwell is the engine that runs these distributed Java applications in extreme scaling. The current release supports Linux/x86_64 platform only. Alibaba Dragonwell is clearly a "friendly fork" under the same licensing terms as the upstream OpenJDK project. Alibaba is committed to collaborate closely with OpenJDK community and intends to bring as many customized features as possible from Alibaba Dragonwell to the upstream. # Using Alibaba Dragonwell Alibaba Dragonwell JDK currently supports Linux/x86_64 platform only. ### Installation ##### Option 1, Download and install pre-built Alibaba Dragonwell * You may download a pre-built Alibaba Dragonwell JDK from its GitHub page: https://github.com/alibaba/dragonwell8/releases. * Uncompress the package to the installation directory. ##### Option 2, Install via YUM Alibaba Dragonwell is officially supported and maintained in Alibaba Cloud Linux 2 (Aliyun Linux 2) YUM repository, and this repo should be also compatible with Aliyun Linux 17.1, Red Hat Enterprise Linux 7 and CentOS 7. * For users running Alibaba Cloud Linux 2 OS, you should be able to install Alibaba Dragonwell by simply running: `sudo yum install -y java-1.8.0-alibaba-dragonwell`; * For users running with aforementioned compatible distros, place a new repository file under `/etc/yum.repos.d` (e.g.: `/etc/repos.d/alinux-plus.repo`) with contents as follows, then you should be able to install Alibaba Dragonwell by executing: `sudo yum install -y java-1.8.0-alibaba-dragonwell`: ``` # plus packages provided by Aliyun Linux dev team [plus] name=AliYun-2.1903 - Plus - mirrors.aliyun.com baseurl=http://mirrors.aliyun.com/alinux/2.1903/plus/$basearch/ gpgcheck=1 gpgkey=http://mirrors.aliyun.com/alinux/RPM-GPG-KEY-ALIYUN ``` ### Enable Alibaba Dragonwell for Java applications To enable Alibaba Dragonwell JDK for your application, simply set `JAVA_HOME` to point to the installation directory of Alibaba Dragonwell. If you installed Dragonwell JDK via YUM, follow the instructions prompted from post-install outputs, e.g.: ``` ======================================================================= Alibaba Dragonwell is installed to: /opt/alibaba/java-1.8.0-alibaba-dragonwell-8.0.0.212.b04-1.al7 You can set Alibaba Dragonwell as default JDK by exporting the following ENV VARs: $ export JAVA_HOME=/opt/alibaba/java-1.8.0-alibaba-dragonwell-8.0.0.212.b04-1.al7 $ export PATH=${JAVA_HOME}/bin:$PATH ======================================================================= ``` # Acknowledgement Special thanks to those who have made contributions to Alibaba's internal JDK builds. # Publications Technologies included in Alibaba Dragonwell have been published in following papers * ICSE'19๏ผšhttps://2019.icse-conferences.org/event/icse-2019-technical-papers-safecheck-safety-enhancement-of-java-unsafe-api * ICPE'18: https://dl.acm.org/citation.cfm?id=3186295 * ICSE'18 SEIP https://www.icse2018.org/event/icse-2018-software-engineering-in-practice-java-performance-troubleshooting-and-optimization-at-alibaba
108
Mirror of Apache Storm
null
109
ไธญๆ–‡่‡ช็„ถ่ฏญ่จ€ๅค„็†ๅทฅๅ…ทๅŒ… Toolkit for Chinese natural language processing
FudanNLP (FNLP) 2018.12.16 ๆˆ‘ไปฌๅพˆ้ซ˜ๅ…ดๅ‘ๅธƒไบ†FudanNLP็š„ๅŽ็ปญ็‰ˆๆœฌ๏ผŒไธ€ไธชๅ…จๆ–ฐ็š„่‡ช็„ถ่ฏญ่จ€ๅค„็†ๅทฅๅ…ท[FastNLP](https://github.com/fastnlp/fastNLP)ใ€‚FudanNLPไธๅ†ๆ›ดๆ–ฐใ€‚ 2018.12.16 We are delighted to announce a new brand toolkit [FastNLP](https://github.com/fastnlp/fastNLP), a major update of the FudanNLP. The FudanNLP is no longer updated. ==== ไป‹็ป(Introduction) ----------------------------------- FNLPไธป่ฆๆ˜ฏไธบไธญๆ–‡่‡ช็„ถ่ฏญ่จ€ๅค„็†่€Œๅผ€ๅ‘็š„ๅทฅๅ…ทๅŒ…๏ผŒไนŸๅŒ…ๅซไธบๅฎž็Žฐ่ฟ™ไบ›ไปปๅŠก็š„ๆœบๅ™จๅญฆไน ็ฎ—ๆณ•ๅ’Œๆ•ฐๆฎ้›†ใ€‚ ๆœฌๅทฅๅ…ทๅŒ…ๅŠๅ…ถๅŒ…ๅซๆ•ฐๆฎ้›†ไฝฟ็”จLGPL3.0่ฎธๅฏ่ฏใ€‚ FNLP is developed for Chinese natural language processing (NLP), which also includes some machine learning algorithms and [DataSet data sets] to achieve the NLP tasks. FudanNLP is distributed under LGPL3.0. If you're new to FNLP, check out the [Quick Start (ไฝฟ็”จ่ฏดๆ˜Ž)](https://github.com/FudanNLP/fnlp/wiki) page. ๅŽŸFudanNLP้กน็›ฎๅœฐๅ€๏ผšhttp://code.google.com/p/fudannlp ๅŠŸ่ƒฝ(Functions) ---- ไฟกๆฏๆฃ€็ดข๏ผš ๆ–‡ๆœฌๅˆ†็ฑป ๆ–ฐ้—ป่š็ฑป ไธญๆ–‡ๅค„็†๏ผš ไธญๆ–‡ๅˆ†่ฏ ่ฏๆ€งๆ ‡ๆณจ ๅฎžไฝ“ๅ่ฏ†ๅˆซ ๅ…ณ้”ฎ่ฏๆŠฝๅ– ไพๅญ˜ๅฅๆณ•ๅˆ†ๆž ๆ—ถ้—ด็Ÿญ่ฏญ่ฏ†ๅˆซ ็ป“ๆž„ๅŒ–ๅญฆไน ๏ผš ๅœจ็บฟๅญฆไน  ๅฑ‚ๆฌกๅˆ†็ฑป ่š็ฑป [ChangeLog ๆ›ดๆ–ฐๆ—ฅๅฟ—(ChangeLog)] [ๆ€ง่ƒฝๆต‹่ฏ•(Benchmark)] (Benchmark) [ๅผ€ๅ‘่ฎกๅˆ’(Development Plan)] (DevPlan) [ๅผ€ๅ‘ไบบๅ‘˜ๅˆ—่กจ(Developers)](People) Demos ---- ไฝ ๅฏไปฅ้€š่ฟ‡่ฏ•็”จไธ‹้ข็š„็ฝ‘็ซ™ๆฅๆต‹่ฏ•้ƒจๅˆ†ๅŠŸ่ƒฝใ€‚ You can also use the following site to check the partial functionality. [Demo Website(ๆผ”็คบ็ฝ‘็ซ™)](http://nlp.fudan.edu.cn/demo) ๆœ‰้‡ๅˆฐFNLPไธ่ƒฝๅค„็†็š„ไพ‹ๅญ๏ผŒ่ฏทๅˆฐ่ฟ™้‡Œๆไบค: [ๅๅŒๆ•ฐๆฎๆ”ถ้›†](http://code.google.com/p/fudannlp/wiki/CollaborativeCollection)ใ€‚ ๆœ‰้—ฎ้ข˜่ฏทๆŸฅ็œ‹[FAQ](faq)ๆˆ–ๅˆฐ QQ็พค๏ผˆ253541693๏ผ‰่ฎจ่ฎบใ€‚ ไฝฟ็”จ(Usages) ---- [FNLPๅ…ฅ้—จๆ•™็จ‹](https://github.com/xpqiu/fnlp/wiki) ้™คไบ†ๆบ็ ๆ–‡ไปถ๏ผŒ่ฟ˜้œ€่ฆไธ‹่ฝฝFNLPๆจกๅž‹ๆ–‡ไปถใ€‚็”ฑไบŽๆจกๅž‹ๆ–‡ไปถ่พƒๅคง๏ผŒไธไพฟไบŽๅญ˜ๆ”พๅœจๆบ็ ๅบ“ไน‹ไธญ๏ผŒ่ฏท่‡ณ[Release](https://github.com/xpqiu/fnlp/releases)้กต้ขไธ‹่ฝฝ๏ผŒๅนถๅฐ†ๆจกๅž‹ๆ–‡ไปถๆ”พๅœจโ€œmodelsโ€็›ฎๅฝ•ใ€‚ * seg.m ๅˆ†่ฏๆจกๅž‹ * pos.m ่ฏๆ€งๆ ‡ๆณจๆจกๅž‹ * dep.m ไพๅญ˜ๅฅๆณ•ๅˆ†ๆžๆจกๅž‹ ๆฌข่ฟŽๅคงๅฎถๆไพ›้žJava่ฏญ่จ€็š„ๆŽฅๅฃใ€‚ ๅผ•็”จ(Citation) ---- If you would like to acknowledge our efforts, please cite the following paper. ๅฆ‚ๆžœๆˆ‘ไปฌ็š„ๅทฅไฝœๅฏนๆ‚จๆœ‰ๅธฎๅŠฉ๏ผŒ่ฏทๅผ•็”จไธ‹้ข่ฎบๆ–‡ใ€‚ Xipeng Qiu, Qi Zhang and Xuanjing Huang, FudanNLP: A Toolkit for Chinese Natural Language Processing, In Proceedings of Annual Meeting of the Association for Computational Linguistics (ACL), 2013.* @INPROCEEDINGS{Qiu:2013, author = {Xipeng Qiu and Qi Zhang and Xuanjing Huang}, title = {FudanNLP: A Toolkit for Chinese Natural Language Processing}, booktitle = {Proceedings of Annual Meeting of the Association for Computational Linguistics}, year = {2013}, } ๅœจ[่ฟ™้‡Œ](http://jkx.fudan.edu.cn/~xpqiu/) ๆˆ– [DBLP](http://scholar.google.com/citations?sortby=pubdate&hl=en&user=Pq4Yp_kAAAAJ&view_op=list_works Google Scholar] ๆˆ– [http://www.informatik.uni-trier.de/~ley/pers/hd/q/Qiu:Xipeng.html) ๅฏไปฅๆ‰พๅˆฐๆ›ดๅคš็š„็›ธๅ…ณ่ฎบๆ–‡ใ€‚ We used [JProfiler](http://www.ej-technologies.com/products/jprofiler/overview.html ) to help optimize the code. ๆœฌ็ฝ‘็ซ™๏ผˆๆˆ–้กต้ข๏ผ‰็š„ๆ–‡ๅญ—ๅ…่ฎธๅœจCC-BY-SA 3.0ๅ่ฎฎๅ’ŒGNU่‡ช็”ฑๆ–‡ๆกฃ่ฎธๅฏ่ฏไธ‹ไฟฎๆ”นๅ’Œๅ†ไฝฟ็”จใ€‚
110
.ignore support plugin for IntelliJ IDEA
.ignore 4.x ============= [![official JetBrains project](https://jb.gg/badges/official.svg)][jb:confluence-on-gh] [![Build](https://github.com/JetBrains/idea-gitignore/workflows/Build/badge.svg)][gh:build] [![Version](http://phpstorm.espend.de/badge/20485/version)][plugin-website] [![Downloads](http://phpstorm.espend.de/badge/20485/downloads)][plugin-website] [![Downloads last month](http://phpstorm.espend.de/badge/7495/last-month)][plugin-website] <!-- New ID does not work here for some reason --> Introduction ------------ <!-- Plugin description --> **.ignore** is a plugin for: - `.bzrignore` (Bazaar) - `.chefignore` (Chef) - `.cfignore` (CloudFoundry) - `.cvsignore` (Cvs) - `.boringignore` (Darcs) - `.deployignore` (DeployHQ) - `.dockerignore` (Docker) - `.ebignore` (ElasticBeanstalk) - `.eleventyignore` (Eleventy) - `.eslintignore` (ESLint) - `.flooignore` (Floobits) - `ignore-glob` (Fossil) - `.gitignore` (Git) - `.gcloudignore` (GoogleCloud) - `.helmignore` (Kubernetes Helm) - `.jpmignore` (Jetpack) - `.jshintignore` (JSHint) - `.hgignore` (Mercurial) - `.mtn-ignore` (Monotone) - `.nodemonignore` (Nodemon) - `.npmignore` (Npm) - `.nuxtignore` (NuxtJS) - `.p4ignore` (Perforce) - `.prettierignore` (Prettier) - `.ignore` (Sourcegraph) - `.stylelintignore` (StyleLint) - `.stylintignore` (Stylint) - `.swagger-codegen-ignore` (SwaggerCodegen) - `.tfignore` (TF) - `.tokeignore` (Tokei) - `.upignore` (Up) - `.vercelignore` (Vercel) - `.yarnignore` (Yarn) files in your project. It supports the following IDEs: - Android Studio - AppCode - CLion - GoLand - IntelliJ IDEA - PhpStorm - PyCharm - RubyMine - WebStorm - DataGrip Features -------- - Files syntax highlight - Templates filtering and selecting in rules generator by name and content - User custom templates - Show ignored files by specified Gitignore file (right-click on `.gitignore` file) - Create a file in the currently selected directory - Generate Gitignore rules basing on [GitHub's templates collection][github-gitignore] - Add a selected file/directory to Gitignore rules from the popup menu - Suggesting `.gitignore` file creation for a new project - Entries inspection (duplicated, covered, unused, incorrect syntax, relative entries) with quick-fix actions - Comments and brackets support - Navigation to entries in Project view - Renaming entries from a dot-ignore file - Close opened ignored files action - Custom user templates with import/export features <!-- Plugin description end --> Supported IDEs -------------- Since `v4.0.0`, .ignore plugin updates will be delivered only to the latest stable IDE version. No worries! It means .ignore for all IDE version from before - `139-193` - will be frozen at `v3.x.x`. Installation ------------ - Using IDE built-in plugin system: - <kbd>Preferences</kbd> > <kbd>Plugins</kbd> > <kbd>Browse repositories...</kbd> > <kbd>Search for ".ignore"</kbd> > <kbd>Install Plugin</kbd> - Manually: - Download the [latest release][latest-release] and install it manually using <kbd>Preferences</kbd> > <kbd>Plugins</kbd> > <kbd>Install plugin from disk...</kbd> Restart IDE. <!-- This is outdated now Early Access Preview -------------------- If you are working with IDEs in EAP version, like IntelliJ 2021.1 EAP, there is `eap` channel introduced to provide the `.ignore` plugin updates supporting such versions. To enable EAP updates of the `.ignore` plugin, add the `https://plugins.jetbrains.com/plugins/eap/20485` URL in the IDE settings: <kbd>Preferences</kbd> > <kbd>Plugins</kbd> > <kbd>Manage Plugin Repositories...</kbd> ![EAP Channel](./.github/readme/eap.png) --> Usage ----- 1. Generate a new file and templates usage To generate new ignore file, just click on <kbd>File</kbd> > <kbd>New</kbd> or use <kbd>Alt</kbd> + <kbd>Insert</kbd> shortcut and select `.ignore file` element. ![Generate new file](./.github/readme/new-file.gif) 2. Support for typing new rules, linking rules with matched files ![Support for typing new rules](./.github/readme/navigation.gif) 3. Code inspections Code inspections covers few cases: - duplicated entries (checks if entry is defined more than once) - covered entries - entry is covered by more general one - unused entries - incorrect syntax (regexp rules) - relative entries ![Code inspections](./.github/readme/inspections.gif) [github-gitignore]: https://github.com/github/gitignore [plugin-website]: https://plugins.jetbrains.com/plugin/20485 [latest-release]: https://github.com/JetBrains/idea-gitignore/releases/latest [jb:confluence-on-gh]: https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub [gh:build]: https://github.com/JetBrains/idea-gitignore/actions?query=workflow%3ABuild
111
An open source, free, high performance, stable and secure Java Application Business Platform of Project Management and Document
# Free, open source Project Management software [![License](http://img.shields.io/badge/License-AGPLv3-orange.svg)](https://www.gnu.org/licenses/agpl-3.0.en.html) [![Project Stats](https://www.openhub.net/p/mycollab/widgets/project_thin_badge.gif)](https://www.openhub.net/p/mycollab) [![Build](https://travis-ci.org/MyCollab/mycollab.svg)](https://travis-ci.org/MyCollab/mycollab) [![Version](https://img.shields.io/badge/Version-7.0.3-brightgreen.svg)](https://docs.mycollab.com/) [![Github](https://img.shields.io/github/downloads/MyCollab/mycollab/total.svg)](https://github.com/MyCollab/mycollab/releases) ## Introduction MyCollab is the free and open source project management software. Intuitive UI, rich features, high performance and stable are the advantages compare with various popular tools in the market such as Redmine, Bugzilla, Mantis etc. This open source is included into a trusted commercial product that is deployed on hundreds of companies' servers. <table> <tr> <td align="center"> <a href="https://c2.staticflickr.com/8/7836/33297801958_8c403afca8_o.png" target="_blank" title="Project Dashboard"> <img src="https://c2.staticflickr.com/8/7836/33297801958_c3958e94ba_n.jpg" alt="Project Dashboard"> </a> <br /> <em>Project Dashboard</em> </td> <td align ="center"> <a href="https://c2.staticflickr.com/8/7918/47173080821_3352d05e2b_o.png" target="_blank" title="Ticket Dashboard"> <img src="https://c2.staticflickr.com/8/7918/47173080821_f6c092822e_n.jpg" alt="Ticket Dashboard"> </a> <br /> <em>Ticket Dashboard</em> </td> <td align="center"> <a href="https://c2.staticflickr.com/8/7868/46259674665_52e5d9ec03_o.png" target="_blank" title="Kanban Board"> <img src="https://c2.staticflickr.com/8/7868/46259674665_c80a0c15a7_n.jpg" alt="Kanban Board"> </a> <br /> <em>Kanban Board</em> </td> </tr> <tr> <td align="center"> <a href="https://c2.staticflickr.com/8/7874/46259716315_bd4269858d_o.png" target="_blank" title="Task View"> <img src="https://c2.staticflickr.com/8/7874/46259716315_44047af85e_n.jpg" alt="Task View"> </a> <br /> <em>Task View</em> </td> <td align="center"> <a href="https://c2.staticflickr.com/8/7896/47173858441_f2395a1b7d_o.png" target="_blank" title="Members"> <img src="https://c2.staticflickr.com/8/7896/47173858441_3b4c77990f_n.jpg" alt="Members"> </a> <br /> <em>Members</em> </td> <td align="center"> <a href="https://c2.staticflickr.com/8/7862/40209055153_0a16241b1b_o.png" target="_blank" title="Settings"> <img src="https://c2.staticflickr.com/8/7862/40209055153_54a427e593_n.jpg" alt="Settings"> </a> <br /> <em>Settings</em> </td> </tr> </table> New features, enhancements, and updates appear on a regular basis. Pull requests and bug reports are always welcome! Visit our website https://www.mycollab.com/ to get a free trial of the premium service. ## Features MyCollab provides the rich set features of Project Management, Customer Management module and online collaboration methods. * Project Management * Activity stream and audit logging * Kanban board * Roadmap view * Issues Management * Tasks and dependencies management * Milestones * Time tracking (for premium users only) * Invoice management (for premium users only) * Risk Management (For premium users only) * People and Permission management * Reporting We use MyCollab in our daily jobs to manage our customers information, projects. It is deployed in the production environment of our premium users, and we supported several organizations to deploy this community version on their servers as well. We take care of our open source edition similar than we do for our premium product, in fact both of them use the same code base structure. So feel free to use it in your business jobs! ## System Requirements MyCollab requires a running Java Runtime Environment (8 or greater), Java command should be presented in PATH environment and MySQL (InnoDB support recommended). * Java Runtime Environment 8+: MyCollab could run when any JVM compatible platform such as Oracle JRE or OpenJDK. * MySQL database, version 5.6+: the higher version is recommended * 1 GB RAM minimum, 2 GB RAM recommended ## Installation 1. Download MyCollab binary - https://www.mycollab.com/self-hosted/ 2. Follow installation guideline at https://docs.mycollab.com/getting-started/installation/ If you need to understand the more MyCollab advanced configuration settings, please visit the link https://docs.mycollab.com/getting-started/configuration/. You will finish reading and understanding in a matter of minutes. If you want to customize MyCollab, following links are useful to you: * Setup MyCollab projects with IntelliJ https://docs.mycollab.com/development/setup-mycollab-projects-with-intellij-ide/ * How to customize MyCollab https://docs.mycollab.com/development/customize-mycollab/ ## Support Contact the MyCollab team at: * Our growing FAQ https://docs.mycollab.com/faq/ * Our help page [http://support.mycollab.com/](https://mycollab.userecho.com/en/) * Our web form [https://www.mycollab.com/contact/](https://www.mycollab.com/contact/) ## License & Author * MyCollab community is licensed with Affero GPL v3. For license terms, see https://www.gnu.org/licenses/agpl-3.0.en.html * You can try MyCollab on-demand edition on site https://www.mycollab.com
112
Gnucash for Android mobile companion application.
<a href="https://travis-ci.org/codinguser/gnucash-android" target="_blank"> <img src="https://travis-ci.org/codinguser/gnucash-android.svg?branch=develop" alt="Travis build status" /> </a> # Introduction GnuCash Android is a companion expense-tracker application for GnuCash (desktop) designed for Android. It allows you to record transactions on-the-go and later import the data into GnuCash for the desktop. Accounts | Transactions | Reports :-------------------------:|:-------------------------:|:-------------------------: ![Accounts List](docs/images/v2.0.0_home.png) | ![Transactions List](docs/images/v2.0.0_transactions_list.png) | ![Reports](docs/images/v2.0.0_reports.png) The application supports Android 4.4 KitKat (API level 19) and above. Features include: * An easy-to-use interface. * **Chart of Accounts**: A master account can have a hierarchy of detail accounts underneath it. This allows similar account types (e.g. Cash, Bank, Stock) to be grouped into one master account (e.g. Assets). * **Split Transactions**: A single transaction can be split into several pieces to record taxes, fees, and other compound entries. * **Double Entry**: Every transaction must debit one account and credit another by an equal amount. This ensures that the "books balance": that the difference between income and outflow exactly equals the sum of all assets, be they bank, cash, stock or other. * **Income/Expense Account Types (Categories)**: These serve not only to categorize your cash flow, but when used properly with the double-entry feature, these can provide an accurate Profit&Loss statement. * **Scheduled Transactions**: GnuCash has the ability to automatically create and enter transactions. * **Export to GnuCash XML**, QIF or OFX. Also, scheduled exports to 3rd-party sync services like DropBox and Google Drive * **Reports**: View summary of transactions (income and expenses) as pie/bar/line charts # Installation There are different ways to get the GnuCash app for Android; through the app store, from github or building it yourself. ### App Store <a href="http://play.google.com/store/apps/details?id=org.gnucash.android"> <img alt="Android app on Google Play" src="http://developer.android.com/images/brand/en_generic_rgb_wo_60.png" /> </a> ### From GitHub Download the .apk from https://github.com/codinguser/gnucash-android/releases ## Building ### With Gradle This project requires the [Android SDK](http://developer.android.com/sdk/index.html) to be installed in your development environment. In addition you'll need to set the `ANDROID_HOME` environment variable to the location of your SDK. For example: export ANDROID_HOME=/home/<user>/tools/android-sdk After satisfying those requirements, the build is pretty simple: * Run `./gradlew build installDevelopmentDebug` from the within the project folder. It will build the project for you and install it to the connected Android device or running emulator. The app is configured to allow you to install a development and production version in parallel on your device. ### With Android Studio The easiest way to build is to install [Android Studio](https://developer.android.com/sdk/index.html) v2.+ with [Gradle](https://www.gradle.org/) v3.4.1 Once installed, then you can import the project into Android Studio: 1. Open `File` 2. Import Project 3. Select `build.gradle` under the project directory 4. Click `OK` Then, Gradle will do everything for you. ## Support Google+ Community: https://plus.google.com/communities/104728406764752407046 ## Contributing There are several ways you could contribute to the development. * Pull requests are always welcome! You could contribute code by fixing bugs, adding new features or automated tests. Take a look at the [bug tracker](https://github.com/codinguser/gnucash-android/issues?state=open) for ideas where to start. It is also preferable to target issues in the current [milestone](https://github.com/codinguser/gnucash-android/milestones). * Make sure to read our [contribution guidelines](https://github.com/codinguser/gnucash-android/blob/master/.github/CONTRIBUTING.md) before starting to code. * Another way to contribute is by providing translations for languages, or improving translations. Please visit [CrowdIn](https://crowdin.com/project/gnucash-android) in order to update and create new translations For development, it is recommended to use the Android Studio for development which is available for free. Import the project into the IDE using the build.gradle file. The IDE will resolve dependencies automatically. # License GnuCash Android is free software; you can redistribute it and/or modify it under the terms of the Apache license, version 2.0. 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.
113
AWS SDK for Android. For more information, see our web site:
# AWS SDK for Android [![DiscordChat](https://img.shields.io/discord/308323056592486420?logo=discord)](https://discord.gg/amplify) [![GitHub release](https://img.shields.io/github/release/aws-amplify/aws-sdk-android.svg)](https://github.com/aws-amplify/aws-sdk-android/releases) [![Maven Central](https://img.shields.io/maven-central/v/com.amazonaws/aws-android-sdk-core.svg)](https://search.maven.org/search?q=a:aws-android-sdk-core) For new projects, we recommend interacting with AWS using the [Amplify Framework](https://docs.amplify.aws/start/q/integration/android). The AWS SDK for Android is a collection of low-level libraries for direct interaction with AWS backend services. For use cases not covered by the Amplify Framework, you may directly integrate these clients into your Android app. ## Installation The AWS SDK for Android can be directly embedded via `.aar` files, or you can download it from the Maven Central repository, by integrating it into your Android project's Gradle files. ### From Maven We recommend obtaining the dependency from Maven. To do so, add a dependency to your app's (module-level) `build.gradle`, in the `dependencies` section: ```groovy dependencies { implementation 'com.amazonaws:aws-android-sdk-SERVICE:2.x.y' } ``` Above, SERVICE might be `s3`, `ddb`, `pinpoint`, etc. A full list is provided below. ## Available Modules * apigateway-core * auth-core * auth-facebook * auth-google * auth-ui * auth-userpools * chimesdkidentity * chimesdkmessaging * cloudwatch * cognitoauth * cognitoidentityprovider * cognitoidentityprovider-asf * comprehend * connect * connectparticipant * core * ddb * ddb-document * ddb-mapper * ec2 * iot * kinesis * kinesisvideo * kinesisvideo-archivedmedia * kinesisvideo-signaling * kms * lambda * lex * location * logs * machinelearning * mobile-client * pinpoint * polly * rekognition * s3 * sagemaker-runtime * sdb * ses * sns * sqs * testutils * textract * transcribe * translate ## SDK Fundamentals There are a few fundamentals that are helpful to know when developing against the AWS SDK for Android. * Never embed credentials in an Android application. It is trivially easy to decompile applications and steal embedded credentials. Always use temporarily vended credentials from services such as Amazon Cognito Identity. * Unless explicitly stated, calls are synchronous and must be taken off of the main thread. * Unless explicitly stated, calls can always throw an AmazonServiceException or an AmazonClientException (depending on if the exception is generated by the service or the client respectively). * The SDK will handle re-trying requests automatically, but unless explicitly stated will throw an exception if it cannot contact AWS. * We are always looking to help, please feel free to open an [issue](https://github.com/aws-amplify/aws-sdk-android/issues). ## Versioning The Android SDK is versioned like `2.x.y`. `2` is a product identifier that never changes. `x` is bumped when there are breaking changes. `y` is bumped for not-breaking bugfixes, or for the introduction of new features/capabilities. ## Building the SDK ### Pre-requisites The AWS Core Runtime (`aws-android-sdk-core`) module builds against Android API Level 23. Please download and install Android API Level 23 through SDK Manager in Android Studio, before building the SDK. Set the `ANDROID_HOME` environment variable, to the root directory of your Android SDK installation. _For example_, on a Mac OS X where Android Studio has been installed, the SDK comes bundled with it. ```shell export ANDROID_HOME="$HOME/Library/Android/sdk" ``` ### Build ```shell ./gradlew build ``` ### Consuming Development Versions Once you've built the SDK, you can manually install the SDK by publishing its artifacts to your local Maven repository. The local Maven repository is usually found in your home directory at `~/.m2/repository`. To publish the outputs of the build, execute the following command from the root of the `amplify-android` project: ```shell ./gradlew publishToMavenLocal ``` After this, you can use the published development artifacts from an app. To do so, specify `mavenLocal()` inside the app's top-level `build.gradle(Project)` file: ```gradle buildscript { repositories { mavenLocal() // this should ideally appear before other repositories } dependencies { classpath 'com.android.tools.build:gradle:4.0.1' } } allprojects { repositories { mavenLocal() // this should ideally appear before other repositories } } ``` Then, find the `VERSION_NAME` of the *library* inside `gradle.properties` file. Use the above version to specify dependencies in your *app*'s `build.gradle (:app)` file: ``` dependencies { implementation 'com.amazonaws:aws-android-sdk-SERVICE:VERSION_NAME' } ``` ## Talk to Us [Come chat with us on our Discord Channel](https://discord.gg/amplify). Report bugs to our [GitHub Issues](https://github.com/aws-amplify/aws-sdk-android/issues) page. ## Author Amazon Web Services ## License See the [`LICENSE.txt`](https://github.com/aws-amplify/aws-sdk-android/blob/main/LICENSE.txt) for more info.
114
Picocli is a modern framework for building powerful, user-friendly, GraalVM-enabled command line apps with ease. It supports colors, autocompletion, subcommands, and more. In 1 source file so apps can include as source & avoid adding a dependency. Written in Java, usable from Groovy, Kotlin, Scala, etc.
<p align="center"><img src="docs/images/logo/horizontal-400x150.png" alt="picocli" height="150px"></p> [![GitHub Release](https://img.shields.io/github/release/remkop/picocli.svg)](https://github.com/remkop/picocli/releases) [![Maven Central](https://img.shields.io/maven-central/v/info.picocli/picocli.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22info.picocli%22%20AND%20a:%22picocli%22) [![GitHub Actions Build Status](https://github.com/remkop/picocli/actions/workflows/ci.yml/badge.svg)](https://github.com/remkop/picocli/actions/workflows/ci.yml) [![Tests](https://gist.githubusercontent.com/remkop/36bc8a3b4395f2fbdb9bc271e97ba2dd/raw/badge.svg)](https://github.com/remkop/picocli/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/remkop/picocli/branch/master/graph/badge.svg)](https://codecov.io/gh/remkop/picocli) [![Follow @remkopopma](https://img.shields.io/twitter/follow/remkopopma.svg?style=social)](https://twitter.com/intent/follow?screen_name=remkopopma) [![Follow @picocli](https://img.shields.io/twitter/follow/picocli.svg?style=social)](https://twitter.com/intent/follow?screen_name=picocli) [![Follow picocli on StackShare](https://img.shields.io/badge/Follow%20on-StackShare-blue.svg?logo=stackshare&style=flat)](https://stackshare.io/picocli) # picocli - a mighty tiny command line interface Picocli aims to be the easiest-to-use way to create rich command line applications that can run on and off the JVM. Considering picocli? Check [what happy users say](https://github.com/remkop/picocli/wiki/Feedback-from-Users) about picocli. Picocli is a modern library and framework, written in Java, that contains both an annotations API and a programmatic API. It features usage help with [ANSI colors and styles](https://picocli.info/#_ansi_colors_and_styles), [TAB autocompletion](https://picocli.info/autocomplete.html) and nested subcommands. In a single file, so you can include it _in source form_. This lets users run picocli-based applications without requiring picocli as an external dependency. Picocli-based applications can be ahead-of-time compiled to a <img src="https://www.graalvm.org/resources/img/logo-colored.svg" alt="GraalVM"> [native image](https://picocli.info/#_graalvm_native_image), with extremely fast startup time and lower memory requirements, which can be distributed as a single executable file. Picocli comes with an [annotation processor](https://picocli.info/#_annotation_processor) that automatically Graal-enables your jar during compilation. Picocli applications can be very compact with no boilerplate code: your command (or subcommand) can be executed with a [single line of code](#example "(example below)"). Simply implement `Runnable` or `Callable`, or put the business logic of your command in a `@Command`-annotated method. <a id="picocli_demo"></a> ![Picocli Demo help message with ANSI colors](docs/images/picocli.Demo.png?raw=true) Picocli makes it easy to follow [Command Line Interface Guidelines](https://clig.dev/#guidelines). How it works: annotate your class and picocli initializes it from the command line arguments, converting the input to strongly typed data. Supports git-like [subcommands](https://picocli.info/#_subcommands) (and nested [sub-subcommands](https://picocli.info/#_nested_sub_subcommands)), any option prefix style, POSIX-style [grouped short options](https://picocli.info/#_short_posix_options), custom [type converters](https://picocli.info/#_custom_type_converters), [password options](https://picocli.info/#_interactive_password_options) and more. Picocli distinguishes between [named options](https://picocli.info/#_options) and [positional parameters](https://picocli.info/#_positional_parameters) and allows _both_ to be [strongly typed](https://picocli.info/#_strongly_typed_everything). [Multi-valued fields](https://picocli.info/#_multiple_values) can specify an exact number of parameters or a [range](https://picocli.info/#_arity) (e.g., `0..*`, `1..2`). Supports [Map options](https://picocli.info/#_maps) like `-Dkey1=val1 -Dkey2=val2`, where both key and value can be strongly typed. Parser [tracing](https://picocli.info/#_tracing) facilitates troubleshooting. Command-line [argument files](https://picocli.info/#AtFiles) (@-files) allow applications to handle very long command lines. Generates polished and easily tailored [usage help](https://picocli.info/#_usage_help) and [version help](https://picocli.info/#_version_help), using [ANSI colors](https://picocli.info/#_ansi_colors_and_styles) where possible. Requires at minimum Java 5, but is designed to facilitate the use of Java 8 lambdas. Tested on all [Java versions between 5 and 18-ea](https://github.com/remkop/picocli/actions/workflows/ci.yml) (inclusive). Picocli-based command line applications can have [TAB autocompletion](https://picocli.info/autocomplete.html), interactively showing users what options and subcommands are available. When an option has [`completionCandidates`](https://picocli.info/#_completion_candidates_variable) or has an `enum` type, autocompletion can also suggest option values. Picocli can generate completion scripts for bash and zsh, and offers [`picocli-shell-jline2`](picocli-shell-jline2/README.md) and [`picocli-shell-jline3`](picocli-shell-jline3/README.md) modules with JLine `Completer` implementations for building interactive shell applications. Unique features in picocli include support for [negatable options](https://picocli.info/#_negatable_options), advanced [quoted values](https://picocli.info/#_quoted_values), and [argument groups](https://picocli.info/#_argument_groups). Argument groups can be used to create mutually [exclusive](https://picocli.info/#_mutually_exclusive_options) options, mutually [dependent](https://picocli.info/#_mutually_dependent_options) options, option [sections](https://picocli.info/#_option_sections_in_usage_help) in the usage help message and [repeating composite arguments](https://picocli.info/#_repeating_composite_argument_groups) like `([-a=<a> -b=<b> -c=<c>] (-x | -y | -z))...`. For advanced use cases, applications can access the picocli command object model with the [`@Spec` annotation](https://picocli.info/#spec-annotation), and implement [custom parameter processing](https://picocli.info/#_custom_parameter_processing) for option parameters if the built-in logic is insufficient. Picocli-based applications can easily [integrate](https://picocli.info/#_dependency_injection) with Dependency Injection containers. The [Micronaut](https://micronaut.io/) microservices framework has [built-in support](https://docs.micronaut.io/latest/guide/index.html#commandLineApps) for picocli. [Quarkus](https://quarkus.io/) has a [Command Mode with Picocli](https://quarkus.io/guides/picocli) extension for facilitating the creation of picocli-based CLI applications with Quarkus. Picocli ships with a [`picocli-spring-boot-starter` module](https://github.com/remkop/picocli/tree/main/picocli-spring-boot-starter) that includes a `PicocliSpringFactory` and Spring Boot auto-configuration to use Spring dependency injection in your picocli command line application. The user manual has examples of integrating with [Guice](https://picocli.info/#_guice_example), [Spring Boot](https://picocli.info/#_spring_boot_example), [Micronaut](https://picocli.info/#_micronaut_example), [Quarkus](https://picocli.info/#_quarkus_example) and with containers that comply to [CDI 2.0 specification](https://picocli.info/#_cdi_2_0_jsr_365) (JSR 365). ### Releases * [All Releases](https://github.com/remkop/picocli/releases) * Latest: 4.7.1 [Release Notes](https://github.com/remkop/picocli/releases/tag/v4.7.1) * Older: Picocli 4.0 [Release Notes](https://github.com/remkop/picocli/releases/tag/v4.0.0) * Older: Picocli 3.0 [Release Notes](https://github.com/remkop/picocli/releases/tag/v3.0.0) * Older: Picocli 2.0 [Release Notes](https://github.com/remkop/picocli/releases/tag/v2.0.0) ### Documentation * [4.x User manual: https://picocli.info](https://picocli.info) * [4.x Quick Guide](https://picocli.info/quick-guide.html) * [4.x API Javadoc](https://picocli.info/apidocs/) * [PREVIEW: Modular Javadoc for all artifacts (4.7.1-SNAPSHOT)](https://picocli.info/apidocs-all/) * [Command line autocompletion](https://picocli.info/autocomplete.html) * [Programmatic API](https://picocli.info/picocli-programmatic-api.html) * [FAQ](https://github.com/remkop/picocli/wiki/FAQ) * [GraalVM AOT Compilation to Native Image](https://picocli.info/picocli-on-graalvm.html) <img src="https://www.graalvm.org/resources/img/logo-colored.svg" > ### Older * ~~[3.x User manual](https://picocli.info/man/3.x)~~ * ~~[3.x Quick Guide](https://picocli.info/man/3.x/quick-guide.html)~~ * ~~[3.x API Javadoc](https://picocli.info/man/3.x/apidocs/)~~ * ~~[2.x User manual](https://picocli.info/man/2.x)~~ * ~~[2.x API Javadoc](https://picocli.info/man/2.x/apidocs/)~~ * ~~[1.x User manual](https://picocli.info/man/1.x)~~ ### Articles & Presentations #### English * [6 things you can do with JBang but you canโ€™t with Shell](http://www.mastertheboss.com/java/jbang-vs-jshell/) (2022-02-28) by [F.Marchioni](http://www.mastertheboss.com/author/admin/). * [VIDEO][Kotlin, CLIs and StarWars! - An introduction to creating CLI applications with Kotlin using Picocli](https://fosdem.org/2022/schedule/event/kotlin_clis_and_starwars/?utm_medium=social&utm_source=twitter&utm_campaign=postfity&utm_content=postfity77511) (2022-02-05) by [Julien Lengrand-Lambert](https://fosdem.org/2022/schedule/speaker/julien_lengrand_lambert/). * [VIDEO][Autocomplete Java CLI using Picocli](https://www.youtube.com/watch?v=tCrQqgOYszQ) (2022-01-24) by [raksrahul](https://www.youtube.com/channel/UCpYkDrjOq3xtt0Uyg9tEqvw). * [Picocli โ€“ Easiness for CLI arguments in Java](https://blog.adamgamboa.dev/picocli-easiness-for-cli-arguments-in-java/) (2021-10-27) by [agamboa](https://blog.adamgamboa.dev/author/agamboa/). * [Building Command Line Interfaces with Kotlin using picoCLI](https://foojay.io/today/building-command-line-interfaces-with-kotlin-using-picocli/) (2021-09-23) by [Julien Lengrand-Lambert](https://foojay.io/today/author/jlengrand/). * [VIDEO][Create Java CLI applications with picocli](https://www.youtube.com/watch?v=PaxBXABJIzY) (2021-09-14) by [coder4life](https://www.youtube.com/channel/UCt9lHt5bMpafypEDwj6J2WQ). * [PICOCLI](https://www.linkedin.com/pulse/picocli-sybren-boland/) (2021-06-30) by [Sybren Boland](https://www.linkedin.com/in/sybrenboland/). * [Picocli | Create your first Kotlin /JVM CLI application with GraalVM](https://manserpatrice.medium.com/picocli-create-your-first-kotlin-jvm-cli-application-with-graalvm-a7fea4da7e2) (2021-02-13) by [manserpatrice](https://manserpatrice.medium.com/). * [VIDEO] [Building kubectl plugins with Quarkus, picocli, fabric8io and jbang](https://www.youtube.com/watch?v=ZL29qrpk_Kc) (2021-01-22) by [Sรฉbastien Blanc](https://twitter.com/sebi2706). * [VIDEO] [J-Fall Virtual 2020: Julien Lengrand - An introduction to creating CLI applications using picoCLI](https://www.youtube.com/watch?v=Rc_D4OTKidU&list=PLpQuPreMkT6D36w9d13uGpIPi5nf9I_0c&index=13) (2020-12-07) by [Julien Lengrand-Lambert](https://twitter.com/jlengrand). This was the top rated talk for [@nljug](https://twitter.com/nljug) #jfall virtual 2020! Congrats, Julien! * [Paginate results in a command line application using picoCLI](https://lengrand.fr/paginate-results-in-a-jvm-cli-application-using-picocli/) (2020-11-17) by [Julien Lengrand-Lambert](https://twitter.com/jlengrand). * [CLI applications with GraalVM Native Image](https://medium.com/graalvm/cli-applications-with-graalvm-native-image-d629a40aa0be) (2020-11-13) by [Oleg ล elajev](https://twitter.com/shelajev). * [Picocli subcommands - One program, many purposes](https://aragost.com/blog/java/picocli-subcommands.html) (2020-09-22) by [Jonas Andersen](https://twitter.com/PrimusAlgo). * [Native CLI with Picocli and GraalVM](https://dev.to/jbebar/native-cli-with-picocli-and-graalvm-566m) (2020-08-20) by [jbebar](https://dev.to/jbebar). * [How to build a CLI app in Java using jbang and picocli](https://www.twilio.com/blog/cli-app-java-jbang-picocli) (2020-08-13) by [Matthew Gilliard](https://twitter.com/MaximumGilliard). * [Building a GitHub Dependents Scraper with Quarkus and Picocli](https://blog.marcnuri.com/github-dependents-scraper-quarkus-picocli/) (2020-07-31) by [Marc Nuri](https://twitter.com/MarcNuri). * [Building a decent Java CLI](https://atextor.de/2020/07/27/building-a-decent-java-cli.html) (2020-07-27) by [Andreas Textor](https://twitter.com/atextor). * [VIDEO] (Another very well-produced video by Szymon Stepniak) [Implementing OAuth 2.0 in a Java command-line app using Micronaut, Picocli, and GraalVM](https://www.youtube.com/watch?v=js5H9UbmmMY) (2020-07-23) by [Szymon Stepniak](https://e.printstacktrace.blog/) ([YouTube channel](https://www.youtube.com/channel/UCEf8e5YAYnowq-2deW4tpsw)). * [Micronaut, Picocli, and GraalVM](https://e.printstacktrace.blog/building-stackoverflow-cli-with-java-11-micronaut-picocli-and-graalvm/) (2020-07-08) by [Szymon Stepniak](https://e.printstacktrace.blog/). * [VIDEO] (Extremely well-produced and informative, recommended!) [Building command-line app with Java 11, Micronaut, Picocli, and GraalVM](https://www.youtube.com/watch?v=Xdcg4Drg1hc) (2020-07-01) by [Szymon Stepniak](https://e.printstacktrace.blog/) ([YouTube channel](https://www.youtube.com/channel/UCEf8e5YAYnowq-2deW4tpsw)). * [AUDIO] [Scala Valentines #2](https://scala.love/scala-valentines-2/) (2020-06-21) Podcast talks about picocli (from 18:11). * [How to create a command line tool using Java?](https://fullstackdeveloper.guru/2020/06/18/how-to-create-a-command-line-tool-using-java/) (2020-06-18) by [Vijay SRJ](https://twitter.com/FullStackDevel6). * [Command-line tools with Quarkus and Picocli](https://quarkify.net/command-line-tools-with-quarkus-and-picocli/) (2020-06-08) by [Dmytro Chaban](https://twitter.com/dmi3coder). * Quarkus guide for [Quarkus command mode with picocli](https://quarkus.io/guides/picocli), thanks to a picocli extension by [Michaล‚ Gรณrniewski](https://github.com/mgorniew) included in [Quarkus 1.5](https://quarkus.io/blog/quarkus-1-5-final-released/) (2020-06-03). * [Native images with Micronaut and GraalVM](https://dev.to/stack-labs/native-images-with-micronaut-and-graalvm-4koe) (2020-06-01) by [ฮ›\: Olivier Revial](https://twitter.com/pommeDouze). * [CLI applications with Micronaut and Picocli](https://dev.to/stack-labs/cli-applications-with-micronaut-and-picocli-4mc8) (2020-06-01) by [ฮ›\: Olivier Revial](https://twitter.com/pommeDouze). * [Picocli introduction - Modern Java command-line parsing](https://aragost.com/blog/java/picocli-introduction.html) (2020-05-19) by [Jonas Andersen](https://twitter.com/PrimusAlgo). * [Building Native Covid19 Tracker CLI using Java, PicoCLI & GraalVM](https://aboullaite.me/java-covid19-cli-picocli-graalvm/) (2020-05-11) by [Mohammed Aboullaite](https://aboullaite.me/author/mohammed/). * [Quarkus Command mode with Picocli](https://quarkify.net/quarkus-command-mode-with-picocli/) (2020-04-27) by [Dmytro Chaban](https://twitter.com/dmi3coder). * [Creating CLI tools with Scala, Picocli and GraalVM](https://medium.com/@takezoe/creating-cli-tools-with-scala-picocli-and-graalvm-ffde05bbd01d) (2020-03-09) by [Naoki Takezoe](https://twitter.com/takezoen) * [Building native Java CLIs with GraalVM, Picocli, and Gradle](https://medium.com/@mitch.seymour/building-native-java-clis-with-graalvm-picocli-and-gradle-2e8a8388d70d) (2020-03-08) by [Mitch Seymour](https://medium.com/@mitch.seymour) * [Build Great Native CLI Apps in Java with Graalvm and Picocli](https://www.infoq.com/articles/java-native-cli-graalvm-picocli/) (2020-03-07) * [Picocli Structured Objects](https://gist.github.com/hanslovsky/8276da86c53bc6d95bf01447cd5cb2b7#file-00_picocli-structured-objects-md) (2019-09-10) by [Philipp Hanslovsky](https://gist.github.com/hanslovsky) explains how to use picocli's support for repeating argument groups to add or configure structured objects from the command line. * [Create a Java Command Line Program with Picocli|Baeldung](https://www.baeldung.com/java-picocli-create-command-line-program) (2019-05-07) by [Franรงois Dupire](https://www.baeldung.com/author/francois-dupire/). * A whirlwind tour of picocli [JAX Magazine "Putting the spotlight on Java tools"](https://jaxenter.com/jax-mag-java-tools-157592.html) (2019-04-08). * [An Introduction to PicoCLI](https://devops.datenkollektiv.de/an-introduction-to-picocli.html) (2019-02-10) by [devop](https://devops.datenkollektiv.de/author/devop.html). * [Corda CLI UX (User Experience) Guide](https://docs.corda.net/head/cli-ux-guidelines.html) (2018 by R3 Limited) gives useful advice. * [Develop a CLI tool using groovy scripts](https://medium.com/@chinthakadinadasa/develop-a-cli-tool-using-groovy-scripts-a7d545eecddd) (2018-10-26) by [Chinthaka Dinadasa](https://medium.com/@chinthakadinadasa). * [Migrating from Commons CLI to picocli](https://picocli.info/migrating-from-commons-cli.html). You won't regret it! :-) (also on: [DZone](https://dzone.com/articles/migrating-from-commons-cli-to-picocli) and [Java Code Geeks](https://www.javacodegeeks.com/2018/11/migrating-commons-cli-picocli.html)). * [Groovy 2.5 CliBuilder Renewal](https://picocli.info/groovy-2.5-clibuilder-renewal.html) (also on [blogs.apache.org](https://blogs.apache.org/logging/entry/groovy-2-5-clibuilder-renewal)). In two parts: [Part 1](https://picocli.info/groovy-2.5-clibuilder-renewal-part1.html) (also on: [DZone](https://dzone.com/articles/groovy-25-clibuilder-renewal), [Java Code Geeks](https://www.javacodegeeks.com/2018/06/groovy-clibuilder-renewal-part-1.html)), [Part 2](https://picocli.info/groovy-2.5-clibuilder-renewal-part2.html) (also on: [DZone](https://dzone.com/articles/groovy-25-clibuilder-renewal-part-2), [Java Code Geeks](https://www.javacodegeeks.com/2018/06/groovy-clibuilder-renewal-part-2.html)). * Micronaut user manual for running microservices [standalone with picocli](https://docs.micronaut.io/snapshot/guide/index.html#commandLineApps). * [Java Command-Line Interfaces (Part 30): Observations](https://marxsoftware.blogspot.jp/2017/11/java-cmd-line-observations.html) by Dustin Marx about picocli 2.0.1 (also on: [DZone](https://dzone.com/articles/java-command-line-interfaces-part-30-finale-observations), [Java Code Geeks](https://www.javacodegeeks.com/2017/11/java-command-line-interfaces-part-30-observations.html)) * [Java Command-Line Interfaces (Part 10): Picocli](https://marxsoftware.blogspot.jp/2017/08/picocli.html) by Dustin Marx about picocli 0.9.7 (also on: [DZone](https://dzone.com/articles/java-command-line-interfaces-part-10-picocli), [Java Code Geeks](https://www.javacodegeeks.com/2017/08/java-command-line-interfaces-part-10-picocli.html)) * [Picocli 2.0: Groovy Scripts on Steroids](https://picocli.info/picocli-2.0-groovy-scripts-on-steroids.html) (also on: [DZone](https://dzone.com/articles/picocli-v2-groovy-scripts-on-steroids), [Java Code Geeks](https://www.javacodegeeks.com/2018/01/picocli-2-0-groovy-scripts-steroids.html)) * [Picocli 2.0: Do More With Less](https://picocli.info/picocli-2.0-do-more-with-less.html) (also on: [DZone](https://dzone.com/articles/whats-new-in-picocli-20), [Java Code Geeks](https://www.javacodegeeks.com/2018/01/picocli-2-0-less.html)) * [Announcing picocli 1.0](https://picocli.info/announcing-picocli-1.0.html) (also on: [DZone](https://dzone.com/articles/announcing-picocli-10)) #### ั€ัƒััะบะธะน * [ะ’ั‹ะฑะพั€ ะฝะตะพะฑั…ะพะดะธะผั‹ั… ะพะฟั†ะธะน Picocli ะฝะฐ ะพัะฝะพะฒะต ะพัะฝะพะฒะฝะพะณะพ ะฒะฐั€ะธะฐะฝั‚ะฐ](https://coderoad.ru/61665865/%D0%92%D1%8B%D0%B1%D0%BE%D1%80-%D0%BD%D0%B5%D0%BE%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D0%BC%D1%8B%D1%85-%D0%BE%D0%BF%D1%86%D0%B8%D0%B9-Picocli-%D0%BD%D0%B0-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%B5-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%BD%D0%BE%D0%B3%D0%BE-%D0%B2%D0%B0%D1%80%D0%B8%D0%B0%D0%BD%D1%82%D0%B0) (2020-05-07) * [ะ˜ะฝั‚ะตั€ั„ะตะนัั‹ ะบะพะผะฐะฝะดะฝะพะน ัั‚ั€ะพะบะธ Java: picocli](https://habr.com/ru/company/otus/blog/419401/) (2018-08-06): Russian translation by [MaxRokatansky](https://habr.com/ru/users/MaxRokatansky/) of Dustin Marx' blog post. #### Espaรฑol * [Quarkus + Picocli: Web scaper para extraer proyectos dependientes en GitHub](https://blog.marcnuri.com/quarkus-picocli-web-scaper-dependientes-github/) (2020-08-15) by [Marc Nuri](https://twitter.com/MarcNuri). * [Quarkus - Introducciรณn: picocli](https://gerardo.dev/aws-quarkus-picocli.html) (2020-06-15) by [Gerardo Arroyo](https://twitter.com/codewarrior506). * [VIDEO] [Picocli - Spring Boot example](https://youtu.be/y9ayfjfrTF4) (2020-05-24) 7-minute quick introduction by Gonzalo H. Mendoza. #### Franรงais * [Application mobile: Crรฉez de superbes applications CLI natives en Java avec Graalvm et Picocli](https://seodigitalmarketing.net/application-mobile-creez-de-superbes-applications-cli-natives-en-java-avec-graalvm-et-picocli/) (2020-05-07) Translation of [Build Great Native CLI Apps in Java with Graalvm and Picocli](https://www.infoq.com/articles/java-native-cli-graalvm-picocli/) by [bouf1450](https://seodigitalmarketing.net/author/bouf1450/). * [VIDEO] [Des applications en ligne de commande avec Picocli et GraalVM (N. Peters)](https://www.youtube.com/watch?v=8ENbMwkaFyk) (2019-05-07): 15-minute presentation by Nicolas Peters during Devoxx FR. Presentation slides are [available on GitHub](https://t.co/tXhtpTpAff?amp=1). #### Portuguรชs * [Desenvolva aplicaรงรตes CLI nativas em Java com Graalvm e Picocli](https://www.infoq.com/br/articles/java-native-cli-graalvm-picocli/) (2020-08-28): Portuguese translation of [Build Great Native CLI Apps in Java with Graalvm and Picocli](https://www.infoq.com/articles/java-native-cli-graalvm-picocli/), thanks to [Rodrigo Ap G Batista](https://www.infoq.com/br/profile/Rodrigo-Ap-G-Batista/). * [VIDEO] [Quarkus #40: Command Mode com Picocli](https://www.youtube.com/watch?v=LweGDh-Jxlc) (2020-06-23): 13-minute presentation by [Vinรญcius Ferraz](https://www.youtube.com/channel/UCJNOHl-pTTTj4S9yq60Ps9A) (@viniciusfcf). #### ๆ—ฅๆœฌ่ชž * [CLI applications with GraalVM Native Image](https://logico-jp.io/2020/11/21/cli-applications-with-graalvm-native-image/) (2020-11-21) translation by [Logico_jp](https://logico-jp.io/who-is-logico/) of Oleg ล elajev's [post](https://medium.com/graalvm/cli-applications-with-graalvm-native-image-d629a40aa0be). * [Picocli + Kotlin + graalvm-native-image plugin ใงใƒใ‚คใƒ†ใ‚ฃใƒ–ใƒ„ใƒผใƒซใ‚’ไฝœใ‚‹](https://mike-neck.hatenadiary.com/entry/2020/04/24/090000) (2020-04-24) blog post by [mike-neck](https://mike-neck.hatenadiary.com/about) ([ๅผ•ใใ“ใ‚‚ใ‚ŠๆŒ็”ฐ](https://twitter.com/mike_neck) on Twitter). * [pythonใฎArgumentParserใ‚ˆใ†ใชไฝฟใ„ๅฟƒๅœฐ๏ผpicocliใฎใ”็ดนไป‹](https://lab.astamuse.co.jp/entry/2020/04/15/115000) (2020-04-15) by [@astamuseLab](https://lab.astamuse.co.jp/) * [Javaใฎใ‚ณใƒžใƒณใƒ‰ใƒฉใ‚คใƒณใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณๅ‘ใ‘ใฎใƒ•ใƒฌใƒผใƒ ใƒฏใƒผใ‚ฏใ€picocliใง้Šใถ](https://kazuhira-r.hatenablog.com/entry/2020/03/07/013626) (2020-03-07) blog post by [ใ‹ใšใฒใ‚‰](https://twitter.com/kazuhira_r). * [KuromojiใฎCLIใ‚ณใƒžใƒณใƒ‰ใจpicocliใจGraalVM](https://blog.johtani.info/blog/2020/02/28/kuromoji-cli/) (2020-02-28) blog post by [@johtani](https://twitter.com/johtani). * [GraalVM, PicocliใจJavaใงใจใใ‚ใใƒใ‚คใƒ†ใ‚ฃใƒ–ใ‚ณใƒžใƒณใƒ‰ใƒฉใ‚คใƒณใ‚ขใƒ—ใƒชใ‚’ไฝœใ‚ใ†](https://remkop.github.io/presentations/20191123/) (2019-11-23) Slides for my presentation at Japan Java User Group's [JJUG CCC 2019 Fall](https://ccc2019fall.java-users.jp/) conference. * [Picocliใ‚’ไฝฟ็”จใ—ใฆJavaใ‚ณใƒžใƒณใƒ‰ใƒฉใ‚คใƒณใƒ—ใƒญใ‚ฐใƒฉใƒ ใ‚’ไฝœๆˆใ™ใ‚‹ - ้–‹็™บ่€…ใƒ‰ใ‚ญใƒฅใƒกใƒณใƒˆ](https://ja.getdocs.org/java-picocli-create-command-line-program/) (2019-10-18) * [GraalVM ใจ Picocliใง Javaใฎใƒใ‚คใƒ†ใ‚ฃใƒ–ใ‚ณใƒžใƒณใƒ‰ใƒฉใ‚คใƒณใ‚ขใƒ—ใƒชใ‚’ไฝœใ‚ใ†](https://remkop.github.io/presentations/20190906/) (2019-09-06) Slides for my lightning talk presentation at [ใ€ๆฑไบฌใ€‘JJUG ใƒŠใ‚คใƒˆใ‚ปใƒŸใƒŠใƒผ: ใƒ“ใƒผใƒซ็‰‡ๆ‰‹ใซLTๅคงไผš 9/6๏ผˆ้‡‘๏ผ‰](https://jjug.doorkeeper.jp/events/95987) * [Picocli๏ผ‹Spring Boot ใงใ‚ณใƒžใƒณใƒ‰ใƒฉใ‚คใƒณใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณใ‚’ไฝœๆˆใ—ใฆใฟใ‚‹](https://ksby.hatenablog.com/entry/2019/07/20/092721) (2019-07-20) by [ใ‹ใ‚“ใŒใ‚‹ใƒผใ•ใ‚“ใฎๆ—ฅ่จ˜](https://ksby.hatenablog.com/). * [GraalVM ใฎ native image ใ‚’ไฝฟใฃใฆ Java ใง็ˆ†้€Ÿ Lambda ใฎๅคขใ‚’่ฆ‹ใ‚‹](https://qiita.com/kencharos/items/69e43965515f368bc4a3) (2019-05-02) by [@kencharos](https://qiita.com/kencharos) #### ไธญๆ–‡ * [Javaๅ‘ฝไปค่กŒ็•Œ้ข๏ผˆ็ฌฌ10้ƒจๅˆ†๏ผ‰๏ผšpicocli](https://blog.csdn.net/dnc8371/article/details/106702365) (2020-06-07) translation by [dnc8371](https://blog.csdn.net/dnc8371). * [ๅฆ‚ไฝ•ๅ€ŸๅŠฉ Graalvm ๅ’Œ Picocli ๆž„ๅปบ Java ็ผ–ๅ†™็š„ๅŽŸ็”Ÿ CLI ๅบ”็”จ](https://www.infoq.cn/article/4RRJuxPRE80h7YsHZJtX) (2020-03-26): Chinese translation of [Build Great Native CLI Apps in Java with Graalvm and Picocli](https://www.infoq.com/articles/java-native-cli-graalvm-picocli/), thanks to [ๅผ ๅซๆปจ](https://www.infoq.cn/profile/1067660). * [ไปŽCommons CLI่ฟ็งปๅˆฐPicocli](https://blog.csdn.net/genghaihua/article/details/88529409) (2019-03-13): Chinese translation of Migrating from Commons CLI to picocli, thanks to [genghaihua](https://me.csdn.net/genghaihua). * [Picocli 2.0: SteroidsไธŠ็š„Groovy่„šๆœฌ](https://picocli.info/zh/picocli-2.0-groovy-scripts-on-steroids.html) * [Picocli 2.0: ไปฅๅฐ‘ๆฑ‚ๅคš](https://picocli.info/zh/picocli-2.0-do-more-with-less.html) ### Mailing List Join the [picocli Google group](https://groups.google.com/d/forum/picocli) if you are interested in discussing anything picocli-related and receiving announcements on new releases. ### Credit <img src="https://picocli.info/images/logo/horizontal-400x150.png" height="100"> [Reallinfo](https://github.com/reallinfo) designed the picocli logo! Many thanks! ### Commitments | This project follows [semantic versioning](https://semver.org/) and adheres to the **[Zero Bugs Commitment](https://github.com/classgraph/classgraph/blob/f24fb4e8f2e4f3221065d755be6e65d59939c5d0/Zero-Bugs-Commitment.md)**. | |------------------------| ## Adoption <div> <img src="https://picocli.info/images/groovy-logo.png" height="50"> <img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://objectcomputing.com/files/3416/2275/4315/micronaut_horizontal_black.svg" height="50"><img src="https://picocli.info/images/1x1.png" width="10"><img src="https://quarkus.io/assets/images/quarkus_logo_horizontal_rgb_reverse.svg" style="background-color:#33475b" height="50"><img src="https://picocli.info/images/1x1.png" width="10"><img src="https://picocli.info/images/junit5logo-172x50.png" height="50"> <img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://picocli.info/images/debian-logo-192x50.png" height="50"> <img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://spring.io/images/spring-logo.svg" height="50"> <img src="https://avatars0.githubusercontent.com/u/3299148?s=200&v=4" height="50"> <img src="https://avatars3.githubusercontent.com/u/39734771?s=200&v=4" height="50"> <img src="https://avatars3.githubusercontent.com/u/1453152?s=200&v=4" height="50"> <img src="https://avatars1.githubusercontent.com/u/201120?s=200&v=4" height="50"> <img src="https://avatars0.githubusercontent.com/u/6154722?s=200&v=4" height="50"> <img src="https://avatars3.githubusercontent.com/u/453694?s=200&v=4" height="50"> <img src="https://avatars0.githubusercontent.com/u/82592?s=200&v=4" height="50"> <img src="https://avatars0.githubusercontent.com/u/9312489?s=200&v=4" height="50"> <img src="https://avatars0.githubusercontent.com/u/59439283?s=200&v=4" height="50"> <img src="https://avatars1.githubusercontent.com/u/4186383?s=200&v=4" height="50"> <img src="https://redis.com/wp-content/uploads/2021/08/redis-logo.png" height="50"> <img src="https://picocli.info/images/karate-logo.png" height="50" width="50"/> <img src="https://picocli.info/images/checkstyle-logo-260x50.png" height="50"><img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://picocli.info/images/ballerina-logo.png" height="40"><img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://picocli.info/images/apache-hive-logo.png" height="50"><img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://hadoop.apache.org/hadoop-logo.jpg" height="50"><img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://picocli.info/images/apache-ozone-logo.png" height="50"> <img src="https://picocli.info/images/1x1.png" width="10"> <img src="https://picocli.info/images/stackshare-logo.png" height="50"> <img src="https://ignite.apache.org/images/Ignite_tm_Logo_blk_RGB.svg" height="50"> <img src="https://camo.githubusercontent.com/501aae78d282faf7a904bbb92f46eb8d19445ad5/687474703a2f2f736c696e672e6170616368652e6f72672f7265732f6c6f676f732f736c696e672e706e67" height="50"> <img src="https://avatars1.githubusercontent.com/u/541152?s=200&v=4" height="50"> <img src="https://camo.qiitausercontent.com/ec81e80366e061c8488b25c013003267b7a578d4/68747470733a2f2f71696974612d696d6167652d73746f72652e73332e616d617a6f6e6177732e636f6d2f302f3939352f33323331306534352d303537332d383534322d373035652d6530313138643434323632302e706e67" height="50"> <img src="https://mk0upserved13l70iwek.kinstacdn.com/media/Upserve_LS_Lockup_000000_RGB_Vertical.svg" height="50"> <img src="https://www.kloudtek.com/logo-dark.png" height="50"> <img src="https://www.schemacrawler.com/images/schemacrawler_logo.svg" height="50"> <img src="https://avatars1.githubusercontent.com/u/22600631?s=200&v=4" height="50"> <img src="https://fisco-bcos-documentation.readthedocs.io/en/latest/_static/images/FISCO_BCOS_Logo.svg" height="50"> <img src="https://avatars0.githubusercontent.com/u/35625214?s=200&v=4" height="50"> <img src="https://avatars1.githubusercontent.com/u/2386734?s=200&v=4" height="50"> <img src="https://www.e-contract.be/images/logo.svg" height="50"> <img src="https://present.co/images/[email protected]" height="50"> <img src="https://avatars2.githubusercontent.com/u/13641167?s=200&v=4" height="50"> <img src="https://files.pvs-studio.com/static/images/logo.svg" height="50"> <img src="https://concord.walmartlabs.com/assets/img/logo.png" height="50"> <img src="https://res-3.cloudinary.com/crunchbase-production/image/upload/c_lpad,h_120,w_120,f_auto,b_white,q_auto:eco/etxip1k2sx4sphvwgkdu" height="50"> <img src="https://www.minecraftforge.net/forum/uploads/set_resources_2/4eeef9d314eb4c008c0f37dacad2cdd5_logo.svg" height="50"> </div> * Picocli is now part of Groovy. From Groovy 2.5, all Groovy command line tools are picocli-based, and picocli is the underlying parser for Groovy's [CliBuilder DSL](https://groovy-lang.org/dsls.html#_clibuilder). * Picocli is now part of Micronaut. The Micronaut CLI has been rewritten with picocli, and Micronaut has dedicated support for running microservices [standalone with picocli](https://docs.micronaut.io/snapshot/guide/index.html#commandLineApps). See also [Micronaut Picocli Guide](https://micronaut-projects.github.io/micronaut-picocli/latest/guide/). * Quarkus now offers [Command mode with picocli](https://quarkus.io/guides/picocli). * Picocli is now part of JUnit 5. JUnit 5.3 migrated its `ConsoleLauncher` from jopt-simple to picocli to support @-files (argument files); this helps users who need to specify many tests on the command line and run into system limitations. * Debian now offers a [libpicocli-java package](https://tracker.debian.org/pkg/picocli). Thanks to [Miroslav Kravec](https://udd.debian.org/dmd/?kravec.miroslav%40gmail.com). * Picocli is used in the Intuit [Karate](https://github.com/intuit/karate) standalone JAR / executable. * Picocli is part of [Ballerina](https://ballerina.io/). Ballerina uses picocli for all its command line utilities. * Picocli is used in the [CheckStyle](https://checkstyle.org/cmdline.html) standalone JAR / executable from Checkstyle 8.15. * Picocli is included in the [OpenJDK Quality Outreach](https://wiki.openjdk.java.net/display/quality/Quality+Outreach) list of Free Open Source Software (FOSS) projects that actively test against OpenJDK builds. * Picocli is used in the Apache Hadoop Ozone/HDDS command line tools, the Apache Hive benchmark CLI, Apache [Ignite TensorFlow](https://github.com/apache/ignite), and Apache Sling [Feature Model Converter](https://github.com/apache/sling-org-apache-sling-feature-modelconverter). * Picocli is listed on [StackShare](https://stackshare.io/picocli). Please add it to your stack and add/upvote reasons why you like picocli! * Picocli is used in Pinterest [ktlint](https://ktlint.github.io/). * Picocli is used in Spring IO [nohttp-cli](https://github.com/spring-io/nohttp/tree/main/nohttp-cli). * The [MinecraftPicocli](https://github.com/Rubydesic/MinecraftPicocli) library facilitates the use of picocli in [Minecraft Forge](https://files.minecraftforge.net/). * [Simple Java Mail](https://www.simplejavamail.org/) now offers a picocli-based [CLI](https://www.simplejavamail.org/cli.html#navigation). * [jbang](https://github.com/maxandersen/jbang) not only uses picocli internally, but also has a CLI template to generate an initial script: use `jbang --init=cli helloworld.java` to generate a sample picocli-enabled jbang script. See [asciinema](https://asciinema.org/a/AVwA19yijKRNKEO0bJENN2ME3?autoplay=true&speed=2). * Picocli is the main library used in the CookieTemple [cli-java template](https://cookietemple.readthedocs.io/en/latest/available_templates/available_templates.html#cli-java) for building GraalVM native CLI executables in Java. See [this preview](https://user-images.githubusercontent.com/21954664/86740903-474a3000-c037-11ea-9ae3-1a8f7bf1743f.gif). * Picocli is [mentioned](https://clig.dev/#the-basics) in [Command Line Interface Guidelines](https://clig.dev/). <img src="https://picocli.info/images/downloads-202011.png"> Glad to see more people are using picocli. We must be doing something right. :-) ### Contribute by helping to promote picocli If you like picocli, help others discover picocli: #### Easy and impactful :sweat_smile: * Give picocli a star on GitHub! * Upvote my [StackOverflow answer](https://stackoverflow.com/a/43780433/1446916) to "How do I parse command line arguments in Java?" * Upvote my [Quora answer](https://www.quora.com/What-is-the-best-way-to-parse-command-line-arguments-with-Java/answer/Remko-Popma) to "What is the best way to parse command-line arguments with Java?" #### Spread the joy! :tada: * Tweet about picocli! What do you like about it? How has it helped you? How is it different from the alternatives? * Mention that your project uses picocli in the documentation of your project. * Show that your GitHub project uses picocli, with this badge in your README.md: [![picocli](https://img.shields.io/badge/picocli-4.7.1-green.svg)](https://github.com/remkop/picocli) ``` [![picocli](https://img.shields.io/badge/picocli-4.7.1-green.svg)](https://github.com/remkop/picocli) ``` #### Preach it! :muscle: * Perhaps the most impactful way to show people how picocli can make their life easier is to write a blog post or article, or even do a video! ## Example Annotate fields with the command line parameter names and description. Optionally implement `Runnable` or `Callable` to delegate error handling and requests for usage help or version help to picocli. For example: ```java import picocli.CommandLine; import picocli.CommandLine.Option; import picocli.CommandLine.Parameters; import java.io.File; @Command(name = "example", mixinStandardHelpOptions = true, version = "Picocli example 4.0") public class Example implements Runnable { @Option(names = { "-v", "--verbose" }, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.") private boolean[] verbose = new boolean[0]; @Parameters(arity = "1..*", paramLabel = "FILE", description = "File(s) to process.") private File[] inputFiles; public void run() { if (verbose.length > 0) { System.out.println(inputFiles.length + " files to process..."); } if (verbose.length > 1) { for (File f : inputFiles) { System.out.println(f.getAbsolutePath()); } } } public static void main(String[] args) { // By implementing Runnable or Callable, parsing, error handling and handling user // requests for usage help or version help can be done with one line of code. int exitCode = new CommandLine(new Example()).execute(args); System.exit(exitCode); } } ``` Implement `Runnable` or `Callable`, and your command can be [executed](https://picocli.info/#execute) in one line of code. The example above uses the `CommandLine.execute` method to parse the command line, handle errors, handle requests for usage and version help, and invoke the business logic. Applications can call `System.exit` with the returned exit code to signal success or failure to their caller. ```bash $ java Example -v inputFile1 inputFile2 2 files to process... ``` The `CommandLine.execute` method automatically prints the usage help message if the user requested help or when the input was invalid. ![Usage help message with ANSI colors](docs/images/ExampleUsageANSI.png?raw=true) This can be customized in many ways. See the user manual [section on Executing Commands](https://picocli.info/#execute) for details. ## Usage Help with ANSI Colors and Styles Colors, styles, headers, footers and section headings are easily [customized with annotations](https://picocli.info/#_ansi_colors_and_styles). For example: ![Longer help message with ANSI colors](docs/images/UsageHelpWithStyle.png?raw=true) See the [source code](https://github.com/remkop/picocli/blob/v0.9.4/src/test/java/picocli/Demo.java#L337). ## Usage Help API Picocli annotations offer many ways to customize the usage help message. If annotations are not sufficient, you can use picocli's [Help API](https://picocli.info/#_usage_help_api) to customize even further. For example, your application can generate help like this with a custom layout: ![Usage help message with two options per row](docs/images/UsageHelpWithCustomLayout.png?raw=true) See the [source code](https://github.com/remkop/picocli/blob/main/src/test/java/picocli/CustomLayoutDemo.java#L61). ## Download You can add picocli as an external dependency to your project, or you can include it as source. See the [source code](https://github.com/remkop/picocli/blob/main/src/main/java/picocli/CommandLine.java). Copy and paste it into a file called `CommandLine.java`, add it to your project, and enjoy! ### Gradle ``` implementation 'info.picocli:picocli:4.7.1' ``` ### Maven ``` <dependency> <groupId>info.picocli</groupId> <artifactId>picocli</artifactId> <version>4.7.1</version> </dependency> ``` ### Scala SBT ``` libraryDependencies += "info.picocli" % "picocli" % "4.7.1" ``` ### Ivy ``` <dependency org="info.picocli" name="picocli" rev="4.7.1" /> ``` ### Grape ```groovy @Grapes( @Grab(group='info.picocli', module='picocli', version='4.7.1') ) ``` ### Leiningen ``` [info.picocli/picocli "4.7.1"] ``` ### Buildr ``` 'info.picocli:picocli:jar:4.7.1' ``` ### JBang ``` //DEPS info.picocli:picocli:4.7.1 ```
115
A powerful and easy-to-use operational logging system that supports analysis of changes in object properties. ๅผบๅคงไธ”ๆ˜“็”จ็š„ๆ“ไฝœๆ—ฅๅฟ—่ฎฐๅฝ•็ณป็ปŸ,ๆ”ฏๆŒๅฏน่ฑกๅฑžๆ€ง็š„ๅ˜ๅŒ–ๅˆ†ๆžใ€‚
<div align="left"> <img src="./pic/ObjectLogger.png" height="80px" alt="ObjectLogger" > </div> # [ObjectLogger](https://github.com/yeecode/ObjectLogger) ![language](https://img.shields.io/badge/language-java-green.svg) ![version](https://img.shields.io/badge/mvn-3.1.1-blue.svg?style=flat) [![codebeat badge](https://codebeat.co/badges/94beca78-0817-4a27-9544-326afe35339f)](https://codebeat.co/projects/github-com-yeecode-objectlogger-master) ![license](https://img.shields.io/badge/license-Apache-brightgreen.svg) The powerful and easy-to-use object log system, supports writing and querying of object attribute changes. --- [ไธญๆ–‡่ฏดๆ˜Ž](./README_CN.md) --- # 1 Introduction ObjectLogger is powerful and easy-to-use object log system, which supports writing and querying of object attribute changes. It can be used in many scenarios, such as user operation log record, object attribute change record and so on. <div align=center> <img width="90%" src="./pic/react_en.png"/> </div> The system has the following characteristics: - It supports logging and query, and developers only need to redevelop the web page before using. - It is not coupled with business systems.Pluggable use, without affecting the main business process. - It can be used by multiple business systems at the same time without affecting each other. - It can be started directly using the jar package; the business system is supported by the official Maven plug-in. - It can automatically parse the attribute changes of objects and support the comparison of rich text. - It supports extension of more object attribute types. The project consists of four parts: - ObjectLoggerClient: A jar package that can be integrated into a business system. It can complete the log analysis and transmission of the business system. You can obtain the jar package from Maven repository. - ObjectLoggerServer: A web service which needs the support of a database. It can accept log information sent by ObjectLoggerClient and provide log query function. - react-object-logger:A React component for displaying log information. This component can be imported from npm repository. - ObjectLoggerDemo: An example of business system integration ObjectLoggerClient. # 2 Quick Start ## 2.1 Create Data Tables Use `/server/database/init_data_table.sql` to init two data tables. ## 2.2 Start Server Download the new target jar file from `/server/target/ObjectLoggerServer-*.jar`. Start the jar with the following statement: ``` java -jar ObjectLoggerServer-*.jar --spring.datasource.driver-class-name={db_driver} --spring.datasource.url=jdbc:{db}://{db_address}/{db_name} --spring.datasource.username={db_username} --spring.datasource.password={db_password} ``` The above configuration items are described below: - `db_driver`:Database driver. `com.mysql.jdbc.Driver` for MySQL database; `com.microsoft.sqlserver.jdbc.SQLServerDriver` for SqlServer database. - `db`:DataBase type. `mysql` for MySQL database ;`sqlserver` for SqlServer database. - `db_address`:Database address. If the database is native, `127.0.0.1`. - `db_name`:Database name. - `db_username`:User name used to log in to the database. - `db_password`:Password used to log in to the database. After starting the jar package, you can see: <div align=center> <img width="80%" src="./pic/server_start.png"/> </div> The default welcome page is: ``` http://127.0.0.1:12301/ObjectLoggerServer/ ``` Visit the above address to see the following welcome interface: <div align=center> <img width="80%" src="./pic/100.jpg"/> </div> The ObjectLoggerServer system has been built. # 3 Access Service System This section explains how to configure the business system to analyze the object changes in the business system through ObjectLoggerClient and then record them in ObjectLoggerServer. The use of this part can refer to the ObjectLoggerDemo project, which gives a detailed example of business system integration ObjectLoggerClient. ObjectLoggerDemo's product package can be obtained from `/demo/target/ObjectLoggerDemo-*. jar`, and the project can be started directly without any other configuration by running `java -jar ObjectLoggerDemo-*. jar`. <div align=center> <img width="90%" src="./pic/demo_start.png"/> </div> ## 3.1 Add Dependency Add dependency package in POM file๏ผš ``` <dependency> <groupId>com.github.yeecode.objectlogger</groupId> <artifactId>ObjectLoggerClient</artifactId> <version>{last_version}</version> </dependency> ``` ## 3.2 Scan Beans in ObjectLoggerClient ### 3.2.1 SpringBoot Add `@ComponentScan` and add `com.github.yeecode.objectlogger` in `basePackages`๏ผš ``` @SpringBootApplication @ComponentScan(basePackages={"{your_beans_root}","com.github.yeecode.objectlogger"}) public class MyBootAppApplication { public static void main(String[] args) { // Eliminate other code } } ``` ### 3.2.2 Spring Add the following code to `applicationContext.xml` file: ``` <context:component-scan base-package="com.github.yeecode.objectlogger"> </context:component-scan> ``` ## 3.3 Configuration Add the following code to `application.properties`: ``` yeecode.objectLogger.serverAddress=http://{ObjectLoggerServer_address} yeecode.objectLogger.businessAppName={your_app_name} yeecode.objectLogger.autoLogAttributes=true ``` - `ObjectLoggerServer_address`: The deployment address of the ObjectLoggerServer in the previous step, such as: `127.0.0.1:12301` - `your_app_name`:The application name of the current business system. In order to differentiate log sources and support multiple business systems at the same time - `yeecode.objectLogger.autoLogAttributes`:Whether to automatically record all attributes of an object At this point, the configuration of the business system is completed. # 4 Query Logs The logs recorded in the system can be queried by `http://127.0.0.1:12301/ObjectLoggerServer/log/query`, and the logs can be filtered by passing in parameters. <div align=center> <img width="90%" src="./pic/api.gif"/> </div> # 5 Show Logs [react-object-logger](https://github.com/promise-coding/react-object-logger) is the react plugin for ObjectLogger project to show logs in web. Demo: [react-object-logger demo](https://promise-coding.github.io/react-object-logger/) <div align=center> <img width="90%" src="./pic/react_en.png"/> </div> More information can be obtained via [react-object-logger](https://github.com/promise-coding/react-object-logger). Plugins for other Front-end technology stacks are also under development. # 6 Insert Logs The business system introduces `LogClient` in any class that requires logging: ``` @Autowired private LogClient logClient; ``` ## 6.1 Simple Use Just put the zero, one or more attributes of the object into `List<BaseAttributeModel>` and call `logAttributes` method. For example, a business application calls: ``` logClient.logAttributes( "CleanRoomTask", 5, "Tom", "add", "Add New Task", "Create a cleanRoomTask", "taskName is :Demo Task", null); ``` Query form ObjectLoggerServer๏ผš ``` http://127.0.0.1:12301/ObjectLoggerServer/log/query?appName=ObjectLoggerDemo&objectName=CleanRoomTask&objectId=5 ``` Results๏ผš ``` { "respMsg": "SUCCESS", "respData": [ { "id": 1, "appName": "ObjectLoggerDemo", "objectName": "CleanRoomTask", "objectId": 5, "operator": "Jone", "operationName": "start", "operationAlias": "Start a Task", "extraWords": "Begin to clean room...", "comment": "Come on and start cleaning up.", "operationTime": "2019-07-04T06:53:40.000+0000", "attributeModelList": [ { "attributeType": "NORMAL", "attributeName": "status", "attributeAlias": "Status", "oldValue": "TODO", "newValue": "DOING", "diffValue": null, "id": 1, "operationId": 1 } ] } ], "respCode": "1000" } ``` ## 6.2 Automatic Recording of Object Attributes This function can automatically complete the comparison between old and new objects, and insert multiple attribute changes into the log system together. When used, ensure that the old and new objects belong to the same class. For example: ``` CleanRoomTask task = new CleanRoomTask(); task.setId(5); task.setTaskName("Demo Task"); task.setStatus("TODO"); task.setDescription("Do something..."); CleanRoomTask oldTask = logClient.deepCopy(task); task.setId(5); task.setTaskName("Demo Task"); task.setStatus("DOING"); task.setDescription("The main job is to clean the floor."); task.setAddress("Sunny Street"); task.setRoomNumber(702); logClient.logObject( cleanRoomTask.getId().toString(), "Tom", "update", "Update a Task", null, null, oldTask, task); ``` Query form ObjectLoggerServer๏ผš ``` http://127.0.0.1:12301/ObjectLoggerServer/log/query?appName=ObjectLoggerDemo&objectName=CleanRoomTask&objectId=5 ``` Results๏ผš ``` { "respMsg": "SUCCESS", "respData": [ { "id": 4, "appName": "ObjectLoggerDemo", "objectName": "CleanRoomTask", "objectId": 5, "operator": "Tom", "operationName": "update", "operationAlias": "Update a Task", "extraWords": null, "comment": null, "operationTime": "2019-07-04T07:22:59.000+0000", "attributeModelList": [ { "attributeType": "NORMAL", "attributeName": "roomNumber", "attributeAlias": "roomNumber", "oldValue": "", "newValue": "702", "diffValue": null, "id": 5, "operationId": 4 }, { "attributeType": "NORMAL", "attributeName": "address", "attributeAlias": "address", "oldValue": "", "newValue": "Sunny Street", "diffValue": null, "id": 6, "operationId": 4 }, { "attributeType": "NORMAL", "attributeName": "status", "attributeAlias": "Status", "oldValue": "TODO", "newValue": "DOING", "diffValue": null, "id": 7, "operationId": 4 }, { "attributeType": "TEXT", "attributeName": "description", "attributeAlias": "Description", "oldValue": "Do something...", "newValue": "The main job is to clean the floor.", "diffValue": "Line 1<br/>&nbsp;&nbsp;&nbsp; -๏ผš <del> Do something... </del> <br/>&nbsp;&nbsp; +๏ผš <u> The main job is to clean the floor. </u> <br/>", "id": 8, "operationId": 4 } ] } ], "respCode": "1000" } ``` # 7 Object Attribute Filtering Some object attributes do not need to be logged, such as `updateTime`, `hashCode`, etc. ObjectLoggerClient supports filtering attributes of objects, tracking only attributes that we are interested in. And for each attribute, we can change the way it is recorded in the ObjectLoggerClient system, such as changing the name. To enable this function, first change the `yeecode.objectLogger.autoLogAttributes` in the configuration to `false`. ``` yeecode.objectLogger.autoLogAttributes=true ``` Then, the `@LogTag` annotation should be added to the attributes that need to be logged for change. Attributes without the annotation will be automatically skipped when logging. For example, if the annotation configuration is as follows, `id` field changes will be ignored. ``` private Integer id; @LogTag private String taskName; @LogTag(alias = "UserId", extendedType = "userIdType") private int userId; @LogTag(alias = "Status") private String status; @LogTag(alias = "Description", builtinType = BuiltinTypeHandler.TEXT) private String description; ``` - alias:The attribute alias to display. - builtinType๏ผšBuilt-in type of ObjectLoggerClient, which form the BuiltinTypeHandler enum. The default value is `BuiltinTypeHandler.NORMAL`. - BuiltinTypeHandler.NORMAL๏ผšRecord the new and old values. - BuiltinTypeHandler.RICHTEXT: Line-by-line comparison of rich text differences. - extendedType๏ผšExtend attribute types. Users can extend the processing of certain fields. # 8 Extended Processing Attribute In many cases, users want to be able to decide how to handle certain object attributes independently. For example, users may want to convert the `userId` attribute of the `Task` object into a name and store it in the log system, thus completely decoupling the log system from `userId`. ObjectLoggerClient fully supports this scenario, allowing users to decide how to log certain attributes independently. To achieve this function, first assign a string value to the `extendedType` attribute of `@LogTag` that needs to be extended. For example: ``` @LogTag(alias = "UserId", extendedType = "userIdType") private int userId; ``` And new a Bean implements BaseExtendedTypeHandler in business system: ``` @Service public class ExtendedTypeHandler implements BaseExtendedTypeHandler { @Override public BaseAttributeModel handleAttributeChange(String extendedType, String attributeName, String attributeAlias, Object oldValue, Object newValue) { // TODO } } ``` When ObjectLoggerClient processes this property, it passes information about the property into the `handleAttributeChange`method of the extended bean. The four parameters introduced are explained as follows: - `extendedType`๏ผšExtended Type.In this example, `userIdType`. - `attributeName`๏ผšAttribute Name. In this example,`userId`. - `attributeAlias`๏ผšAttribute alias, from `@LogTag`. In this example,`UserId`. - `oldValue`๏ผšOld value of the attribute. - `newValue`๏ผšNew value of the attribute. For example, we can deal with the `userIdType` attribute in the following way: ``` @Service public class ExtendedTypeHandler implements BaseExtendedTypeHandler { @Override public BaseAttributeModel handleAttributeChange(String extendedType, String attributeName, String attributeAlias, Object oldValue, Object newValue) { BaseAttributeModel baseAttributeModel = new BaseAttributeModel(); if (extendedType.equals("userIdType")) { // For example only, you can call external application here to convert user number to user name. baseAttributeModel.setOldValue("USER_" + oldValue); baseAttributeModel.setNewValue("USER_" + newValue); baseAttributeModel.setDiffValue(oldValue + "->" + newValue); } return baseAttributeModel; } } ``` ## 9 Roadmap - 3.1.1๏ผšAdd object deep copy function to facilitate users to save the objects before change - 3.0.1๏ผšOptimizing System Naming, represent the difference value with json - 3.0.0๏ผšOptimizing System Naming - 2.3.0๏ผšAdded automatic recording for inherited attributes - 2.2.0๏ผšAdded automatic recording function of global object attribute change - 2.0.1๏ผšMade the system support multi-threading - 2.0.0๏ผšOptimized system structure - 1.0.0๏ผšInitialize the system
116
Enhancing Java Stream API
# StreamEx 0.8.1 Enhancing Java Stream API. [![Maven Central](https://img.shields.io/maven-central/v/one.util/streamex.svg)](https://maven-badges.herokuapp.com/maven-central/one.util/streamex/) [![Javadocs](https://www.javadoc.io/badge/one.util/streamex.svg)](https://www.javadoc.io/doc/one.util/streamex) [![Build Status](https://github.com/amaembo/streamex/actions/workflows/test.yml/badge.svg)](https://travis-ci.org/amaembo/streamex) [![Coverage Status](https://coveralls.io/repos/amaembo/streamex/badge.svg?branch=master&service=github)](https://coveralls.io/github/amaembo/streamex?branch=master) This library defines four classes: `StreamEx`, `IntStreamEx`, `LongStreamEx`, `DoubleStreamEx` which are fully compatible with Java 8 stream classes and provide many additional useful methods. Also `EntryStream` class is provided which represents the stream of map entries and provides additional functionality for this case. Finally, there are some new useful collectors defined in `MoreCollectors` class as well as primitive collectors concept. Full API documentation is available [here](http://amaembo.github.io/streamex/javadoc/). Take a look at the [Cheatsheet](wiki/CHEATSHEET.md) for brief introduction to the StreamEx! Before updating StreamEx check the [migration notes](wiki/MIGRATION.md) and full list of [changes](wiki/CHANGES.md). StreamEx library main points are following: * Shorter and convenient ways to do the common tasks. * Better interoperability with older code. * 100% compatibility with original JDK streams. * Friendliness for parallel processing: any new feature takes the advantage on parallel streams as much as possible. * Performance and minimal overhead. If StreamEx allows to solve the task using less code compared to standard Stream, it should not be significantly slower than the standard way (and sometimes it's even faster). ### Examples Collector shortcut methods (toList, toSet, groupingBy, joining, etc.) ```java List<String> userNames = StreamEx.of(users).map(User::getName).toList(); Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole); StreamEx.of(1,2,3).joining("; "); // "1; 2; 3" ``` Selecting stream elements of specific type ```java public List<Element> elementsOf(NodeList nodeList) { return IntStreamEx.range(nodeList.getLength()) .mapToObj(nodeList::item).select(Element.class).toList(); } ``` Adding elements to stream ```java public List<String> getDropDownOptions() { return StreamEx.of(users).map(User::getName).prepend("(none)").toList(); } public int[] addValue(int[] arr, int value) { return IntStreamEx.of(arr).append(value).toArray(); } ``` Removing unwanted elements and using the stream as Iterable: ```java public void copyNonEmptyLines(Reader reader, Writer writer) throws IOException { for(String line : StreamEx.ofLines(reader).remove(String::isEmpty)) { writer.write(line); writer.write(System.lineSeparator()); } } ``` Selecting map keys by value predicate: ```java Map<String, Role> nameToRole; public Set<String> getEnabledRoleNames() { return StreamEx.ofKeys(nameToRole, Role::isEnabled).toSet(); } ``` Operating on key-value pairs: ```java public Map<String, List<String>> invert(Map<String, List<String>> map) { return EntryStream.of(map).flatMapValues(List::stream).invert().grouping(); } public Map<String, String> stringMap(Map<Object, Object> map) { return EntryStream.of(map).mapKeys(String::valueOf) .mapValues(String::valueOf).toMap(); } Map<String, Group> nameToGroup; public Map<String, List<User>> getGroupMembers(Collection<String> groupNames) { return StreamEx.of(groupNames).mapToEntry(nameToGroup::get) .nonNullValues().mapValues(Group::getMembers).toMap(); } ``` Pairwise differences: ```java DoubleStreamEx.of(input).pairMap((a, b) -> b-a).toArray(); ``` Support of byte/char/short/float types: ```java short[] multiply(short[] src, short multiplier) { return IntStreamEx.of(src).map(x -> x*multiplier).toShortArray(); } ``` Define custom lazy intermediate operation recursively: ```java static <T> StreamEx<T> scanLeft(StreamEx<T> input, BinaryOperator<T> operator) { return input.headTail((head, tail) -> scanLeft(tail.mapFirst(cur -> operator.apply(head, cur)), operator) .prepend(head)); } ``` And more! ### License This project is licensed under [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0) ### Installation Releases are available in [Maven Central](https://repo1.maven.org/maven2/one/util/streamex/) Before updating StreamEx check the [migration notes](wiki/MIGRATION.md) and full list of [changes](wiki/CHANGES.md). #### Maven Add this snippet to the pom.xml `dependencies` section: ```xml <dependency> <groupId>one.util</groupId> <artifactId>streamex</artifactId> <version>0.8.1</version> </dependency> ``` #### Gradle Add this snippet to the build.gradle `dependencies` section: ```groovy implementation 'one.util:streamex:0.8.1' ``` Pull requests are welcome.
117
Everything you need to know to get the job.
# Interviews > Your personal guide to Software Engineering technical interviews. Video > solutions to the following interview problems with detailed explanations can be found [here](https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g). <a href="https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g" style="display:block;"><img src="/images/youtube.png?raw=true"></a> > > Maintainer - [Kevin Naughton Jr.](https://github.com/kdn251) ## Translations - [็ฎ€ไฝ“ไธญๆ–‡](./README-zh-cn.md) ## Table of Contents - [YouTube](#youtube) - [The Daily Byte](#the-daily-byte) - [Instagram](#instagram) - [Articles](#articles) - [Online Judges](#online-judges) - [Live Coding Practice](#live-coding-practice) - [Data Structures](#data-structures) - [Algorithms](#algorithms) - [Greedy Algorithms](#greedy-algorithms) - [Bitmasks](#bitmasks) - [Runtime Analysis](#runtime-analysis) - [Video Lectures](#video-lectures) - [Interview Books](#interview-books) - [Computer Science News](#computer-science-news) - [Directory Tree](#directory-tree) ## YouTube * [Kevin Naughton Jr.](https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g) ## The Daily Byte * [FAANG Interview Prep](https://bit.ly/2BaaSaK) ## Instagram * [Kevin Naughton Jr.](https://bit.ly/2SM8SLZ) ## Articles * [Starting Work](https://medium.com/@Naughton/starting-work-b06e10f6007e) ## Online Judges * [LeetCode](https://leetcode.com/) * [Virtual Judge](https://vjudge.net/) * [CareerCup](https://www.careercup.com/) * [HackerRank](https://www.hackerrank.com/) * [CodeFights](https://codefights.com/) * [Kattis](https://open.kattis.com/) * [HackerEarth](https://www.hackerearth.com) * [Codility](https://codility.com/programmers/lessons/1-iterations/) * [Code Forces](http://codeforces.com/) * [Code Chef](https://www.codechef.com/) * [Sphere Online Judge - SPOJ](http://www.spoj.com/) * [InterviewBit](https://www.interviewbit.com/) ## Live Coding Practice * [Pramp](https://www.pramp.com/ref/gt4) * [Gainlo](http://www.gainlo.co/#!/) * [Refdash](https://refdash.com/) * [Interviewing.io](https://www.interviewing.io/) ## Data Structures ### Linked List * A *Linked List* is a linear collection of data elements, called nodes, each pointing to the next node by means of a pointer. It is a data structure consisting of a group of nodes which together represent a sequence. * **Singly-linked list**: linked list in which each node points to the next node and the last node points to null * **Doubly-linked list**: linked list in which each node has two pointers, p and n, such that p points to the previous node and n points to the next node; the last node's n pointer points to null * **Circular-linked list**: linked list in which each node points to the next node and the last node points back to the first node * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Stack * A *Stack* is a collection of elements, with two principle operations: *push*, which adds to the collection, and *pop*, which removes the most recently added element * **Last in, first out data structure (LIFO)**: the most recently added object is the first to be removed * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Queue * A *Queue* is a collection of elements, supporting two principle operations: *enqueue*, which inserts an element into the queue, and *dequeue*, which removes an element from the queue * **First in, first out data structure (FIFO)**: the oldest added object is the first to be removed * Time Complexity: * Access: `O(n)` * Search: `O(n)` * Insert: `O(1)` * Remove: `O(1)` ### Tree * A *Tree* is an undirected, connected, acyclic graph ### Binary Tree * A *Binary Tree* is a tree data structure in which each node has at most two children, which are referred to as the *left child* and *right child* * **Full Tree**: a tree in which every node has either 0 or 2 children * **Perfect Binary Tree**: a binary tree in which all interior nodes have two children and all leave have the same depth * **Complete Tree**: a binary tree in which every level *except possibly the last* is full and all nodes in the last level are as far left as possible ### Binary Search Tree * A binary search tree, sometimes called BST, is a type of binary tree which maintains the property that the value in each node must be greater than or equal to any value stored in the left sub-tree, and less than or equal to any value stored in the right sub-tree * Time Complexity: * Access: `O(log(n))` * Search: `O(log(n))` * Insert: `O(log(n))` * Remove: `O(log(n))` <img src="/images/BST.png?raw=true" alt="Binary Search Tree" width="400" height="500"> ### Trie * A trie, sometimes called a radix or prefix tree, is a kind of search tree that is used to store a dynamic set or associative array where the keys are usually Strings. No node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the String associated with that node, and the root is associated with the empty String. ![Alt text](/images/trie.png?raw=true "Trie") ### Fenwick Tree * A Fenwick tree, sometimes called a binary indexed tree, is a tree in concept, but in practice is implemented as an implicit data structure using an array. Given an index in the array representing a vertex, the index of a vertex's parent or child is calculated through bitwise operations on the binary representation of its index. Each element of the array contains the pre-calculated sum of a range of values, and by combining that sum with additional ranges encountered during an upward traversal to the root, the prefix sum is calculated * Time Complexity: * Range Sum: `O(log(n))` * Update: `O(log(n))` ![Alt text](/images/fenwickTree.png?raw=true "Fenwick Tree") ### Segment Tree * A Segment tree, is a tree data structure for storing intervals, or segments. It allows querying which of the stored segments contain a given point * Time Complexity: * Range Query: `O(log(n))` * Update: `O(log(n))` ![Alt text](/images/segmentTree.png?raw=true "Segment Tree") ### Heap * A *Heap* is a specialized tree based structure data structure that satisfies the *heap* property: if A is a parent node of B, then the key (the value) of node A is ordered with respect to the key of node B with the same ordering applying across the entire heap. A heap can be classified further as either a "max heap" or a "min heap". In a max heap, the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node. In a min heap, the keys of parent nodes are less than or equal to those of the children and the lowest key is in the root node * Time Complexity: * Access Max / Min: `O(1)` * Insert: `O(log(n))` * Remove Max / Min: `O(log(n))` <img src="/images/heap.png?raw=true" alt="Max Heap" width="400" height="500"> ### Hashing * *Hashing* is used to map data of an arbitrary size to data of a fixed size. The values returned by a hash function are called hash values, hash codes, or simply hashes. If two keys map to the same value, a collision occurs * **Hash Map**: a *hash map* is a structure that can map keys to values. A hash map uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. * Collision Resolution * **Separate Chaining**: in *separate chaining*, each bucket is independent, and contains a list of entries for each index. The time for hash map operations is the time to find the bucket (constant time), plus the time to iterate through the list * **Open Addressing**: in *open addressing*, when a new entry is inserted, the buckets are examined, starting with the hashed-to-slot and proceeding in some sequence, until an unoccupied slot is found. The name open addressing refers to the fact that the location of an item is not always determined by its hash value ![Alt text](/images/hash.png?raw=true "Hashing") ### Graph * A *Graph* is an ordered pair of G = (V, E) comprising a set V of vertices or nodes together with a set E of edges or arcs, which are 2-element subsets of V (i.e. an edge is associated with two vertices, and that association takes the form of the unordered pair comprising those two vertices) * **Undirected Graph**: a graph in which the adjacency relation is symmetric. So if there exists an edge from node u to node v (u -> v), then it is also the case that there exists an edge from node v to node u (v -> u) * **Directed Graph**: a graph in which the adjacency relation is not symmetric. So if there exists an edge from node u to node v (u -> v), this does *not* imply that there exists an edge from node v to node u (v -> u) <img src="/images/graph.png?raw=true" alt="Graph" width="400" height="500"> ## Algorithms ### Sorting #### Quicksort * Stable: `No` * Time Complexity: * Best Case: `O(nlog(n))` * Worst Case: `O(n^2)` * Average Case: `O(nlog(n))` ![Alt text](/images/quicksort.gif?raw=true "Quicksort") #### Mergesort * *Mergesort* is also a divide and conquer algorithm. It continuously divides an array into two halves, recurses on both the left subarray and right subarray and then merges the two sorted halves * Stable: `Yes` * Time Complexity: * Best Case: `O(nlog(n))` * Worst Case: `O(nlog(n))` * Average Case: `O(nlog(n))` ![Alt text](/images/mergesort.gif?raw=true "Mergesort") #### Bucket Sort * *Bucket Sort* is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm * Time Complexity: * Best Case: `ฮฉ(n + k)` * Worst Case: `O(n^2)` * Average Case:`ฮ˜(n + k)` ![Alt text](/images/bucketsort.png?raw=true "Bucket Sort") #### Radix Sort * *Radix Sort* is a sorting algorithm that like bucket sort, distributes elements of an array into a number of buckets. However, radix sort differs from bucket sort by 're-bucketing' the array after the initial pass as opposed to sorting each bucket and merging * Time Complexity: * Best Case: `ฮฉ(nk)` * Worst Case: `O(nk)` * Average Case: `ฮ˜(nk)` ### Graph Algorithms #### Depth First Search * *Depth First Search* is a graph traversal algorithm which explores as far as possible along each branch before backtracking * Time Complexity: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### Breadth First Search * *Breadth First Search* is a graph traversal algorithm which explores the neighbor nodes first, before moving to the next level neighbors * Time Complexity: `O(|V| + |E|)` ![Alt text](/images/dfsbfs.gif?raw=true "DFS / BFS Traversal") #### Topological Sort * *Topological Sort* is the linear ordering of a directed graph's nodes such that for every edge from node u to node v, u comes before v in the ordering * Time Complexity: `O(|V| + |E|)` #### Dijkstra's Algorithm * *Dijkstra's Algorithm* is an algorithm for finding the shortest path between nodes in a graph * Time Complexity: `O(|V|^2)` ![Alt text](/images/dijkstra.gif?raw=true "Dijkstra's") #### Bellman-Ford Algorithm * *Bellman-Ford Algorithm* is an algorithm that computes the shortest paths from a single source node to all other nodes in a weighted graph * Although it is slower than Dijkstra's, it is more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers * Time Complexity: * Best Case: `O(|E|)` * Worst Case: `O(|V||E|)` ![Alt text](/images/bellman-ford.gif?raw=true "Bellman-Ford") #### Floyd-Warshall Algorithm * *Floyd-Warshall Algorithm* is an algorithm for finding the shortest paths in a weighted graph with positive or negative edge weights, but no negative cycles * A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between *all* pairs of nodes * Time Complexity: * Best Case: `O(|V|^3)` * Worst Case: `O(|V|^3)` * Average Case: `O(|V|^3)` #### Prim's Algorithm * *Prim's Algorithm* is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. In other words, Prim's find a subset of edges that forms a tree that includes every node in the graph * Time Complexity: `O(|V|^2)` ![Alt text](/images/prim.gif?raw=true "Prim's Algorithm") #### Kruskal's Algorithm * *Kruskal's Algorithm* is also a greedy algorithm that finds a minimum spanning tree in a graph. However, in Kruskal's, the graph does not have to be connected * Time Complexity: `O(|E|log|V|)` ![Alt text](/images/kruskal.gif?raw=true "Kruskal's Algorithm") ## Greedy Algorithms * *Greedy Algorithms* are algorithms that make locally optimal choices at each step in the hope of eventually reaching the globally optimal solution * Problems must exhibit two properties in order to implement a Greedy solution: * Optimal Substructure * An optimal solution to the problem contains optimal solutions to the given problem's subproblems * The Greedy Property * An optimal solution is reached by "greedily" choosing the locally optimal choice without ever reconsidering previous choices * Example - Coin Change * Given a target amount V cents and a list of denominations of n coins, i.e. we have coinValue[i] (in cents) for coin types i from [0...n - 1], what is the minimum number of coins that we must use to represent amount V? Assume that we have an unlimited supply of coins of any type * Coins - Penny (1 cent), Nickel (5 cents), Dime (10 cents), Quarter (25 cents) * Assume V = 41. We can use the Greedy algorithm of continuously selecting the largest coin denomination less than or equal to V, subtract that coin's value from V, and repeat. * V = 41 | 0 coins used * V = 16 | 1 coin used (41 - 25 = 16) * V = 6 | 2 coins used (16 - 10 = 6) * V = 1 | 3 coins used (6 - 5 = 1) * V = 0 | 4 coins used (1 - 1 = 0) * Using this algorithm, we arrive at a total of 4 coins which is optimal ## Bitmasks * Bitmasking is a technique used to perform operations at the bit level. Leveraging bitmasks often leads to faster runtime complexity and helps limit memory usage * Test kth bit: `s & (1 << k);` * Set kth bit: `s |= (1 << k);` * Turn off kth bit: `s &= ~(1 << k);` * Toggle kth bit: `s ^= (1 << k);` * Multiple by 2<sup>n</sup>: `s << n;` * Divide by 2<sup>n</sup>: `s >> n;` * Intersection: `s & t;` * Union: `s | t;` * Set Subtraction: `s & ~t;` * Extract lowest set bit: `s & (-s);` * Extract lowest unset bit: `~s & (s + 1);` * Swap Values: ``` x ^= y; y ^= x; x ^= y; ``` ## Runtime Analysis #### Big O Notation * *Big O Notation* is used to describe the upper bound of a particular algorithm. Big O is used to describe worst case scenarios ![Alt text](/images/bigO.png?raw=true "Theta Notation") #### Little O Notation * *Little O Notation* is also used to describe an upper bound of a particular algorithm; however, Little O provides a bound that is not asymptotically tight #### Big ฮฉ Omega Notation * *Big Omega Notation* is used to provide an asymptotic lower bound on a particular algorithm ![Alt text](/images/bigOmega.png?raw=true "Theta Notation") #### Little ฯ‰ Omega Notation * *Little Omega Notation* is used to provide a lower bound on a particular algorithm that is not asymptotically tight #### Theta ฮ˜ Notation * *Theta Notation* is used to provide a bound on a particular algorithm such that it can be "sandwiched" between two constants (one for an upper limit and one for a lower limit) for sufficiently large values ![Alt text](/images/theta.png?raw=true "Theta Notation") ## Video Lectures * Data Structures * [UC Berkeley Data Structures](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22) * [MIT Advanced Data Structures](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf&index=1) * Algorithms * [MIT Introduction to Algorithms](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb&index=1) * [MIT Advanced Algorithms](https://www.youtube.com/playlist?list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c) * [UC Berkeley Algorithms](https://archive.org/details/ucberkeley-webcast?&and[]=subject%3A%22Computer%20Science%22&and[]=subject%3A%22CS%22) ## Interview Books * [Competitive Programming 3 - Steven Halim & Felix Halim](https://www.amazon.com/Competitive-Programming-3rd-Steven-Halim/dp/B00FG8MNN8) * [Cracking The Coding Interview - Gayle Laakmann McDowell](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850/ref=sr_1_1?s=books&ie=UTF8) * [Cracking The PM Interview - Gayle Laakmann McDowell & Jackie Bavaro](https://www.amazon.com/Cracking-PM-Interview-Product-Technology-ebook/dp/B00ISYMUR6/ref=sr_1_1?s=books&ie=UTF8) * [Introduction to Algorithms - Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest & Clifford Stein](https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844/ref=sr_1_1?ie=UTF8&qid=1490295989&sr=8-1&keywords=Introduction+to+Algorithms) ## Computer Science News * [Hacker News](https://news.ycombinator.com/) * [Lobsters](https://lobste.rs/) ## Directory Tree ``` . โ”œโ”€โ”€ Array โ”‚ย ย  โ”œโ”€โ”€ bestTimeToBuyAndSellStock.java โ”‚ย ย  โ”œโ”€โ”€ findTheCelebrity.java โ”‚ย ย  โ”œโ”€โ”€ gameOfLife.java โ”‚ย ย  โ”œโ”€โ”€ increasingTripletSubsequence.java โ”‚ย ย  โ”œโ”€โ”€ insertInterval.java โ”‚ย ย  โ”œโ”€โ”€ longestConsecutiveSequence.java โ”‚ย ย  โ”œโ”€โ”€ maximumProductSubarray.java โ”‚ย ย  โ”œโ”€โ”€ maximumSubarray.java โ”‚ย ย  โ”œโ”€โ”€ mergeIntervals.java โ”‚ย ย  โ”œโ”€โ”€ missingRanges.java โ”‚ย ย  โ”œโ”€โ”€ productOfArrayExceptSelf.java โ”‚ย ย  โ”œโ”€โ”€ rotateImage.java โ”‚ย ย  โ”œโ”€โ”€ searchInRotatedSortedArray.java โ”‚ย ย  โ”œโ”€โ”€ spiralMatrixII.java โ”‚ย ย  โ”œโ”€โ”€ subsetsII.java โ”‚ย ย  โ”œโ”€โ”€ subsets.java โ”‚ย ย  โ”œโ”€โ”€ summaryRanges.java โ”‚ย ย  โ”œโ”€โ”€ wiggleSort.java โ”‚ย ย  โ””โ”€โ”€ wordSearch.java โ”œโ”€โ”€ Backtracking โ”‚ย ย  โ”œโ”€โ”€ androidUnlockPatterns.java โ”‚ย ย  โ”œโ”€โ”€ generalizedAbbreviation.java โ”‚ย ย  โ””โ”€โ”€ letterCombinationsOfAPhoneNumber.java โ”œโ”€โ”€ BinarySearch โ”‚ย ย  โ”œโ”€โ”€ closestBinarySearchTreeValue.java โ”‚ย ย  โ”œโ”€โ”€ firstBadVersion.java โ”‚ย ย  โ”œโ”€โ”€ guessNumberHigherOrLower.java โ”‚ย ย  โ”œโ”€โ”€ pow(x,n).java โ”‚ย ย  โ””โ”€โ”€ sqrt(x).java โ”œโ”€โ”€ BitManipulation โ”‚ย ย  โ”œโ”€โ”€ binaryWatch.java โ”‚ย ย  โ”œโ”€โ”€ countingBits.java โ”‚ย ย  โ”œโ”€โ”€ hammingDistance.java โ”‚ย ย  โ”œโ”€โ”€ maximumProductOfWordLengths.java โ”‚ย ย  โ”œโ”€โ”€ numberOf1Bits.java โ”‚ย ย  โ”œโ”€โ”€ sumOfTwoIntegers.java โ”‚ย ย  โ””โ”€โ”€ utf-8Validation.java โ”œโ”€โ”€ BreadthFirstSearch โ”‚ย ย  โ”œโ”€โ”€ binaryTreeLevelOrderTraversal.java โ”‚ย ย  โ”œโ”€โ”€ cloneGraph.java โ”‚ย ย  โ”œโ”€โ”€ pacificAtlanticWaterFlow.java โ”‚ย ย  โ”œโ”€โ”€ removeInvalidParentheses.java โ”‚ย ย  โ”œโ”€โ”€ shortestDistanceFromAllBuildings.java โ”‚ย ย  โ”œโ”€โ”€ symmetricTree.java โ”‚ย ย  โ””โ”€โ”€ wallsAndGates.java โ”œโ”€โ”€ DepthFirstSearch โ”‚ย ย  โ”œโ”€โ”€ balancedBinaryTree.java โ”‚ย ย  โ”œโ”€โ”€ battleshipsInABoard.java โ”‚ย ย  โ”œโ”€โ”€ convertSortedArrayToBinarySearchTree.java โ”‚ย ย  โ”œโ”€โ”€ maximumDepthOfABinaryTree.java โ”‚ย ย  โ”œโ”€โ”€ numberOfIslands.java โ”‚ย ย  โ”œโ”€โ”€ populatingNextRightPointersInEachNode.java โ”‚ย ย  โ””โ”€โ”€ sameTree.java โ”œโ”€โ”€ Design โ”‚ย ย  โ””โ”€โ”€ zigzagIterator.java โ”œโ”€โ”€ DivideAndConquer โ”‚ย ย  โ”œโ”€โ”€ expressionAddOperators.java โ”‚ย ย  โ””โ”€โ”€ kthLargestElementInAnArray.java โ”œโ”€โ”€ DynamicProgramming โ”‚ย ย  โ”œโ”€โ”€ bombEnemy.java โ”‚ย ย  โ”œโ”€โ”€ climbingStairs.java โ”‚ย ย  โ”œโ”€โ”€ combinationSumIV.java โ”‚ย ย  โ”œโ”€โ”€ countingBits.java โ”‚ย ย  โ”œโ”€โ”€ editDistance.java โ”‚ย ย  โ”œโ”€โ”€ houseRobber.java โ”‚ย ย  โ”œโ”€โ”€ paintFence.java โ”‚ย ย  โ”œโ”€โ”€ paintHouseII.java โ”‚ย ย  โ”œโ”€โ”€ regularExpressionMatching.java โ”‚ย ย  โ”œโ”€โ”€ sentenceScreenFitting.java โ”‚ย ย  โ”œโ”€โ”€ uniqueBinarySearchTrees.java โ”‚ย ย  โ””โ”€โ”€ wordBreak.java โ”œโ”€โ”€ HashTable โ”‚ย ย  โ”œโ”€โ”€ binaryTreeVerticalOrderTraversal.java โ”‚ย ย  โ”œโ”€โ”€ findTheDifference.java โ”‚ย ย  โ”œโ”€โ”€ groupAnagrams.java โ”‚ย ย  โ”œโ”€โ”€ groupShiftedStrings.java โ”‚ย ย  โ”œโ”€โ”€ islandPerimeter.java โ”‚ย ย  โ”œโ”€โ”€ loggerRateLimiter.java โ”‚ย ย  โ”œโ”€โ”€ maximumSizeSubarraySumEqualsK.java โ”‚ย ย  โ”œโ”€โ”€ minimumWindowSubstring.java โ”‚ย ย  โ”œโ”€โ”€ sparseMatrixMultiplication.java โ”‚ย ย  โ”œโ”€โ”€ strobogrammaticNumber.java โ”‚ย ย  โ”œโ”€โ”€ twoSum.java โ”‚ย ย  โ””โ”€โ”€ uniqueWordAbbreviation.java โ”œโ”€โ”€ LinkedList โ”‚ย ย  โ”œโ”€โ”€ addTwoNumbers.java โ”‚ย ย  โ”œโ”€โ”€ deleteNodeInALinkedList.java โ”‚ย ย  โ”œโ”€โ”€ mergeKSortedLists.java โ”‚ย ย  โ”œโ”€โ”€ palindromeLinkedList.java โ”‚ย ย  โ”œโ”€โ”€ plusOneLinkedList.java โ”‚ย ย  โ”œโ”€โ”€ README.md โ”‚ย ย  โ””โ”€โ”€ reverseLinkedList.java โ”œโ”€โ”€ Queue โ”‚ย ย  โ””โ”€โ”€ movingAverageFromDataStream.java โ”œโ”€โ”€ README.md โ”œโ”€โ”€ Sort โ”‚ย ย  โ”œโ”€โ”€ meetingRoomsII.java โ”‚ย ย  โ””โ”€โ”€ meetingRooms.java โ”œโ”€โ”€ Stack โ”‚ย ย  โ”œโ”€โ”€ binarySearchTreeIterator.java โ”‚ย ย  โ”œโ”€โ”€ decodeString.java โ”‚ย ย  โ”œโ”€โ”€ flattenNestedListIterator.java โ”‚ย ย  โ””โ”€โ”€ trappingRainWater.java โ”œโ”€โ”€ String โ”‚ย ย  โ”œโ”€โ”€ addBinary.java โ”‚ย ย  โ”œโ”€โ”€ countAndSay.java โ”‚ย ย  โ”œโ”€โ”€ decodeWays.java โ”‚ย ย  โ”œโ”€โ”€ editDistance.java โ”‚ย ย  โ”œโ”€โ”€ integerToEnglishWords.java โ”‚ย ย  โ”œโ”€โ”€ longestPalindrome.java โ”‚ย ย  โ”œโ”€โ”€ longestSubstringWithAtMostKDistinctCharacters.java โ”‚ย ย  โ”œโ”€โ”€ minimumWindowSubstring.java โ”‚ย ย  โ”œโ”€โ”€ multiplyString.java โ”‚ย ย  โ”œโ”€โ”€ oneEditDistance.java โ”‚ย ย  โ”œโ”€โ”€ palindromePermutation.java โ”‚ย ย  โ”œโ”€โ”€ README.md โ”‚ย ย  โ”œโ”€โ”€ reverseVowelsOfAString.java โ”‚ย ย  โ”œโ”€โ”€ romanToInteger.java โ”‚ย ย  โ”œโ”€โ”€ validPalindrome.java โ”‚ย ย  โ””โ”€โ”€ validParentheses.java โ”œโ”€โ”€ Tree โ”‚ย ย  โ”œโ”€โ”€ binaryTreeMaximumPathSum.java โ”‚ย ย  โ”œโ”€โ”€ binaryTreePaths.java โ”‚ย ย  โ”œโ”€โ”€ inorderSuccessorInBST.java โ”‚ย ย  โ”œโ”€โ”€ invertBinaryTree.java โ”‚ย ย  โ”œโ”€โ”€ lowestCommonAncestorOfABinaryTree.java โ”‚ย ย  โ”œโ”€โ”€ sumOfLeftLeaves.java โ”‚ย ย  โ””โ”€โ”€ validateBinarySearchTree.java โ”œโ”€โ”€ Trie โ”‚ย ย  โ”œโ”€โ”€ addAndSearchWordDataStructureDesign.java โ”‚ย ย  โ”œโ”€โ”€ implementTrie.java โ”‚ย ย  โ””โ”€โ”€ wordSquares.java โ””โ”€โ”€ TwoPointers โ”œโ”€โ”€ 3Sum.java โ”œโ”€โ”€ 3SumSmaller.java โ”œโ”€โ”€ mergeSortedArray.java โ”œโ”€โ”€ minimumSizeSubarraySum.java โ”œโ”€โ”€ moveZeros.java โ”œโ”€โ”€ removeDuplicatesFromSortedArray.java โ”œโ”€โ”€ reverseString.java โ””โ”€โ”€ sortColors.java 18 directories, 124 files ```
118
The Common Data Model (CDM) is a standard and extensible collection of schemas (entities, attributes, relationships) that represents business concepts and activities with well-defined semantics, to facilitate data interoperability. Examples of entities include: Account, Contact, Lead, Opportunity, Product, etc.
# Common Data Model Official Packages | [![NuGet](https://img.shields.io/nuget/v/Microsoft.CommonDataModel.ObjectModel.svg?style=flat-square&label=nuget&colorB=00b200)](https://www.nuget.org/profiles/CommonDataModel/) | [![Maven Central](https://img.shields.io/maven-central/v/com.microsoft.commondatamodel/objectmodel.svg?style=flat-square&label=maven-central&colorB=00b200)](https://search.maven.org/artifact/com.microsoft.commondatamodel/objectmodel) | [![PyPI](https://img.shields.io/pypi/v/commondatamodel-objectmodel.svg?style=flat-square&label=pypi&colorB=00b200)](https://pypi.org/project/commondatamodel-objectmodel/) | [![npm](https://img.shields.io/npm/v/cdm.objectmodel.svg?style=flat-square&label=npm&colorB=00b200)](https://www.npmjs.com/package/cdm.objectmodel) | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | # We welcome your feedback Do you use the Common Data Model SDK? If you do, please can you tell us which version(s) you use (C#/.NET, Java, Python, or TypeScript) by taking this [**short survey**](https://forms.office.com/r/hainr3a7rR). # Common Data Model (CDM) Schema The Common Data Model is a declarative specification, and definition of standard entities that represent commonly used concepts and activities across business and productivity applications, and is being extended to observational and analytical data as well. CDM provides well-defined, modular, and extensible business entities such as Account, Business Unit, Case, Contact, Lead, Opportunity, and Product, as well as interactions with vendors, workers, and customers, such as activities and service level agreements. Anyone can build on and extend CDM definitions to capture additional business-specific ideas. <pre> <img src="docs/blank.png"/> <a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/dynamicsCRM.manifest.cdm.json&simpleChrome=true"> <img src="docs/dyn-static.PNG"/> </a> <a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=standards.manifest.cdm.json&simpleChrome=true"> <img src="docs/all-entities-small.PNG"/></a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/insightsApplications.manifest.cdm.json&simpleChrome=true"> <img src="docs/insights-static.PNG"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/financeAndOperations.manifest.cdm.json&simpleChrome=true"> <img src="docs/f-and-o-static.PNG"/> </a> <a href="https://microsoft.github.io/CDM/SchemaViz.html?"> <img src="docs/advanced-small.PNG"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/automotiveAccelerator.manifest.cdm.json&simpleChrome=true"> <img src="docs/auto-accel-static.png"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/bankingAccelerator.manifest.cdm.json&simpleChrome=true"> <img src="docs/banking-accel-static.png"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/electronicMedicalRecordsAccelerator.manifest.cdm.json&simpleChrome=true"> <img src="docs/medical-accel-static.png"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/higherEducationAccelerator.manifest.cdm.json&simpleChrome=true"> <img src="docs/higher-ed-accel-static.png"/> </a><a href="https://microsoft.github.io/CDM/SchemaViz.html?initialManifest=manifests/nonProfitAccelerator.manifest.cdm.json&simpleChrome=true"> <img src="docs/non-prof-accel-static.png"/> </a> </pre> # Introduction The Common Data Model standard defines a common language for business entities covering, over time, the full range of business processes across sales, services, marketing, operations, finance, talent, and commerce and for the Customer, People, and Product entities at the core of a company's business processes. The goal of CDM is to enable data and application interoperability spanning multiple channels, service implementations, and vendors. CDM provides self-describing data (structurally and semantically), enabling applications to easily read and understand the data. The CDM is undergoing a specification effort driven by Microsoft and the documents published are continuously being iterated upon. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. # Repository Layout There are two ways to consume the information in this repository: 1. [Entity Reference Index](schemaDocuments#directory-of-cdm-entities) 2. [Visual Entity Navigator](https://microsoft.github.io/CDM/) for interactively exploring entities, entity extensions/inheritance, attributes, and relationships # Versioning Maintaining forward and backward compatibility is a key goal of the CDM. Therefore, the CDM uses only additive versioning, which means any revision of the CDM following a "1.0" release will not: * Introduce new mandatory attributes on previously published entities, or change an optional attribute to be mandatory * Rename previously published attributes or entities * Remove previously published attributes # Legal Notices Microsoft and any contributors grant you a license to the Microsoft documentation and other content in this repository under the [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode), see the [LICENSE](LICENSE) file, and grant you a license to any code in the repository under the [MIT License](https://opensource.org/licenses/MIT), see the [LICENSE-CODE](LICENSE-CODE) file. Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at http://go.microsoft.com/fwlink/?LinkID=254653. Privacy information can be found at https://privacy.microsoft.com/en-us/ Microsoft and any contributors reserve all others rights, whether under their respective copyrights, patents, or trademarks, whether by implication, estoppel or otherwise.
119
Distributed Big Data Orchestration Service
# Genie [![License](https://img.shields.io/github/license/Netflix/genie.svg)](http://www.apache.org/licenses/LICENSE-2.0) [![Issues](https://img.shields.io/github/issues/Netflix/genie.svg)](https://github.com/Netflix/genie/issues) [![NetflixOSS Lifecycle](https://img.shields.io/osslifecycle/Netflix/genie.svg)]() ## Introduction Genie is a federated Big Data orchestration and execution engine developed by Netflix. Genieโ€™s value is best described in terms of the problem it solves. Big Data infrastructure is complex and ever-evolving. Data consumers (Data Scientists or other applications) need to jump over a lot of hurdles in order to run a simple query: - Find, download, install and configure a number of binaries, libraries and tools - Point to the correct cluster, using valid configuration and reasonable parameters, some of which are very obscure - Manually monitor the query, retrieve its output What works today, may not work tomorrow. The cluster may have moved, the binaries may no longer be compatible, etc. Multiply this overhead times the number of data consumers, and it adds up to a lot of wasted time (and grief!). Data infrastructure providers face a different set of problems: - Users require a lot of help configuring their working setup, which is not easy to debug remotely - Infrastructure upgrades and expansion require careful coordination with all users Genie is designed to sit at the boundary of these two worlds, and simplify the lives of people on either side. A data scientist can โ€œrub the magic lampโ€ and just say โ€œGenie, run query โ€˜Qโ€™ using engine SparkSQL against production dataโ€. Genie takes care of all the nitty-gritty details. It dynamically assembles the necessary binaries and configurations, execute the job, monitors it, notifies the user of its completion, and makes the output data available for immediate and future use. Providers of Big data infrastructure work with Genie by making resources available for use (clusters, binaries, etc) and plugging in the magic logic that the user doesnโ€™t need to worry about: which cluster should a given query be routed to? Which version of spark should a given query be executed with? Is this user allowed to access this data? etc. Moreover, every jobโ€™s details are recorded for later audit or debugging. Genie is designed from the ground up to be very flexible and customizable. For more details visit the [official documentation](https://netflix.github.io/genie) ## Builds Genie builds are run on Travis CI [here](https://travis-ci.com/Netflix/genie). | Branch | Build | Coverage (coveralls.io) | |:--------------:|:-------------------------------------------------------------------------------------------------------------:|:------------------------------------------------------------------------------------------------------------------------------------------------------:| | master (4.2.x) | [![Build Status](https://travis-ci.com/Netflix/genie.svg?branch=master)](https://travis-ci.com/Netflix/genie) | [![Coverage Status](https://coveralls.io/repos/github/Netflix/genie/badge.svg?branch=master)](https://coveralls.io/github/Netflix/genie?branch=master) | | 4.1.x | [![Build Status](https://travis-ci.com/Netflix/genie.svg?branch=4.1.x)](https://travis-ci.com/Netflix/genie) | [![Coverage Status](https://coveralls.io/repos/github/Netflix/genie/badge.svg?branch=4.1.x)](https://coveralls.io/github/Netflix/genie?branch=4.1.x) | | 4.0.x | [![Build Status](https://travis-ci.com/Netflix/genie.svg?branch=4.0.x)](https://travis-ci.com/Netflix/genie) | [![Coverage Status](https://coveralls.io/repos/github/Netflix/genie/badge.svg?branch=4.0.x)](https://coveralls.io/github/Netflix/genie?branch=4.0.x) | ## Project structure ### `genie-app` Self-contained Genie service server. ### `genie-agent-app` Self-contained Genie CLI job executor. ### `genie-client` Genie client interact with the service via REST API. ### `genie-web` The main server library, can be re-wrapped to inject and override server components. ### `genie-agent` The main agent library, can be re-wrapped to inject and override components. ### `genie-common`, `genie-common-internal`, `genie-common-external` Internal components libraries shared by the server, agent, and client modules. ### `genie-proto` Protobuf messages and gRPC services definition shared by server and agent. This is not a public API meant for use by other clients. ### `genie-docs`, `genie-demo` Documentation and demo application. ### `genie-test`, `genie-test-web` Testing classes and utilities shared by other modules. ### `genie-ui` JavaScript UI to search and visualize jobs, clusters, commands. ### `genie-swagger` Auto-configuration of [Swagger](https://swagger.io/) via [Spring Fox](https://springfox.github.io/springfox/). Add to final deployment artifact of server to enable. ## Artifacts Genie publishes to [Maven Central](https://search.maven.org/) and [Docker Hub](https://hub.docker.com/r/netflixoss/genie-app/) Refer to the [demo]() section of the documentations for examples. And to the [setup]() section for more detailed instructions to set up Genie. ## Python Client The [Genie Python client](https://github.com/Netflix/pygenie) is hosted in a different repository. ## Further info For a detailed explanation of Genie architecture, use cases, API documentation, demos, deployment and customization guides, and more, visit the [Genie documentation](https://netflix.github.io/genie). ## Contact To contact Genie developers with questions and suggestions, please use [GitHub Issues](https://github.com/Netflix/genie/issues)
120
KOOM is an OOM killer on mobile platform by Kwai.
[![license](https://img.shields.io/badge/license-Apache--2.0-brightgreen.svg)](https://github.com/KwaiAppTeam/KOOM/blob/master/LICENSE) [![Platform](https://img.shields.io/badge/Platform-Android-brightgreen.svg)](https://github.com/KwaiAppTeam/KOOM/wiki/home) # KOOM An OOM killer on mobile platform by Kwai. ไธญๆ–‡็‰ˆๆœฌ่ฏทๅ‚็œ‹[่ฟ™้‡Œ](README.zh-CN.md) ## Introduction KOOM creates a mobile high performance online memory monitoring solution๏ผŒwhich supplies a detailed report when OOM related problems are detected, and has solved a large number of OOM issues in the Kwai application. It's currently available on **Android**. With the increasing complexity of mobile terminal business logic and the gradual popularity of scenarios with high memory requirements such as 4K codec and AR magic watch, the OOM problem has become the number one problem in the stability management of the Kuaishou client. In the daily version iteration process, OOM surges occasionally occur, and the online environment is very complicated. There are thousands of AB experiments. Pre-prevention and post-recovery cannot be achieved. Therefore, high-performance online memory monitoring solutions are urgently needed. So how should OOM governance be built? At present, KOOM has the capability of monitoring leakage of Java Heap/Native Heap/Thread, and will build multi-dimensional and multi-business scenarios monitoring in the future. ## Features ### Java Leak Monitor - The `koom-java-leak` module is used for Java Heap leak monitoring: it uses the Copy-on-write mechanism to fork the child process dump Java Heap, which solves the problem. The app freezes for a long time during the dump. For details, please refer to [here](./koom-java-leak/README.md) ### Native Leak Monitor - The `koom-native-leak` module is a Native Heap leak monitoring solution: use the [Tracing garbage collection](https://en.wikipedia.org/wiki/Tracing_garbage_collection) mechanism to analyze the entire Native Heap, and directly output the leaked memory information like: size/Allocating stacks/etc.; greatly reduces the cost of analyzing and solving memory leaks for business students. For details, please refer to [here](./koom-native-leak/README.md) ### Thread Leak Monitor - The `koom-thread-leak` module is used for Thread leak monitoring: it hooks the life cycle function of the thread, and periodically reports the leaked thread information. For details, please refer to [here](./koom-thread-leak/README.md) ## STL Support All Native modules support two access modes, c++_shared and c++_static. For details, please refer to [cpp-support](https://developer.android.com/ndk/guides/cpp-support). - Add dependency to the project build.gradle (take koom-java-leak as an example)๏ผš ```groovy dependencies { // In shared mode, multiple modules share the same libc++_shared.so (STL), and the package // size is small, but when multiple modules depend on different STL versions, the final // compilation will conflict. For example, you might get "dlopen failed: cannot locate symbol // "__emutls_get_address" referenced by" errors. implementation "com.kuaishou.koom:koom-java-leak:${latest_version}" // Or in static mode, each module has its own STL, the package size is large, and there are no // compilation and runtime problems. implementation "com.kuaishou.koom:koom-java-leak-static:${latest_version}" // If you depend on multiple modules, the shared and static modes cannot be mixed. // The following way is wrong, remember! implementation "com.kuaishou.koom:koom-java-leak-static:${latest_version}" implementation "com.kuaishou.koom:koom-monitor-base:${latest_version}" } ``` - Introduce a way to resolve the conflict of shared mode, add `pickFirst` in the project root directory build.gradle๏ผš ```groovy packagingOptions { // Select the first libc++_shared.so when packaging apk, it may encounter unpredictable bugs // at runtime, use it with caution! pickFirst 'lib/*/libc++_shared.so' } ``` ## minSdk - The minSdk of all modules is 18. If the minSdk of your app is lower than that, it needs to be compatible with overrideLibrary in the manifest. ```xml <uses-sdk tools:overrideLibrary="com.kwai.koom.fastdump, com.kwai.android.base, com.kwai.koom.base" /> ``` ## License KOOM is under the Apache license 2.0. For details check out the [LICENSE](./LICENSE). ## Change Log Check out the [CHANGELOG.md](./CHANGELOG.md) for details of change history. ## Contributing If you are interested in contributing, check out the [CONTRIBUTING.md](./CONTRIBUTING.md) ## Feedback Welcome report [issues](https://github.com/KwaiAppTeam/KOOM/issues) or contact us in WeChat group. <img src=./doc/images/wechat.jpg/>
121
Extended Android Tab Layout with animated indicators that have continuous feedback.
# Dachshund Tab Layout [![](https://img.shields.io/badge/minSDK-15-brightgreen.svg)](https://developer.android.com/training/basics/supporting-devices/platforms.html) [![](https://jitpack.io/v/Andy671/Dachshund-Tab-Layout.svg)](https://jitpack.io/#Andy671/Dachshund-Tab-Layout) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) # ![Logo](https://raw.githubusercontent.com/Andy671/Dachshund-Tab-Layout/master/dachshund_logo.png) ## Introduction Boosted Android Tab Layout with custom animated indicators including "Dachshund" animation inspired by [this](https://material.uplabs.com/posts/tab-interaction). ## Sample ![](http://i.giphy.com/1VVYHwT4OFf6U.gif) ## Available Animated Indicators | Indicator | Example | Custom behavior | |--------------------- |--------------------------------| ----- | | DachshundIndicator | ![](http://i.giphy.com/115nZIzHqsDpcI.gif) | | | PointMoveIndicator |![](http://i.giphy.com/yK9y4NcPH7wNa.gif) | setInterpolator(TimeInterpolator interpolator) | | LineMoveIndicator | ![](http://i.giphy.com/rzvsTmlUOod0I.gif) | setEdgeRadius(int edgeRadius)| | PointFadeIndicator | ![](http://i.giphy.com/nQZYOyfYH7gJy.gif) | | | LineFadeIndicator | ![](http://i.giphy.com/PHUmWmrM0O7YI.gif) | setEdgeRadius(int edgeRadius)| ### ## Installation ### Step 1 Add the JitPack repository to your build file ```gradle allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` ### Step 2 Add the dependency ```gradle dependencies { compile 'com.github.Andy671:Dachshund-Tab-Layout:v0.3.3' } ``` # Usage DachshundTabLayout is a subclass of TabLayout, so usage is pretty similar. The most of the original methods should work without any problems. See sample and source code for more info. Add DachshundTabLayout to xml (after the Toolbar in the AppBarLayout), if you have TabLayout simply replace it: ```xml <android.support.design.widget.AppBarLayout ... <android.support.v7.widget.Toolbar .../> <com.kekstudio.dachshundtablayout.DachshundTabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` Setup it with a ViewPager: ```java DachshundTabLayout tabLayout = (DachshundTabLayout) findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(yourViewPager); ``` If you want to change animated indicator (see **Available Animated Indicators**): ```java //AvailableAnimatedIndicator - change it with available animated indicator AvailableAnimatedIndicator indicator = new AvailableAnimatedIndicator(tabLayout); tabLayout.setAnimatedIndicator(indicator); ``` ## Center align In **v0.3.2** I've added **ddCenterAlign** parameter. You can use it when you want to center the tabs in **scrollable** tabMode. Working behavior from [Stackoverflow](https://stackoverflow.com/questions/33191794/android-tablayout-with-active-tab-always-at-center-just-like-in-play-newsstand) question. ```xml <com.kekstudio.dachshundtablayout.DachshundTabLayout ... custom:tabMode="scrollable" custom:ddCenterAlign="true"/> ``` ## Creating custom AnimatedIndicator If you want to create your own custom AnimatedIndicator - you can implement AnimatedIndicatorInterface and if you want to use animators - AnimatorUpdateListener (See JavaDoc of AnimatedIndicatorInterface for more info): ```java public class CustomIndicator implements AnimatedIndicatorInterface, ValueAnimator.AnimatorUpdateListener { private DachshundTabLayout dachshundTabLayout; public CustomIndicator(DachshundTabLayout dachshundTabLayout){ this.dachshundTabLayout = dachshundTabLayout; //here set-up your Animators, Paints etc. } @Override public void onAnimationUpdate(ValueAnimator animator) { // when animator updates - invalidate your canvas, and draw what you want. } @Override public void setSelectedTabIndicatorColor(@ColorInt int color) { // customization of color } @Override public void setSelectedTabIndicatorHeight(int height) { // customization of height } @Override public void setIntValues(int startXLeft, int endXLeft, int startXCenter, int endXCenter, int startXRight, int endXRight){ // X-positions of the target and current tabs } @Override public void setCurrentPlayTime(long currentPlayTime) { // current play time of the animation } @Override public void draw(Canvas canvas) { //Make your draw calls here } @Override public long getDuration() { return DEFAULT_DURATION; } } ``` ## XML Attributes | Attribute | Type | Default | | ----------------------|:-------------------:| :-----------| | ddIndicatorHeight | dimension | 6dp | | ddIndicatorColor | color | Color.WHITE | | ddAnimatedIndicator | enum [dachshund, pointMove, lineMove, pointFade, lineFade] | dachshund | ## Contribution - Feel free to fork the repo, make pull requests or fix existing bug - Feel free to open issues if you find some bug or unexpected behaviour
122
Apache Maven Daemon
null
123
Microservices using Spring Boot, Spring Cloud, Docker and Kubernetes
# Spring MicroServices [![Image](https://www.springboottutorial.com/images/Course-Master-Microservices-with-Spring-Boot-and-Spring-Cloud.png "Master Microservices with Spring Boot and Spring Cloud")](https://www.udemy.com/course/microservices-with-spring-boot-and-spring-cloud/) Learn how to create awesome Microservices and RESTful web services with Spring and Spring Boot. ## Overview * [Installing Tools](#installing-tools) * [Running Examples](#running-examples) * [Course Overview](#course-overview) - [Course Steps](#step-list) - [Expectations](#expectations) * [About in28Minutes](#about-in28minutes) - [Our Beliefs](#our-beliefs) - [Our Approach](#our-approach) - [Find Us](#useful-links) - [Other Courses](#other-courses) ### Introduction Developing RESTful web services is fun. The combination of Spring Boot, Spring Web MVC, Spring Web Services and JPA makes it even more fun. And its even more fun to create Microservices. There are two parts to this course - RESTful web services and Microservices Architectures are moving towards microservices. RESTful web services are the first step to developing great microservices. Spring Boot, in combination with Spring Web MVC (also called Spring REST) makes it easy to develop RESTful web services. In the first part of the course, you will learn the basics of RESTful web services developing resources for a social media application. You will learn to implement these resources with multiple features - versioning, exception handling, documentation (Swagger), basic authentication (Spring Security), filtering and HATEOAS. You will learn the best practices in designing RESTful web services. In this part of the course, you will be using Spring (Dependency Management), Spring MVC (or Spring REST), Spring Boot, Spring Security (Authentication and Authorization), Spring Boot Actuator (Monitoring), Swagger (Documentation), Maven (dependencies management), Eclipse (IDE), Postman (REST Services Client) and Tomcat Embedded Web Server. We will help you set up each one of these. In the second part of the course, you will learn the basics of Microservices. You will understand how to implement microservices using Spring Cloud. In this part of the course, you will learn to establish communication between microservices, enable load balancing, scaling up and down of microservices. You will also learn to centralize configuration of microservices with Spring Cloud Config Server. You will implement Eureka Naming Server and Distributed tracing with Spring Cloud Sleuth and Zipkin. You will create fault toleranct microservices with Zipkin ### You will learn - You will be able to develop and design RESTful web services - You will setup Centralized Microservice Configuration with Spring Cloud Config Server - You will understand how to implement Exception Handling, Validation, HATEOAS and filtering for RESTful Web Services. - You will implement client side load balancing (Ribbon), Dynamic scaling(Eureka Naming Server) and an API Gateway (Zuul) - You will learn to implement Distributed tracing for microservices with Spring Cloud Sleuth and Zipkin - You will implement Fault Tolerance for microservices with Zipkin - You will understand how to version your RESTful Web Services - You will understand how to monitor RESTful Services with Spring Boot Actuator - You will understand how to document RESTful Web Services with Swagger - You will understand the best practices in designing RESTful web services - Using Spring Cloud Bus to exchange messages about Configuration updates - Simplify communication with other Microservices using Feign REST Client ### Step Wise Details Refer each steps ### Expectations - You should know Java and Spring. - A basic understanding of developing web applications is a bonus but NOT mandatory. - A basic understanding of Spring Boot is a bonus but NOT mandatory. We have seperate section to introduce Spring Boot. - A basic understanding of JPA is a bonus but NOT mandatory. We have seperate section to introduce JPA. - You are NOT expected to have any experience with Eclipse, Maven or Tomcat. - We will help you install Eclipse and get up and running with Maven and Tomcat. ## Installing Tools - Eclipse & Embedded Maven - PostMan - Git Client - https://git-scm.com/ - Rabbit MQ - https://www.rabbitmq.com/download.html ### Installing Eclipse & Embedded Maven - Installation Video : https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3 - GIT Repository For Installation : https://github.com/in28minutes/getting-started-in-5-steps - PDF : https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf ### Installing Rabbit MQ #### Windows - https://www.rabbitmq.com/install-windows.html - https://www.rabbitmq.com/which-erlang.html - http://www.erlang.org/downloads - Video - https://www.youtube.com/watch?v=gKzKUmtOwR4 #### Mac - https://www.rabbitmq.com/install-homebrew.html ## Running Examples - Download the zip or clone the Git repository. - Unzip the zip file (if you downloaded one) - Open Command Prompt and Change directory (cd) to folder containing pom.xml - Open Eclipse - File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip - Select the right project - Choose the Spring Boot Application file (search for @SpringBootApplication) - Right Click on the file and Run as Java Application - You are all Set - For help : use our installation guide - https://www.youtube.com/playlist?list=PLBBog2r6uMCSmMVTW_QmDLyASBvovyAO3 ### Diagrams - Check notes.md ### Troubleshooting - Refer our TroubleShooting Guide - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ ## Youtube Playlists - 500+ Videos [Click here - 30+ Playlists with 500+ Videos on Spring, Spring Boot, REST, Microservices and the Cloud](https://www.youtube.com/user/rithustutorials/playlists?view=1&sort=lad&flow=list) ## Keep Learning in28Minutes in28Minutes is creating amazing solutions for you to learn Spring Boot, Full Stack and the Cloud - Docker, Kubernetes, AWS, React, Angular etc. - [Check out all our courses here](https://github.com/in28minutes/learn) ![in28MinutesLearningRoadmap-July2019.png](https://github.com/in28minutes/in28Minutes-Course-Roadmap/raw/master/in28MinutesLearningRoadmap-July2019.png)
124
Gephi - The Open Graph Viz Platform
# Gephi - The Open Graph Viz Platform [![build](https://github.com/gephi/gephi/actions/workflows/build.yml/badge.svg)](https://github.com/gephi/gephi/actions/workflows/build.yml) [![Downloads](https://img.shields.io/github/downloads/gephi/gephi/v0.10.1/total.svg)](https://github.com/gephi/gephi/releases/tag/v0.10.1) [![Downloads](https://img.shields.io/github/downloads/gephi/gephi/total.svg)](https://github.com/gephi/gephi/releases/) [![Translation progress](https://hosted.weblate.org/widgets/gephi/-/svg-badge.svg)](https://hosted.weblate.org/engage/gephi/?utm_source=widget) [Gephi](http://gephi.org) is an award-winning open-source platform for visualizing and manipulating large graphs. It runs on Windows, Mac OS X and Linux. Localization is available in English, French, Spanish, Japanese, Russian, Brazilian Portuguese, Chinese, Czech, German and Romanian. - **Fast** Powered by a built-in OpenGL engine, Gephi is able to push the envelope with very large networks. Visualize networks up to a million elements. All actions (e.g. layout, filter, drag) run in real-time. - **Simple** Easy to install and [get started](https://gephi.github.io/users/quick-start). An UI that is centered around the visualization. Like Photoshopโ„ข for graphs. - **Modular** Extend Gephi with [plug-ins](https://gephi.org/plugins). The architecture is built on top of [Apache Netbeans Platform](https://netbeans.apache.org/tutorials/nbm-quick-start.html) and can be extended or reused easily through well-written APIs. [Download Gephi](https://gephi.github.io/users/download) for Windows, Mac OS X and Linux and consult the [release notes](https://github.com/gephi/gephi/releases). Example datasets can be found on our [wiki](https://github.com/gephi/gephi/wiki/Datasets). ![Gephi](https://gephi.github.io/images/screenshots/select-tool-mini.png) ## Install and use Gephi Download and [Install](https://gephi.github.io/users/install/) Gephi on your computer. Get started with the [Quick Start](https://gephi.github.io/users/quick-start/) and follow the [Tutorials](https://gephi.github.io/users/). Load a sample [dataset](https://github.com/gephi/gephi/wiki/Datasets) and start to play with the data. If you run into any trouble or have questions consult our [discussions](https://github.com/gephi/gephi/discussions). ## Latest releases ### Stable - Latest stable release on [gephi.org](https://gephi.org/users/download/). ### Development builds Development builds are [generated regularly](https://github.com/gephi/gephi/actions/workflows/release.yml). Current version is 0.10.2-SNAPSHOT - [gephi-0.10.2-SNAPSHOT-windows-x64.exe](https://oss.sonatype.org/service/local/artifact/maven/content?r=snapshots&g=org.gephi&a=gephi&v=0.10.2-SNAPSHOT&c=windows-x64&p=exe) (Windows) - [gephi-0.10.2-SNAPSHOT-windows-x32.exe](https://oss.sonatype.org/service/local/artifact/maven/content?r=snapshots&g=org.gephi&a=gephi&v=0.10.2-SNAPSHOT&c=windows-x32&p=exe) (Windows x32) - [gephi-0.10.2-SNAPSHOT-macos-x64.dmg](https://oss.sonatype.org/service/local/artifact/maven/content?r=snapshots&g=org.gephi&a=gephi&v=0.10.2-SNAPSHOT&c=macos-x64&p=dmg) (Mac OS X) - [gephi-0.10.2-SNAPSHOT-macos-aarch64.dmg](https://oss.sonatype.org/service/local/artifact/maven/content?r=snapshots&g=org.gephi&a=gephi&v=0.10.2-SNAPSHOT&c=macos-aarch64&p=dmg) (Mac OS X Silicon) - [gephi-0.10.2-SNAPSHOT-linux-x64.tar.gz](https://oss.sonatype.org/service/local/artifact/maven/content?r=snapshots&g=org.gephi&a=gephi&v=0.10.2-SNAPSHOT&c=linux-x64&p=tar.gz) (Linux) ## Developer Introduction Gephi is developed in Java and uses OpenGL for its visualization engine. Built on the top of Netbeans Platform, it follows a loosely-coupled, modular architecture philosophy. Gephi is split into modules, which depend on other modules through well-written APIs. Plugins can reuse existing APIs, create new services and even replace a default implementation with a new one. Consult the [**Javadoc**](http://gephi.github.io/gephi/0.9.2/apidocs/index.html) for an overview of the APIs. ### Requirements - Java JDK 11 (or later) - [Apache Maven](http://maven.apache.org/) version 3.6.3 or later ### Checkout and Build the sources - Fork the repository and clone git clone [email protected]:username/gephi.git - Run the following command or [open the project in an IDE](https://github.com/gephi/gephi/wiki/How-to-build-Gephi) mvn -T 4 clean install - Once built, one can test running Gephi cd modules/application mvn nbm:cluster-app nbm:run-platform Note that while Gephi can be built using JDK 11 or later, it currently requires JDK 11 to run. ### Create Plug-ins Gephi is extensible and lets developers create plug-ins to add new features, or to modify existing features. For example, you can create a new layout algorithm, add a metric, create a filter or a tool, support a new file format or database, or modify the visualization. - [**Plugins Portal**](https://github.com/gephi/gephi/wiki/Plugins) - [Plugins Quick Start (5 minutes)](https://github.com/gephi/gephi/wiki/Plugin-Quick-Start) - Browse the [plugins](https://gephi.org/plugins) created by the community - We've created a [**Plugins Bootcamp**](https://github.com/gephi/gephi-plugins-bootcamp) to learn by examples. ## Gephi Toolkit The Gephi Toolkit project packages essential Gephi modules (Graph, Layout, Filters, IOโ€ฆ) in a standard Java library which any Java project can use for getting things done. It can be used on a server or command-line tool to do the same things Gephi does but automatically. - [Download](https://gephi.org/toolkit/) - [GitHub Project](https://github.com/gephi/gephi-toolkit) - [Toolkit Portal](https://github.com/gephi/gephi/wiki/Toolkit) ## Localization We use [Weblate](https://hosted.weblate.org/projects/gephi/) for localization. Follow the guidelines on the [wiki](https://github.com/gephi/gephi/wiki/Localization) for more details how to contribute. ## Icons Gephi uses icons from various sources. The icons are licensed under the [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/) license. All icons can be found in the `DesktopIcons` module, organised by module name. ## License Gephi main source code is distributed under the dual license [CDDL 1.0](http://www.opensource.org/licenses/CDDL-1.0) and [GNU General Public License v3](http://www.gnu.org/licenses/gpl.html). Read the [Legal FAQs](http://gephi.github.io/legal/faq/) to learn more. Copyright 2011 Gephi Consortium. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 3 only ("GPL") or the Common Development and Distribution License ("CDDL") (collectively, the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the License at http://gephi.github.io/developers/license/ or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the specific language governing permissions and limitations under the License. When distributing the software, include this License Header Notice in each file and include the License files at /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" If you wish your version of this file to be governed by only the CDDL or only the GPL Version 3, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 3] license." If you do not indicate a single choice of license, a recipient has the option to distribute your version of this file under either the CDDL, the GPL Version 3 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 3 code and therefore, elected the GPL Version 3 license, then the option applies only if the new code is made subject to such option by the copyright holder.
125
LibRec: A Leading Java Library for Recommender Systems, see
<img src="http://librec.net/images/logo.png" height="25%" width="25%" /> **LibRec** (http://www.librec.net) is a Java library for recommender systems (Java version 1.7 or higher required). It implements a suit of state-of-the-art recommendation algorithms, aiming to resolve two classic recommendation tasks: **rating prediction** and **item ranking**. [![Join the chat at https://gitter.im/librec/Lobby](https://badges.gitter.im/librec/Lobby.svg)](https://gitter.im/librec/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ### Authors Words about the NEW Version It has been a year since the last version was released. In this year, lots of changes have been taken to the LibRec project, and the most significant one is the formulation of the LibRec team. The team pushes forward the development of LibRec with the wisdom of many experts, and the collaboration of experienced and enthusiastic contributors. Without their great efforts and hardworking, it is impossible to reach the state that a single developer may dream of. LibRec 2.0 is not the end of our teamwork, but just the begining of greater objectives. We aim to continously provide NEXT versions for better experience and performance. There are many directions and goals in plan, and we will do our best to make them happen. It is always exciting to receive any code contributions, suggestions, comments from all our LibRec users. We hope you enjoy the new version! PS: Follow us on WeChat to have first-hand and up-to-date information about LibRec. <img src="http://librec.net/images/mp.jpg" height="25%" width="25%" /> ### Features * **Rich Algorithms:** More than 70 recommendation algorithms have been implemented, and more will be added to the LibRec project. * **Module Composition:** LibRec has six main components including data split, data conversion, similarity, algorithms, evaluators and filters. * **Flexible Configuration:** LibRec is based on low coupling, flexible and either external textual or internal API configuration. * **High Performance:** LibRec has more efficient implementations than other counterparts while producing comparable accuracy. * **Simple Usage:** LibRec can get executed in a few lines of codes, and a number of demos are provided for easy start. * **Easy Expansion:** LibRec provides a set of recommendation interfaces for easy expansion to implement new recommenders. <img src="http://librec.net/images/modules.png" height="30%" width="30%" /> ### Download * **librec-v2.0** * RC version: check out the new 2.0.0-RC branch. * **[librec-v1.3](http://www.librec.net/release/librec-v1.3.zip)** * **[librec-v1.2](http://www.librec.net/release/librec-v1.2.zip)** * **[librec-v1.1](http://www.librec.net/release/librec-v1.1.zip)** * **[librec-v1.0](http://www.librec.net/release/librec-v1.0.zip)** ### Execution You can run LibRec with configurations from command arguments: <pre> librec rec -exec -D rec.recommender.class=itemcluster -D rec.pgm.number=10 -D rec.iterator.maximum=20 </pre> or from a configuration file: <pre> librec rec -exec -conf itemcluster-test.properties </pre> ### Code Snippet You can use **LibRec** as a part of your projects, and use the following codes to run a recommender. <pre> public void main(String[] args) throws Exception { // recommender configuration Configuration conf = new Configuration(); Resource resource = new Resource("rec/cf/userknn-test.properties"); conf.addResource(resource); // build data model DataModel dataModel = new TextDataModel(conf); dataModel.buildDataModel(); // set recommendation context RecommenderContext context = new RecommenderContext(conf, dataModel); RecommenderSimilarity similarity = new PCCSimilarity(); similarity.buildSimilarityMatrix(dataModel, true); context.setSimilarity(similarity); // training Recommender recommender = new UserKNNRecommender(); recommender.recommend(context); // evaluation RecommenderEvaluator evaluator = new MAEEvaluator(); recommender.evaluate(evaluator); // recommendation results List<RecommendedItem> recommendedItemList = recommender.getRecommendedList(); RecommendedFilter filter = new GenericRecommendedFilter(); recommendedItemList = filter.filter(recommendedItemList); } </pre> ### Reference Please cite the following papers if LibRec is helpful to your research. 1. Guibing Guo, Jie Zhang, Zhu Sun and Neil Yorke-Smith, [LibRec: A Java Library for Recommender Systems](http://ceur-ws.org/Vol-1388/demo_paper1.pdf), in Posters, Demos, Late-breaking Results and Workshop Proceedings of the 23rd Conference on User Modelling, Adaptation and Personalization (UMAP), 2015. ### Acknowledgement We would like to express our appreciation to the following people for contributing source codes to LibRec, including [Prof. Robin Burke](http://josquin.cti.depaul.edu/~rburke/), [Bin Wu](https://github.com/wubin7019088), [Ge Zhou](https://github.com/466152112), [Ran Locar](https://github.com/ranlocar), [Shawn Rutledge](https://github.com/shawndr), [Tao Lian](https://github.com/taolian), [Takuya Kitazawa](https://github.com/takuti), etc. We also appreciate many others for reporting bugs and issues, and for providing valuable suggestions and support. ### Publications LibRec has been used in the following publications (let me know if your paper is not listed): 1. G. Guo, J. Zhang and N. Yorke-Smith, TrustSVD: Collaborative Filtering with Both the Explicit and Implicit Influence of User Trust and of Item Ratings, in Proceedings of the 29th AAAI Conference on Artificial Intelligence (AAAI), 2015, 123-129. 2. Z. Sun, G. Guo and J. Zhang, Exploiting Implicit Item Relationships for Recommender Systems, in Proceedings of the 23rd International Conference on User Modeling, Adaptation and Personalization (UMAP), 2015. ### GPL License LibRec is [free software](http://www.gnu.org/philosophy/free-sw.html): you can redistribute it and/or modify it under the terms of the [GNU General Public License (GPL)](http://www.gnu.org/licenses/gpl.html) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LibRec is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with LibRec. If not, see http://www.gnu.org/licenses/.
126
EPI Judge - Preview Release
# EPI Judge ## Beta 5 ## Introduction EPI Judge is meant to serve as a companion to our book Elements of Programming Interviews. Specifically, this project consists of the following: - **Stub programs** for each problem in our book in Python, Java, and C++ - **Test-cases** that cover common corner-case and performance bugs - A **framework** for running these tests on your implementation on your machine ## Installation Here's how to download the judge: $ git clone https://github.com/adnanaziz/EPIJudge.git If you do not have `git`, here's a good [tutorial](https://www.atlassian.com/git/tutorials/install-git) on installing git itself. ## Running the judge using IDEs Check out these one minute videos to see how easy it is to get started with the judge. ### Python [PyCharm](https://youtu.be/ImD_iI-uGYo), [Eclipse](https://youtu.be/rZ1qqwEXwQY), [NetBeans](https://youtu.be/Z41jW1TyZwY) ### Java [IntelliJ IDEA](https://youtu.be/1BzHUpluQHM), [Eclipse](https://youtu.be/i9uz9Zazo0A) ### C++ [CLion](https://youtu.be/aHPDApyyYEg), [Visual Studio 2017](https://youtu.be/hgd8IIQpBEE) ## Running the judge from the command line ### Python $ python3 <program_name>.py #### Java Use the [`Makefile`](https://github.com/adnanaziz/EPIJudge/blob/master/epi_judge_java/Makefile). Compile and run a specific program: $ make <program_name> Example: $ make Anagrams Compile and run the last program that you edited: $ make ### C++ You can manually compile and run all programs by directly invoking GCC and Clang. $ g++ -pthread -std=c++14 -O3 -o anagrams anagrams.cc You can also use the provided Makefile: `make <program_name>`. You can also use CMake with the provided CMakeLists.txt file. $ make The default Makefile target is the last edited file. $ make anagrams ## FAQ - How can I contact the authors? Please feel free to send us questions and feedback - `[email protected]` and `[email protected]` - Help, my EPIJudge is not working, what should I do? If you do have issues, e.g., with install or with buggy tests, feel free to reach out to us via email. Please be as detailed as you can: the ideal is if you can upload a screencast video of the issue to youtube; failing that, please upload screenshots. The more detailed the description of the problem and your environment (OS, language version, IDE and version), the easier itโ€™ll be for us to help you. - I'm new to programming, and don't have any kind of development environment, what should I do? The IntelliJ Integrated Development environments described above are best-in-class, and have free versions that will work fine for the EPI Judge. They do not include the compilers. You can get the Java development environment from [Oracle](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html), and the Python development environment from [Python.org](https://www.python.org/downloads/). For C++, you have multiple options. The simplest is to install [VisualStudio](https://code.visualstudio.com/download), which includes both the IDE and the compiler. Google is a good resource for installation help. - What compilers are supported for judge? - C++ - Linux - **GCC** 5.4.1 and newer - **Clang** 4.0 and newer - OS X - **Apple LLVM Clang** 9.0.0 and newer - Windows - **Visual Studio** 2017 and newer - **MinGW** GCC 5.4.0 and newer - **LXSS** (Windows Subsystem for Linux) GCC 5.4.0 and newer - Java - **Java** 9 and newer - Python - **Python** 3.7 and newer - What compilers are supported for solutions? - C++ - Linux - **GCC** 7.0.0 and newer - **Clang** 5.0 and newer - OS X - **Apple LLVM Clang** 9.0.0 and newer - Windows - **Visual Studio** 2017 and newer - **MinGW** GCC 7.2.0 and newer - **LXSS** (Windows Subsystem for Linux) GCC 7.2.0 and newer - Java - **Java** 9 and newer - Python - **Python** 3.6 and newer Let us know if you managed to compile with an older version. - What does the UI look like? Take a look at this screenshot. <img src="http://elementsofprogramminginterviews.com/img/judge-ide-example.png" width="600px"></img> - How can I understand the test framework better? The judge harness is fairly complex (but does not use nonstandard language features or libraries). You are welcome to study it, but weโ€™d advise you against making changes to it (since it will lead to nasty merge conflicts when you update). - How do I import the C++ project? If you want to import the project into your favourite IDE, you probably need to create IDE project with [CMake](https://cmake.org/) (no need to do it for CLion, it supports CMake out-of-the-box). Here is an example recipe for generationg Visual Studio project ([list](https://cmake.org/cmake/help/v3.10/manual/cmake-generators.7.html) of all CMake supported IDEs). After installing CMake, open your terminal, go to `epi_judge_cpp` folder and run following commands: mkdir vs cd vs cmake -G "Visual Studio 15 2017" .. Then just open `epi_judge_cpp/vs/epi_judge_cpp.sln` solution with Visual Studio and it will load all EPI programs. ## Tracking your progress The file [index.html](https://github.com/adnanaziz/EPIJudge/blob/master/index.html) in the root of this project tracks your progress through the problems. Specifically, there's an expanding tab for each chapter. Click on it, and you will see your progress, e.g., as below. This file gets updated each time you execute a program. You can **use this file to map book problems to stub programs**. <img src="https://i.imgur.com/xjf7Z32.png" width="600px"></img> ## Acknowledgments A big shout-out to the hundreds of users who tried out the release over the past couple of months. As always, we never fail to be impressed by the enthusiasm and commitment our readers have; it has served to bring out the best in us. We all thank [Viacheslav Kroilov](https://github.com/metopa), for applying his exceptional software engineering skills to make EPI Judge a reality.
127
LINE Messaging API SDK for Java
# LINE Messaging API SDK for Java [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.linecorp.bot/line-bot-model/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.linecorp.bot/line-bot-model) [![javadoc](https://javadoc.io/badge2/com.linecorp.bot/line-bot-model/javadoc.svg)](https://javadoc.io/doc/com.linecorp.bot/line-bot-model) [![codecov](https://codecov.io/gh/line/line-bot-sdk-java/branch/master/graph/badge.svg)](https://codecov.io/gh/line/line-bot-sdk-java) ## Introduction The LINE Messaging API SDK for Java makes it easy to develop bots using LINE Messaging API, and you can create a sample bot within minutes. ## Documentation See the official API documentation for more information. - English: https://developers.line.biz/en/docs/messaging-api/overview/ - Japanese: https://developers.line.biz/ja/docs/messaging-api/overview/ ## Requirements This library requires Java 8 or later. ## Installation We've uploaded this library to the Maven Central Repository. You can install the modules using Maven or Gradle. http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.linecorp.bot%22 ## Modules This project contains the following modules: * line-bot-api-client: API client library for the Messaging API * line-bot-model: Model classes for the Messaging API * line-bot-servlet: Java servlet utilities for bot servers * line-bot-spring-boot: Spring Boot auto configuration library for bot servers This project contains the following sample projects: * sample-spring-boot-echo: A simple echo server. * sample-spring-boot-kitchensink: Full featured sample code. ## Spring Boot integration The line-bot-spring-boot module lets you build a bot application as a Spring Boot application. ```java /* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you 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. */ package com.example.bot.spring.echo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.linecorp.bot.model.event.Event; import com.linecorp.bot.model.event.MessageEvent; import com.linecorp.bot.model.event.message.TextMessageContent; import com.linecorp.bot.model.message.TextMessage; import com.linecorp.bot.spring.boot.annotation.EventMapping; import com.linecorp.bot.spring.boot.annotation.LineMessageHandler; @SpringBootApplication @LineMessageHandler public class EchoApplication { public static void main(String[] args) { SpringApplication.run(EchoApplication.class, args); } @EventMapping public TextMessage handleTextMessageEvent(MessageEvent<TextMessageContent> event) { System.out.println("event: " + event); return new TextMessage(event.getMessage().getText()); } @EventMapping public void handleDefaultMessageEvent(Event event) { System.out.println("event: " + event); } } ``` ## How do I use a proxy server? You can use `LineMessagingServiceBuilder` to configure a proxy server. It accepts your own OkHttpBuilder instance. Note: You don't need to use an add-on like Fixie to have static IP addresses for proxy servers. You can make API calls without entering IP addresses on the server IP whitelist. ## Help and media FAQ: https://developers.line.biz/en/faq/ Community Q&A: https://www.line-community.me/questions News: https://developers.line.biz/en/news/ Twitter: [@LINE_DEV](https://twitter.com/LINE_DEV) ## Versioning This project respects semantic versioning. See http://semver.org/. ## Version 5.x and 6.x This library provides the Spring Boot binding. And there are some incompatible changes between Spring Boot 2.x and 3.x. As a result, line-bot-sdk-java maintainers maintain two maintenance lines until the end of the life of Spring Boot 2.x. - line-bot-sdk-java 6.x supports Spring Boot 3.x and Jakarta EE, Java 17+(Branch: master). - line-bot-sdk-java 5.x supports Spring Boot 2.x and Java EE, Java 8+(branch: maint/5.x). Spring Boot 2.x is scheduled for retirement on 2023/11/18. This means that line-bot-sdk-java 5.x will be retired on 2023/11/18. https://endoflife.date/spring-boot We will add new features to line-bot-sdk-java 6.x. But if you send us a backport patch for maint/5.x branch, we might apply it :) ## Contributing Please check [CONTRIBUTING](CONTRIBUTING.md) before making a contribution. ## License Copyright (C) 2016 LINE Corp. 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.
128
A modern, Material Design UI for Java Swing
# Material-UI-Swing [![Maven Central](https://img.shields.io/maven-central/v/io.github.vincenzopalazzo/material-ui-swing?color=%237cc4f4&style=for-the-badge)](https://search.maven.org/search?q=g:%22io.github.vincenzopalazzo%22%20AND%20a:%22material-ui-swing%22) ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/vincenzopalazzo/material-ui-swing/build?style=for-the-badge) ![GitHub last commit](https://img.shields.io/github/last-commit/vincenzopalazzo/material-ui-swing?color=%237cc4f4&style=for-the-badge) ![GitHub All Releases](https://img.shields.io/github/downloads/atarw/material-ui-swing/total?color=%234caf50&style=for-the-badge) <div align="center"> <img src="https://raw.githubusercontent.com/material-ui-swing/material-ui-swing-icon/main/svg/java-red-icon.svg" /> </div> ## Description ![GitHub issues](https://img.shields.io/github/issues/vincenzopalazzo/material-ui-swing.svg?style=for-the-badge) ![GitHub pull requests](https://img.shields.io/github/issues-pr/vincenzopalazzo/material-ui-swing.svg?style=for-the-badge) [![Donation](https://img.shields.io/website/http/material-ui-swing.github.io/material-ui-swing-donations.svg?style=for-the-badge&up_color=yellow&up_message=Donation)](https://material-ui-swing.github.io/material-ui-swing-donations) [![Gitter chat](https://img.shields.io/gitter/room/vincenzopalazzo/material-ui-swing.svg?style=for-the-badge)](https://gitter.im/material-ui-swing/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) A modern, Material Design UI for Java Swing # Overview - [Introduction](https://github.com/vincenzopalazzo/material-ui-swing/wiki/Introduction) - [Component Supported](https://github.com/vincenzopalazzo/material-ui-swing/wiki/Component-Supported) - [Material Theming](https://github.com/vincenzopalazzo/material-ui-swing/wiki) - [Develop a new Theme](https://github.com/vincenzopalazzo/material-ui-swing/wiki) - [Screenshots](https://github.com/vincenzopalazzo/material-ui-swing/wiki/Screenshots) - [Built with](https://github.com/vincenzopalazzo/material-ui-swing/wiki/Built-with) - [Community](https://gitter.im/material-ui-swing/community?utm_source=share-link&utm_medium=link&utm_campaign=share-link) - [License](https://github.com/vincenzopalazzo/material-ui-swing/tree/development#license) ## Repository _Maven_ ```xml <dependency> <groupId>io.github.vincenzopalazzo</groupId> <artifactId>material-ui-swing</artifactId> <version>1.1.2</version> </dependency> ``` _Gradle (Groovy)_ ```groovy implementation 'io.github.vincenzopalazzo:material-ui-swing:1.1.2' ``` _Gradle (Kotlin DSL)_ ```kotlin implementation("io.github.vincenzopalazzo:material-ui-swing:1.1.2") ``` Others version [here](https://search.maven.org/artifact/io.github.vincenzopalazzo/material-ui-swing) ### Snapshot version Each master version has a SNAPSHOT version that is the official version `x.x.x + 1`, so for example for the version `v1.1.2-rc1` the version on if exist a new version of the master branch is `v1.1.2-rc2-SNAPSHOT` An example of gradle configuration is reported below _Gradle (Kotlin DSL)_ ```kotlin configurations.all { resolutionStrategy.cacheDynamicVersionsFor(0, "seconds") resolutionStrategy.cacheChangingModulesFor(0, "seconds") } repositories { ... other suff maven("https://oss.sonatype.org/content/repositories/snapshots") } dependencies { ... other stuff implementation("io.github.vincenzopalazzo:material-ui-swing:1.1.3-rc1-SNAPSHOT") } ``` ## Code Style > We live in a world where robots can drive a car, so we shouldn't just write code, we should write elegant code. This repository use [google-java-format](https://github.com/sherter/google-java-format-gradle-plugin) to maintains the code of the repository elegant, so before submit the code check the Java format with the following command on the root of the directory ```bash ./gradlew verifyGoogleJavaFormat ``` It any error are reported please run the following command to try to fix it ```bash ./gradlew googleJavaFormat ``` p.s: The gradle plugin work with all the JDK version >= 9 (or better with java byte code version compatible with the version 55.0) For more details about the JDK support see the [this issue](https://github.com/sherter/google-java-format-gradle-plugin/issues/58) and to know more about the Google Java code Style see the [this reference](https://google.github.io/styleguide/javaguide.html) ## Build with Material-UI-Swing _**List of projects with Material-UI-Swing theme**_ - [Krayon for SBGN](https://github.com/wiese42/krayon4sbgn) - [JMars 5](https://JMars.mars.asu.edu): Used by NASA and United Arab Emirates (UAE) for the last Mars missions. Contact us if you use this look and feel, so we can add your project to the list ๐Ÿ™‚ ### _Donors_ - [lilili87222](https://github.com/lilili87222) - Arizona State University - [zanderson9](https://github.com/zanderson9) You can support the project on the [Material-UI-Swing donation site](https://material-ui-swing.github.io/material-ui-swing-donations/) ## Supporters <div align="center"> <img src="docs/jetbrains-logos/jetbrains-variant-4.png" width="325" height="180"/> </div> [JetBrains' support](https://www.jetbrains.com/?from=material-ui-swing) <div align="center"> <img src="https://www.yourkit.com/images/yklogo.png"/> </div> The YourKit is used also by Google, Microsoft, PayPal, ecc. - **YourKit**: it supports open source projects with innovative and intelligent tools for monitoring and profiling Java and .NET applications. YourKit is the creator of <a href="https://www.yourkit.com/java/profiler/">YourKit Java Profiler</a>, <a href="https://www.yourkit.com/.net/profiler/">YourKit .NET Profiler</a>, and <a href="https://www.yourkit.com/youmonitor/">YourKit YouMonitor</a>. ## License <div align="center"> <img src="https://opensource.org/files/osi_keyhole_300X300_90ppi_0.png" width="150" height="150"/> </div> Copyright (c) 2018 atharva washimkar. Copyright (c) 2019-2020 atharva washimkar, Vincenzo Palazzo [email protected] Copyright (c) 2021 Vincenzo Palazzo [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
129
JetCache is a Java cache framework.
null
130
BinNavi is a binary analysis IDE that allows to inspect, navigate, edit and annotate control flow graphs and call graphs of disassembled code.
# BinNavi [![Build Status](https://api.travis-ci.org/google/binnavi.svg?branch=master)](https://travis-ci.org/google/binnavi) Copyright 2011-2020 Google LLC ## Introduction BinNavi is a binary analysis IDE - an environment that allows users to inspect, navigate, edit, and annotate control-flow-graphs of disassembled code, do the same for the callgraph of the executable, collect and combine execution traces, and generally keep track of analysis results among a group of analysts. **Note: The BinNavi project is no longer under active development.** ## Commercial third-party dependency BinNavi uses a commercial third-party graph visualisation library (yFiles) for displaying and laying out graphs. This library is immensely powerful, and not easily replaceable. In order to perform direct development using yFiles, you need a developer license for it. At the same time, we want the community to be able to contribute to BinNavi without needing a commercial yFiles license. In order to do this and conform to the yFiles license, all interfaces to yFiles need to be properly obfuscated. In order to achieve this, we did the following: 1) BinNavi and all the libraries have been split into two: The parts of the project that directly depend on yFiles were split into subpackages called "yfileswrap": * `com.google.security.zynamics.binnavi` * `com.google.security.zynamics.binnavi.yfileswrap` * `com.google.security.zynamics.zylib` * `com.google.security.zynamics.zylib.yfileswrap` * `com.google.security.zynamics.reil` * `com.google.security.zynamics.reil.yfileswrap` We are distributing a pre-built JAR file with all the code in the ``yfileswrap`` subpackages - pre-linked and obfuscated against yFiles. If you wish to change or add code in BinNavi and do not have a yFiles license, you can freely do pretty much whatever you want in the non-yfileswrap packages - you can simply put the ``lib/yfileswrap-obfuscated.jar`` into your classpath to test and see the results. If you wish to make changes to the ``yfileswrap`` subdirectories, please be aware that you will need a valid yFiles license - and any contribution that you make to the BinNavi project has to honor their license agreement. This means that you can't simply expose their inner APIs under different names etc. We will enforce this - we're very happy to have found a way to open-source BinNavi with the yFiles dependency, and we will make sure that any code we pull in respects the yFiles license. ### Note for maintainers/yFiles license holders To rebuild the yFiles wrapper library, first copy `y.jar` and `ysvg.jar` to `third_party/java/yfiles`. Then rebuild with: ``` mvn dependency:copy-dependencies ant build-yfiles-wrapper-jar mvn install:install-file \ -Dfile=target/yfileswrap-obfuscated.jar \ -DgroupId=com.google.security.zynamics.binnavi \ -DartifactId=yfileswrap-obfuscated \ -Dversion=6.1 \ -Dpackaging=jar \ -DlocalRepositoryPath=lib ``` ## Building BinNavi from scratch BinNavi uses Maven for its dependency management, but not for the actual build. Java 11 is the minimum supported version. To build from scratch use these commands: ``` mvn dependency:copy-dependencies ant build-binnavi-fat-jar ``` ## Running BinNavi for the first time Please be aware that BinNavi makes use of a central PostgreSQL database for storing disassemblies/comments/traces - so you need to have such an instance running somewhere accessible to you. You can launch BinNavi as follows: ``` java -jar target/binnavi-all.jar ``` ## Importing the project into Eclipse Loading the code into Eclipse for further development requires a little bit of configuration. 1. Install the dependencies (as described above) and make sure you have a Java SDK with 1.8 language compliance installed. 2. Create a new "Java Project From Existing Ant Buildfile" and use the file ``build.xml`` 3. Select the "javac" task found in target "build-binnavi-jar" 4. Open the "Project Properties" dialog and choose "Java build Path" showing the "Source" tab. 5. Remove all but one source folder and edit it to have the following properties: * Linked Folder Location: ``PROJECT_LOC/src/main/java`` * Folder Name: ``java`` * Click on "Next" 6. Add ``**/yfileswrap/**`` to the list of directories to exclude. 7. Go to "Run->Run As", select "Java Application" and then search for ``CMain``. You should be ready to go from here. ## Exporting disassemblies from IDA As part of this project, we are distributing an IDA Pro plugin that exports disassemblies from IDA into the PostgreSQL database format that BinNavi requires. When running BinNavi, simply configure the right path for IDA, click on the "install plugin" button if necessary -- you should now be able to import disassemblies. ## Using other disassemblers than IDA Right now, we only have the IDA export plugin - but we are hoping very much that someone will help us build export functionality for other disassemblers in the near future. ## Building BinNavi with Gradle *Please note that at current the Maven build is the authoritative build system for BinNavi. Gradle is purely experimental and is likely to change.* You can build BinNavi with gradle by running the following: On Linux / OS X: ``` $ ./gradlew clean jar ``` On Windows: ``` /gradlew.bat clean jar ``` This will produce the jar in the project route under `build/libs/`. ### Loading the project into Eclipse with Gradle On Linux / OS X: ``` $ ./gradlew eclipse ``` On Windows: ``` ./gradlew.bat eclipse ``` As part of the project creation process it will download the dependencies. Once complete do the following to load into Eclipse: 1. Open Eclipse. 2. File > Import... from menu bar. 3. From the window that appears select General > Existing Projects into Workspace. 4. Ensure the "Select root directory" radio button is selected. 5. Click Browse... and navigate to the project directory. 6. The projects area should now have "binnavi" and a tick next to it. 7. Press Finish. You Eclipse workspace is now setup and complete for BinNavi. ### Loading the project into IntelliJ with Gradle On Linux / OS X: ``` $ ./gradlew idea ``` On Windows: ``` ./gradlew.bat idea ``` As part of the project creation process it will download the dependencies. Once complete do the following to load into IntelliJ: 1. Open IntelliJ. 2. Select "Open" from main window. 3. Navigate to the project folder and should see the IntelliJ icon. This signifies its a project. 4. Press Ok and wait for it to import and load. 5. IntelliJ might not recognise it as a gradle project. Select enable from the popup window and use local gradle. Your IntelliJ environment is now setup and complete for IntelliJ.
131
Lightweight Java State Machine
Maven ===== ```xml <dependency> <groupId>com.github.stateless4j</groupId> <artifactId>stateless4j</artifactId> <version>2.6.0</version> </dependency> ``` Introduction ============ Create **state machines** and lightweight state machine-based workflows **directly in java code**. ```java StateMachineConfig<State, Trigger> phoneCallConfig = new StateMachineConfig<>(); phoneCallConfig.configure(State.OffHook) .permit(Trigger.CallDialed, State.Ringing); phoneCallConfig.configure(State.Ringing) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.CallConnected, State.Connected); // this example uses Java 8 method references // a Java 7 example is provided in /examples phoneCallConfig.configure(State.Connected) .onEntry(this::startCallTimer) .onExit(this::stopCallTimer) .permit(Trigger.LeftMessage, State.OffHook) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PlacedOnHold, State.OnHold); // ... StateMachine<State, Trigger> phoneCall = new StateMachine<>(State.OffHook, phoneCallConfig); phoneCall.fire(Trigger.CallDialed); assertEquals(State.Ringing, phoneCall.getState()); ``` stateless4j is a port of [stateless](https://github.com/nblumhardt/stateless) for java Features ======== Most standard state machine constructs are supported: * Generic support for states and triggers of any java type (numbers, strings, enums, etc.) * Hierarchical states * Entry/exit events for states * Guard clauses to support conditional transitions * User-defined actions can be executed when transitioning * Internal transitions (not calling `onExit`/`onEntry`) * Introspection Some useful extensions are also provided: * Parameterised triggers * Reentrant states Parallel states are not supported, but if you are looking for it, there is a fork that supports it: [ParallelStateless4j](https://gitlab.com/erasmusmc-public-health/parallelstateless4j/). Hierarchical States =================== In the example below, the `OnHold` state is a substate of the `Connected` state. This means that an `OnHold` call is still connected. ```java phoneCall.configure(State.OnHold) .substateOf(State.Connected) .permit(Trigger.TakenOffHold, State.Connected) .permit(Trigger.HungUp, State.OffHook) .permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed); ``` In addition to the `StateMachine.getState()` property, which will report the precise current state, an `isInState(State)` method is provided. `isInState(State)` will take substates into account, so that if the example above was in the `OnHold` state, `isInState(State.Connected)` would also evaluate to `true`. Entry/Exit Events ================= In the example, the `startCallTimer()` method will be executed when a call is connected. The `stopCallTimer()` will be executed when call completes (by either hanging up or hurling the phone against the wall.) The call can move between the `Connected` and `OnHold` states without the `startCallTimer(`) and `stopCallTimer()` methods being called repeatedly because the `OnHold` state is a substate of the `Connected` state. Entry/Exit event handlers can be supplied with a parameter of type `Transition` that describes the trigger, source and destination states. Action on transition =================== It is possible to execute a user-defined action when doing a transition. For a 'normal' or 're-entrant' transition this action will be called without any parameters. For 'dynamic' transitions (those who compute the target state based on trigger-given parameters) the parameters of the trigger will be given to the action. This action is only executed if the transition is actually taken; so if the transition is guarded and the guard forbids a transition, then the action is not executed. If the transition is taken, the action will be executed between the `onExit` handler of the current state and the `onEntry` handler of the target state (which might be the same state in case of a re-entrant transition. License ======= Apache 2.0 License Created by [@oxo42](https://github.com/oxo42) Maintained by Chris Narkiewicz [@ezaquarii](https://github.com/ezaquarii)
132
Chaos Monkey for Spring Boot
[![Apache License 2](https://img.shields.io/github/license/codecentric/chaos-monkey-spring-boot)](https://www.apache.org/licenses/LICENSE-2.0.txt) [![Build Status](https://github.com/codecentric/chaos-monkey-spring-boot/workflows/Chaos%20Monkey%20Build/badge.svg)](https://github.com/codecentric/chaos-monkey-spring-boot/actions?query=workflow%3A%22Chaos+Monkey+Build%22) [![codecov](https://codecov.io/gh/codecentric/chaos-monkey-spring-boot/branch/main/graph/badge.svg)](https://codecov.io/gh/codecentric/chaos-monkey-spring-boot) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/de.codecentric/chaos-monkey-spring-boot/badge.svg)](https://maven-badges.herokuapp.com/maven-central/de.codecentric/chaos-monkey-spring-boot/) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg)](CODE_OF_CONDUCT.adoc) [![Open in Gitpod](https://img.shields.io/badge/Open%20with-Gitpod-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/codecentric/chaos-monkey-spring-boot) [![VS Code DevContainer](https://img.shields.io/static/v1?label=VS+Code&message=DevContainer&logo=visualstudiocode&color=007ACC&logoColor=007ACC&labelColor=2C2C32)](https://open.vscode.dev/microsoft/vscode) # Chaos Monkey for Spring Boot ### inspired by Chaos Engineering at Netflix <p align="center"> <img src="docs/images/sb-chaos-monkey-logo.png"> </p> This project provides a Chaos Monkey for Spring Boot applications and will try to attack your running Spring Boot App. >Everything from getting started to advanced usage is explained in the [Documentation for Chaos Monkey for Spring Boot](https://codecentric.github.io/chaos-monkey-spring-boot/latest/) ## Introduction If you're not familiar with the principles of chaos engineering yet, check out this blog post and enter the world of chaos engineering. <a href="https://blog.codecentric.de/en/2018/07/chaos-engineering/" target="_blank"><img src="https://pbs.twimg.com/media/DhaRNO7XUAAi00i.jpg" alt="Chaos Engineering โ€“ withstanding turbulent conditions in production" width="260" height="155" border="10" /></a><br> Get familiar with the Chaos Monkey for Spring Boot in the following video, <a href="https://goo.gl/r2Tmig" target="_blank">available on YouTube</a>: <a href="https://goo.gl/r2Tmig" target="_blank"><img src="https://i.ytimg.com/vi/7sQiIR9qCdA/maxresdefault.jpg" alt="Chaos Monkey for Spring Boot" width="260" height="155" border="10" /></a><br> ## What is the goal of Chaos Monkey? Inspired by [PRINCIPLES OF CHAOS ENGINEERING](https://principlesofchaos.org/), with a focus on [Spring Boot](https://projects.spring.io/spring-boot/), Chaos Monkey wants to test applications better and especially during operation. After writing many unit and integration tests, a code coverage from 70% to 80%, this unpleasant feeling remains, how our baby behaves in production? Many questions remain unanswered: - Will our fallbacks work? - How does the application behave with network latency? - What if one of our services breaks down? - Service Discovery works, but is our Client-Side-Load-Balancing also working? As you can see, there are many more questions and open topics you have to deal with. That was the start of Chaos Monkey for Spring Boot. ### How does it work? If Spring Boot Chaos Monkey is on your classpath and activated with profile name `chaos-monkey`, it will automatically hook into your application. Now you can activate [watchers](https://codecentric.github.io/chaos-monkey-spring-boot/latest/#watchers), which look for classes to [assault](https://codecentric.github.io/chaos-monkey-spring-boot/latest/#assaults). There are also [runtime assaults](https://codecentric.github.io/chaos-monkey-spring-boot/latest/#runtime-assaults), which attack your whole application. <p align="center"> <img class="imgborder s1" width="90%" src="docs/images/sb-chaos-monkey-architecture.png"> </p> ## Be social and communicative! If you start to implement Chaos Engineering at your company, then you must be a very social and communicative person. Why? Because you will get to know many of your colleagues personally in a very short time when your chaos experiments strike. ### Check your resilience Are your services already resilient and can handle failures? Donยดt start a chaos experiment if not! ### Implement active application monitoring Check your monitoring and check if you can see the overall state of your system. There are many great tools out there to get a pleasant feeling about your entire system. ### Define steady states Define a metric to check a steady state of your service and of course your entire system. Start small with a service that is not critical. ### Do not start in production Of course, you can start in production, but keep in mind... > The best place on earth is...production!<br> > *Josh Long* ...so let's keep production as the best place on earth and look for our first experiences on another stage. If all goes well, and you're confident, run it in production. ## Documentation [Documentation](https://codecentric.github.io/chaos-monkey-spring-boot/latest/) ## Help We are using GitHub issues to track bugs, improvements and new features (for more information see [Contributions](#contributions)). If you have a general question on how to use Chaos Monkey for Spring Boot, please ask on Stack Overflow using the tag [`#spring-boot-chaos-monkey`](https://stackoverflow.com/questions/tagged/spring-boot-chaos-monkey). ## Contributions Chaos Monkey is open source and welcomes contributions from everyone. The [contribution guideline](https://github.com/codecentric/chaos-monkey-spring-boot/blob/main/CONTRIBUTING.adoc) is where you should begin in order to best understand how to contribute to this project. ## Releases [Releases](https://github.com/codecentric/chaos-monkey-spring-boot/releases)
133
A Java library for parsing and building iCalendar data models
# iCal4j - iCalendar parser and object model [RFC2445]: https://tools.ietf.org/html/rfc2445 [RFC2446]: https://tools.ietf.org/html/rfc2446 [RFC2447]: https://tools.ietf.org/html/rfc2447 [RFC5545]: https://tools.ietf.org/html/rfc5545 [RFC5546]: https://tools.ietf.org/html/rfc5546 [RFC6047]: https://datatracker.ietf.org/doc/html/rfc6047 [RFC6868]: https://datatracker.ietf.org/doc/html/rfc6868 [RFC7808]: https://datatracker.ietf.org/doc/html/rfc7808 [RFC7953]: https://datatracker.ietf.org/doc/html/rfc7953 [RFC7986]: https://datatracker.ietf.org/doc/html/rfc7986 [RFC7529]: https://datatracker.ietf.org/doc/html/rfc7529 [RFC9073]: https://datatracker.ietf.org/doc/html/rfc9073 [RFC9074]: https://datatracker.ietf.org/doc/html/rfc9074 [RFC9253]: https://www.rfc-editor.org/rfc/rfc9253.html [mavenrepo]: https://mvnrepository.com/artifact/org.mnode.ical4j/ical4j [Introduction]: #introduction [Setup]: #setup [System requirements]: #system-requirements [Release downloads]: #release-downloads [Install with Maven]: #install-with-maven [Install with Gradle]: #install-with-gradle [Usage]: #usage [Examples]: #examples [References]: #references [Specifications]: #specifications [Configuration]: #configuration [Compatibility Hints]: #compatibility-hints [Limitations]: #limitations [Development]: #development [Building with Gradle]: #building-with-gradle [Redistribution]: #redistribution [Contributing]: #contributing #### Table of Contents 1. [Introduction - What is iCal4j?][Introduction] 2. [Setup - Download and installation of iCal4j][Setup] - [System requirements - What is required to use iCal4j][System requirements] - [Release downloads - Where to get iCal4j][Release downloads] - [Install with Maven] - [Install with Gradle] 3. [Usage - The iCal4j object model and how to use it][Usage] - [Examples - common usage scenarios][Examples] 4. [References][References] 5. [Configuration options][Configuration] - [Compatibility Hints] 7. [Development - Guide for contributing to the iCalj project][Development] - [Building with Gradle] - [Redistribution] - [Contributing to iCal4j][Contributing] ## Introduction iCal4j is a Java library used to read and write iCalendar data streams as defined in [RFC2445]. The iCalendar standard provides a common data format used to store information about calendar-specific data such as events, appointments, to-do lists, etc. All of the popular calendaring tools, such as Lotus Notes, Outlook and Apple's iCal also support the iCalendar standard. - For a concise description of the goals and directions of iCal4j please take a look at the [open issues](https://github.com/ical4j/ical4j/issues). - You will find examples of how to use iCal4j in [the official website](https://www.ical4j.org/examples/overview/) and throughout the [API documentation](https://ical4j.github.io/docs/ical4j/api). - Detailed descriptions of changes included in each release may be found in the [CHANGELOG](https://ical4j.github.io/docs/ical4j/release-notes). - iCal4j was created with the help of [Open Source](http://opensource.org) software. ## Setup ### System requirements - Version 4.x - Java 8 or later - Version 3.x - Java 8 or later - Version 2.x - Java 7 or later ### Dependencies In the interests of portability and compatibility with as many environments as possible, the number of dependent libraries for iCal4j is kept to a minimum. The following describes the required (and optional) dependencies and the functionality they provide. * slf4j-api [required] - A logging meta-library with integration to different logging framework implementations. Used in all classes that require logging. * commons-lang3 [required] - Provides enhancements to the standard Java library, including support for custom `equals()` and `hashcode()` implementations. Used in all classes requiring custom equality implementations. * commons-collections4 [required] - Provides enhancements to the standard Java collections API, including support for closures. Used in `net.fortuna.ical4j.validate.Validator` implementations to reduce the duplication of code in validity checks. * javax.cache.cache-api [optional*] - Supports caching timzeone definitions. * NOTE: when not included you must set a value for the `net.fortuna.ical4j.timezone.cache.impl` configuration * commons-codec [optional] - Provides support for encoding and decoding binary data in text form. Used in `net.fortuna.ical4j.model.property.Attach` * groovy-all [optional] - The runtime for the Groovy language. Required for library enhancements such as iCalendar object construction using the `net.fortuna.ical4j.model.ContentBuilder` DSL. This library is optional for all non-Groovy features of iCal4j. * bndlib [optional] - A tool for generating OSGi library metadata and packaging OSGi bundles. This library is not a runtime requirement, and is used only to generate version information in the javadoc API documentation. ### Release Downloads * [mavenrepo] ### Install with Maven ### Install with Gradle ## Usage ### Examples ## References * [RFC5545] - Internet Calendaring and Scheduling Core Object Specification (iCalendar) * [RFC5546] - iCalendar Transport-Independent Interoperability Protocol (iTIP) * [RFC6047] - iCalendar Message-Based Interoperability Protocol (iMIP) * [RFC6868] - Parameter Value Encoding in iCalendar and vCard * [RFC7953] - Calendar Availability * [RFC7808] - Time Zone Data Distribution Service * [RFC7986] - New Properties for iCalendar * [RFC7529] - Non-Gregorian Recurrence Rules in iCalendar * [RFC9073] - Event Publishing Extensions to iCalendar * [RFC9074] - "VALARM" Extensions for iCalendar * [RFC9253] - Support for iCalendar Relationships ## Configuration net.fortuna.ical4j.parser=net.fortuna.ical4j.data.HCalendarParserFactory net.fortuna.ical4j.timezone.registry=net.fortuna.ical4j.model.DefaultTimeZoneRegistryFactory net.fortuna.ical4j.timezone.update.enabled={true|false} net.fortuna.ical4j.factory.decoder=net.fortuna.ical4j.util.DefaultDecoderFactory net.fortuna.ical4j.factory.encoder=net.fortuna.ical4j.util.DefaultEncoderFactory net.fortuna.ical4j.recur.maxincrementcount=1000 net.fortuna.ical4j.timezone.cache.impl=net.fortuna.ical4j.util.MapTimeZoneCache ### Compatibility Hints #### Relaxed Parsing ical4j.parsing.relaxed={true|false} iCal4j now has the capability to "relax" its parsing rules to enable parsing of *.ics files that don't properly conform to the iCalendar specification (RFC2445) This property is intended as a general relaxation of parsing rules to allow for parsing otherwise invalid calendar files. Initially enabling this property will allow for the creation of properties and components with illegal names (e.g. Mozilla Calendar's "X" property). Note that although this will allow for parsing calendars with illegal names, validation will still identify such names as an error in the calendar model. - You can relax iCal4j's unfolding rules by specifying the following system property: ical4j.unfolding.relaxed={true|false} Note that I believe this problem is not restricted to Mozilla calendaring products, but rather may be caused by UNIX/Linux-based applications relying on the default newline character (LF) to fold long lines (KOrganizer also seems to have this problem). This is, however, still incorrect as by definition long lines are folded using a (CRLF) combination. I've obtained a couple of samples of non-standard iCalendar files that I've included in the latest release (0.9.11). There is a Sunbird, phpicalendar, and a KOrganizer sample there (open them in Notepad on Windows to see what I mean). It seems that phpicalendar and KOrganizer always use LF instead of CRLF, and in addition KOrganizer seems to fold all property parameters and values (similar to Mozilla Calendar/Sunbird). Mozilla Calendar/Sunbird uses CRLF to fold all property parameter/values, however it uses just LF to fold long lines (i.e. longer than 75 characters). The latest release of iCal4j includes changes to UnfoldingReader that should work correctly with Mozilla Calendar/Sunbird, as long as the ical4j.unfolding.relaxed system property is set to true. KOrganizer/phpicalendar files should also work with the relaxed property, although because ALL lines are separated with just LF it also relies on the StreamTokenizer to correctly identify LF as a newline on Windows, and CRLF as a newline on UNIX/Linux. The API documentation for Java 1.5 says that it does do this, so if you still see problems with parsing it could be a bug in the Java implementation. The full set of system properties may be found in net.fortuna.ical4j.util.CompatibilityHints. #### iCal4j and Timezones net.fortuna.ical4j.timezone.date.floating={true|false} Supporting timezones in an iCalendar implementation can be a complicated process, mostly due to the fact that there is not a definitive list of timezone definitions used by all iCalendar implementations. This means that an iCalendar file may be produced by one implementation and, if the file does not include all definitions for timezones relevant to the calendar properties, an alternate implementation may not know how to interpret the timezone identified in the calendar (or worse, it may interpret the timezone differently to the original implementation). All of these possibilities mean unpredictable behaviour which, to put it nicely, is not desireable. iCal4j approaches the problem of timezones in two ways: The first and by far the preferred approach is for iCalendar files to include definitions for all timezones referenced in the calendar object. To support this, when an existing calendar is parsed a list of VTimeZone definitions contained in the calendar is constructed. This list may then be queried whenever a VTimeZone definition is required. The second approach is to rely on a registry of VTimeZone definitions. iCal4j includes a default registry of timezone definitions (derived from the Olson timezone database - a defacto standard for timezone definitions), or you may also provide your own registry implementation from which to retreieve timezones. This approach is required when constructing new iCalendar files. Note that the intention of the iCal4j model is not to provide continuous validation feedback for every change in the model. For this reason you are free to change timezones on Time objects, remove or add TzId parameters, remove or add VTimeZone definitions, etc. without restriction. However when validation is run (automatically on output of the calendar) you will be notified if the changes are invalid. #### Validation ical4j.validation.relaxed={true|false} #### Micosoft Outlook compatibility ical4j.compatibility.outlook={true|false} Behaviour: * Enforces a folding length of 75 characters (by default ical4j will fold at 73 characters) * Allows for spaces when parsing a WEEKDAY list Microsoft Outlook also appears to provide quoted TZID parameter values, as follows: DTSTART;TZID="Pacific Time (US & Canada),Tijuana":20041011T223000 #### Lotus Notes compatibility ical4j.compatibility.notes={true|false} ## Development ### Building with Gradle iCal4j includes the Gradle wrapper for a simpler and more consistent build. **Run unit tests** ./gradlew clean test **Build a new release** ./gradlew clean test release -Prelease.forceVersion=2.0.0 **Upload release binaries and packages** RELEASE_VERSION=2.0.0 ./gradlew uploadArchives uploadDist ### Redistribution If you intend to use and distribute iCal4j in your own project please follow these very simple guidelines: - Make a copy of the LICENSE, rename it to LICENSE.ical4j, and save it to the directory where you are re-distributing the iCal4j JAR. - I don't recommend extracting the iCal4j classes from its JAR and package in another JAR along with other classes. It may lead to version incompatibilites in the future. Rather I would suggest to include the ical4j.jar in your classpath as required. ### Contributing Open source software is made stronger by the community that supports it. Through participation you not only contribute to the quality of the software, but also gain a deeper insight into the inner workings. Contributions may be in the form of feature enhancements, bug fixes, test cases, documentation and forum participation. If you have a question, just ask. If you have an answer, write it down. And if you are somehow constrained from participation, through corporate policy or otherwise, consider financial support. After all, if you are profiting from open source it's only fair to give something back to the community that make it all possible.
134
ActiveJ is an alternative Java platform built from the ground up. ActiveJ redefines core, web and high-load programming in Java, providing simplicity, maximum performance and scalability
[![Maven Central](https://img.shields.io/maven-central/v/io.activej/activej)](https://mvnrepository.com/artifact/io.activej) [![GitHub](https://img.shields.io/github/license/activej/activej)](https://github.com/activej/activej/blob/master/LICENSE) ## Introduction [ActiveJ](https://activej.io) is a modern Java platform built from the ground up. It is designed to be self-sufficient (no third-party dependencies), simple, lightweight and provides competitive performance. ActiveJ consists of a range of libraries, from dependency injection and high-performance asynchronous I/O (inspired by Node.js), to application servers and big data solutions. You can use ActiveJ to build scalable web applications, distributed systems and use it for high-load data processing. ## ActiveJ components ActiveJ consists of several modules, which can be logically grouped into the following categories : * **Async.io** - High-performance asynchronous IO with the efficient event loop, NIO, promises, streaming, and CSP. Alternative to Netty, RxJava, Akka, and others. ([Promise](https://activej.io/async-io/promise), [Eventloop](https://activej.io/async-io/eventloop), [Net](https://activej.io/async-io/net), [CSP](https://activej.io/async-io/csp), [Datastream](https://activej.io/async-io/datastream)) * **HTTP** - High-performance HTTP server and client with WebSocket support. It can be used as a simple web server or as an application server. Alternative to other conventional HTTP clients and servers. ([HTTP](https://activej.io/http)) * **ActiveJ Inject** - Lightweight library for dependency injection. Optimized for fast application start-up and performance at runtime. Supports annotation-based component wiring as well as reflection-free wiring. ([ActiveJ Inject](https://activej.io/inject)) * **Boot** - Production-ready tools for running and monitoring an ActiveJ application. Concurrent control of services lifecycle based on their dependencies. Various service monitoring utilities with JMX and Zabbix support. ([Launcher](https://activej.io/boot/launcher), [Service Graph](https://activej.io/boot/servicegraph), [JMX](https://github.com/activej/activej/tree/master/boot-jmx), [Triggers](https://github.com/activej/activej/tree/master/boot-triggers)) * **Bytecode manipulation** * **ActiveJ Codegen** - Dynamic bytecode generator for classes and methods on top of [ObjectWeb ASM](https://asm.ow2.io/) library. Abstracts the complexity of direct bytecode manipulation and allows you to create custom classes on the fly using Lisp-like AST expressions. ([ActiveJ Codegen](https://activej.io/codegen)) * **ActiveJ Serializer** - [Fast](https://github.com/activej/jvm-serializers) and space-efficient serializers created with bytecode engineering. Introduces schema-free approach for best performance. ([ActiveJ Serializer](https://activej.io/serializer)) * **ActiveJ Specializer** - Innovative technology to improve class performance at runtime by automatically converting class instances into specialized static classes and class instance fields into baked-in static fields. Provides a wide variety of JVM optimizations for static classes that are impossible otherwise: dead code elimination, aggressive inlining of methods and static constants. ([ActiveJ Specializer](https://activej.io/specializer)) * **Cloud components** * **ActiveJ FS** - Asynchronous abstraction over the file system for building efficient, scalable local or remote file storages that support data redundancy, rebalancing, and resharding. ([ActiveJ FS](https://activej.io/fs)) * **ActiveJ RPC** - High-performance binary client-server protocol. Allows building distributed, sharded, and fault-tolerant microservice applications. ([ActiveJ RPC](https://activej.io/rpc)) * Various extra services: [ActiveJ CRDT](https://github.com/activej/activej/tree/master/extra/cloud-crdt), [Redis client](https://github.com/activej/activej/tree/master/extra/cloud-redis), [Memcache](https://github.com/activej/activej/tree/master/extra/cloud-memcache), [OLAP Cube](https://github.com/activej/activej/tree/master/extra/cloud-lsmt-cube), [Dataflow](https://github.com/activej/activej/tree/master/extra/cloud-dataflow) ## Quick start Paste this snippet into your terminal... ``` mvn archetype:generate -DarchetypeGroupId=io.activej -DarchetypeArtifactId=archetype-http -DarchetypeVersion=5.5-rc1 ``` ... and open the project in your favorite IDE. Then build the application and run it. Open your browser on [localhost:8080](http://localhost:8080) to see the "Hello World" message. #### Full-featured embedded web application server with Dependency Injection: ```java public final class HttpHelloWorldExample extends HttpServerLauncher { @Provides AsyncServlet servlet() { return request -> HttpResponse.ok200().withPlainText("Hello, World!"); } public static void main(String[] args) throws Exception { Launcher launcher = new HttpHelloWorldExample(); launcher.launch(args); } } ``` Some technical details about the example above: - *The JAR file size is only 1.4 MB. By comparison, the minimum size of a Spring web application is about 17 MB*. - *The cold start time is 0.65 sec.* - *The [ActiveJ Inject](https://activej.io/inject) DI library used is 5.5 times faster than Guice and hundreds of times faster than Spring.* To learn more about ActiveJ, please visit https://activej.io or follow our 5-minute [getting-started guide](https://activej.io/tutorials/getting-started). Examples of using the ActiveJ platform and all ActiveJ libraries can be found in the [`examples`](https://github.com/activej/activej/tree/master/examples) module. **Release notes for ActiveJ can be found [here](https://activej.io/blog)**
135
๐ŸŽจ core business process engine of Alibaba Halo platform, best process engine for trade scenes. | ไธ€ไธช้ซ˜ๆ€ง่ƒฝๆต็จ‹็ผ–ๆŽ’ๅผ•ๆ“Ž
<img src="doc/compileflow-logo.png" alt="compileflow logo" width="20%" align="right" /> # compileflow ๐Ÿ“– See the [๐Ÿ“– ไธญๆ–‡ๆ–‡ๆกฃ](README_CN.md) for the documents in Chinese. [![Github Workflow Build Status](https://img.shields.io/github/actions/workflow/status/alibaba/compileflow/ci.yaml?branch=master&logo=github&logoColor=white)](https://github.com/alibaba/compileflow/actions/workflows/ci.yaml) [![Build Status](https://img.shields.io/appveyor/ci/oldratlee/compileflow/master?logo=appveyor&logoColor=white)](https://ci.appveyor.com/project/oldratlee/compileflow) [![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.compileflow/compileflow?color=2d545e&logo=apache-maven&logoColor=white)](https://search.maven.org/artifact/com.alibaba.compileflow/compileflow) [![GitHub release](https://img.shields.io/github/release/alibaba/compileflow.svg)](https://github.com/alibaba/compileflow/releases) [![Java support](https://img.shields.io/badge/Java-8+-green?logo=OpenJDK&logoColor=white)](https://openjdk.java.net/) [![License](https://img.shields.io/badge/license-Apache%202-4D7A97.svg?logo=Apache&logoColor=white)](https://www.apache.org/licenses/LICENSE-2.0.html) [![GitHub Stars](https://img.shields.io/github/stars/alibaba/compileflow)](https://github.com/alibaba/compileflow/stargazers) [![GitHub Forks](https://img.shields.io/github/forks/alibaba/compileflow)](https://github.com/alibaba/compileflow/fork) [![GitHub issues](https://img.shields.io/github/issues/alibaba/compileflow.svg)](https://github.com/alibaba/compileflow/issues) [![GitHub Contributors](https://img.shields.io/github/contributors/alibaba/compileflow)](https://github.com/alibaba/compileflow/graphs/contributors) ## 1. Introduction Compileflow is a very lightweight, high-performance, integrable and extensible process engine. The Compileflow process engine is an important part of Taobao Business Process Management(TBBPM), which is dedicated to optimizating operations at Alibabaโ€™s Taobao Marketplace. Specifically, Compileflow is designed to focus on pure memory execution and stateless process engines by converting process files to generate, compile and execute java code. Currently, compileflow powers multiple core systems such as Alibaba's e-commerce stores and transactions. Compileflow allows developers to design their own business processes through the process editor, which will visualize complex business logic, and build a bridge between designers and development engineers. ## 2. Design Intention 1.Provide an end-to-end business process solution from design to execution of business development ideas. 2.Offer a variety of process engines to realize the visual global architecture, so that strategy easily translates to visualizations, which lead to enhanced business capabilities, processes and system. 3.Design an efficient execution engine that can support the company's rapid deployment of new services, and capable of streamlining processes that accelerate the development response and interaction speed. ## 3. Features 1.High performance: It is simple and efficient for compiling and executing java code, which is generated by converting process files. 2.Diverse application scenarios: Widely used across Alibaba's mid-platform solutions; supports multiple business scenarios such as shopping guides, transactions. 3.Integrable: Lightweight and concise design makes it extremely easy to integrate into various solutions and business scenarios. 4.Complete plugin support: Compileflow is currently supported by IntelliJ IDEA and Eclipse plugins. Java code can be dynamically generated and previewed in real-time during the process design. What you see is what you get. 5.Process design drawing:Supports exporting to SVG file and unit test code. ## 4. Quick start ### Step1: Download and install IntelliJ IDEA plugin (optional) Plugin download address: https://github.com/alibaba/compileflow-idea-designer *Installation instructions: Please use IntelliJ IDEA local installation method to install. Then restart IntelliJ IDEA to activate.* ### Step2: Import POM file ```xml <dependency> <groupId>com.alibaba.compileflow</groupId> <artifactId>compileflow</artifactId> <version>1.2.0</version> </dependency> ``` Check available version at [search.maven.org](https://search.maven.org/artifact/com.alibaba.compileflow/compileflow). **Note**: Compileflow only supports JDK 1.8 and above. ### Step3: Process design Refer to the KTV demo below to understand the configuration of nodes and attributes and the use of APIs through the demonstration and practice of the demo. Demo description: N number of people go to ktv to sing. Each person sing a song. The usual fee for the ktv session is 30 yuan/person, but if the total price exceeds 300 yuan, they would receive 10% off. But if the group's total fee falls under 300 yuan, they need to pay the full price. #### S3.1 Create a bpm file, as shown below: ![ktv_demo_s1](./doc/image/ktv_demo_s1.png) Note: The path of the bpm file must be consistent with the code. When the process engine executes in the file loading mode, the file will be found according to the code. #### S3.2 Design process through plug-ins or write process xml files directly. #### S3.3 invoke process Write the following unit test: ```java public void testProcessEngine() { final String code = "bpm.ktv.ktvExample"; final Map<String, Object> context = new HashMap<>(); final List<String> pList = new ArrayList<>(); pList.add("wuxiang"); pList.add("xuan"); pList.add("yusu"); context.put("pList", pList); final ProcessEngine<TbbpmModel> processEngine = ProcessEngineFactory.getProcessEngine(); final TbbpmModel tbbpmModel = processEngine.load(code); final OutputStream outputStream = TbbpmModelConverter.getInstance().convertToStream(tbbpmModel); System.out.println(processEngine.getTestCode(code)); processEngine.preCompile(code); System.out.println(processEngine.start(code, context)); } ``` Compileflow was designed to support the Taobao BPM specification. It has made adaptations to be compatible with the BPMN 2.0 specification, but only supports some of BPMN 2.0 elements. If other elements are needed, it can be extended on the original basis. ## 5. More information [DEMO quick start](https://github.com/alibaba/compileflow/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8BDEMO) [Detailed description of the original Taobao BPM specification](https://github.com/alibaba/compileflow/wiki/%E5%8D%8F%E8%AE%AE%E8%AF%A6%E8%A7%A3) ## 6. Welcome to join the compileflow development group Please contact @ไฝ™่‹ @ๅพๅทฅ @ๆขตๅบฆ @ๅ“ฒ่‰ฏ @ๆ— ็›ธ ## Known Users Welcome to register the company name in this issue: https://github.com/alibaba/compileflow/issues/9 ![](doc/image/known_users/alibaba.png) ![](doc/image/known_users/alipay.png) ![](doc/image/known_users/aliyun.png) ![](doc/image/known_users/taobao.png) ![](doc/image/known_users/tmall.png)
136
Provide support to increase developer productivity in Java when using Neo4j. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
null
137
Native Android app for Habitica
# Habitica for Android [Habitica](https://habitica.com) is an open source habit building program which treats your life like a Role Playing Game. Level up as you succeed, lose HP as you fail, earn money to buy weapons and armor. This repository is related to the Android Native Application. It's also on Google Play: <a href="https://play.google.com/store/apps/details?id=com.habitrpg.android.habitica"> <img alt="Get it on Google Play" width="185" src="https://play.google.com/intl/en_us/badges/images/generic/en-play-badge.png" /> </a> Having the application installed is a good way to be notified of new releases. However, clicking "Watch" on this repository will allow GitHub to email you whenever we publish a release. # What's New See the project's Releases page for a list of versions with their changelogs. ##### [View Releases](https://github.com/HabitRPG/habitrpg-android/releases) If you Watch this repository, GitHub will send you an email every time we publish an update. ## Contributing For an introduction to the technologies used and how the software is organized, refer to [Contributing to Habitica](http://habitica.wikia.com/wiki/Contributing_to_Habitica#Coders_.28Web_.26_Mobile.29) - "Coders (Web & Mobile)" section. Thank you very much [to all contributors](https://github.com/HabitRPG/habitrpg-android/graphs/contributors). #### How mobile releases work All major mobile releases are organized by Milestones labeled with the release number. The 'Help Wanted' is added to any issue we feel would be okay for a contributor to work on, so look for that tag first! We do our best to answer any questions contributors may have regarding issues marked with that tag. If an issue does not have the 'Help Wanted' tag, that means staff will handle it when we have the availability. The mobile team consists of one developer and one designer for both Android and iOS. Because of this, we switch back and forth for releases. While we work on one platform, the other will be put on hold. This may result in a wait time for PRs to be reviewed or questions to be answered. Any PRs submitted while we're working on a different platform will be assigned to the next Milestone and we will review it when we come back! Given that our team is stretched pretty thin, it can be difficult for us to take an active role in helping to troubleshoot how to fix issues, but we always do our best to help as much as possible :) With this in mind, when selecting issues to work on it may be best to pick up issues you already have a good idea how to handle and test. Thank you for putting in your time to help make Habitica the best it can be! #### Steps for contributing to this repository: 1. Fork it 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Create new Pull Request * Don't forget to include your Habitica User ID, so that we can count your contribution towards your contributor tier ### Code Style Guidelines We follow the code style guidelines outlined in [Android Code Style Guidelines for Contributors](https://source.android.com/source/code-style.html). You can install our code style scheme to Intellij and/or Android Studio via this shell command: $ ./install-codestyle.sh ## Build Instructions ### Config Files 1. Setup Habitica build config files by simply copying or renaming the example habitica files: `habitica.properties.example` to `habitica.properties` `habitica.resources.example` to `habitica.resources` You also need `google-services.json`. Download it from Firebase in the next step. Note: this is the default production `habitica.properties` file for habitica.com. If you want to use a local Habitica server, please modify the values in the properties file accordingly. 2. Go to https://console.firebase.google.com a. Register/Login to Firebase. (You can use a Google account.) b. Create a new project called Habitica c. Create two apps in the project: `com.habitrpg.android.habitica` and `com.habitrpg.android.habitica.debug` d. Creating each app will generate a `google-services.json` file. Download the `google-services.json` file from the second app and put it in `\Habitica\` and `\wearos\` You can skip the last part of the app creation wizards (where you run the app to verify installation). 3. If using Android Studio, click Sync Project with Gradle Files. Update Android Studio if it asks you to update. Run Habitica.
138
The simple, stupid batch framework for Java
*** <div align="center"> <b><em>Easy Batch</em></b><br> The simple, stupid batch framework for Java&trade; </div> <div align="center"> [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](http://opensource.org/licenses/MIT) [![Build Status](https://github.com/j-easy/easy-batch/actions/workflows/build.yml/badge.svg)](https://github.com/j-easy/easy-batch/actions) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.jeasy/easy-batch-core/badge.svg?style=flat)](http://search.maven.org/#artifactdetails|org.jeasy|easy-batch-core|7.0.2|) [![Javadoc](https://www.javadoc.io/badge/org.jeasy/easy-batch-core.svg)](http://www.javadoc.io/doc/org.jeasy/easy-batch-core) [![Project status](https://img.shields.io/badge/Project%20status-Maintenance-orange.svg)](https://img.shields.io/badge/Project%20status-Maintenance-orange.svg) </div> *** ## Project status As of November 18, 2020, Easy Batch is in maintenance mode. This means only bug fixes will be addressed from now on. Version 7.0.x is the only supported version. ## Latest news * 2020-03-14: [Version 7.0.2 is out](https://github.com/j-easy/easy-batch/releases) with a minor bug fix and a number of dependency updates. # What is Easy Batch? Easy Batch is a framework that aims at simplifying batch processing with Java. It was **specifically** designed for simple, single-task ETL jobs. Writing batch applications requires a **lot** of boilerplate code: reading, writing, filtering, parsing and validating data, logging, reporting to name a few.. The idea is to free you from these tedious tasks and let you focus on your batch application's logic. # How does it work? Easy Batch jobs are simple processing pipelines. Records are read in sequence from a data source, processed in pipeline and written in batches to a data sink: ![batch processing](https://raw.githubusercontent.com/wiki/j-easy/easy-batch/images/batch-processing.png) The framework provides the `Record` and `Batch` APIs to abstract data format and process records in a consistent way regardless of the data source/sink type. Let's see a quick example. Suppose you have the following `tweets.csv` file: ``` id,user,message 1,foo,hello 2,bar,@foo hi! ``` and you want to transform these tweets to XML format. Here is how you can do that with Easy Batch: ```java Path inputFile = Paths.get("tweets.csv"); Path outputFile = Paths.get("tweets.xml"); Job job = new JobBuilder<String, String>() .reader(new FlatFileRecordReader(inputFile)) .filter(new HeaderRecordFilter<>()) .mapper(new DelimitedRecordMapper<>(Tweet.class, "id", "user", "message")) .marshaller(new XmlRecordMarshaller<>(Tweet.class)) .writer(new FileRecordWriter(outputFile)) .batchSize(10) .build(); JobExecutor jobExecutor = new JobExecutor(); JobReport report = jobExecutor.execute(job); jobExecutor.shutdown(); ``` This example creates a job that: * reads records one by one from the input file `tweets.csv` * filters the header record * maps each record to an instance of the `Tweet` bean * marshals the tweet to XML format * and finally writes XML records in batches of 10 to the output file `tweets.xml` At the end of execution, you get a report with statistics and metrics about the job run (Execution time, number of errors, etc). All the boilerplate code of resources I/O, iterating through the data source, filtering and parsing records, mapping data to the domain object `Tweet`, writing output and reporting is handled by Easy Batch. Your code becomes declarative, intuitive, easy to read, understand, test and maintain. ## Quick start Add the following dependency to your project and you are ready to go: ```xml <dependency> <groupId>org.jeasy</groupId> <artifactId>easy-batch-core</artifactId> <version>7.0.2</version> </dependency> ``` You can also generate a quick start project with the following command: ``` $>mvn archetype:generate \ -DarchetypeGroupId=org.jeasy \ -DarchetypeArtifactId=easy-batch-archetype \ -DarchetypeVersion=7.0.2 ``` For more details, please check the [Getting started](https://github.com/j-easy/easy-batch/wiki/getting-started) guide. ## Presentations, articles & blog posts - :movie_camera: [Introduction to Easy Batch: the simple, stupid batch processing framework for Java](https://speakerdeck.com/benas/easy-batch) - :newspaper: [First batch job on Podcastpedia.org using Easy Batch](http://www.codingpedia.org/ama/first-batch-job-on-podcastpedia-org-with-easybatch/) - :newspaper: [EasyBatch, les batchs en JAVA tout simplement (in french)](https://blog.sodifrance.fr/easybatch-les-batchs-en-java-tout-simplement/) - :memo: [Easy Batch vs Spring Batch: Feature comparison](https://github.com/benas/easy-batch-vs-spring-batch/issues/1) - :memo: [Easy Batch vs Spring Batch: Performance comparison](https://github.com/benas/easy-batch-vs-spring-batch/issues/2) ## Current versions #### Stable: The current stable version is [v7.0.2](http://search.maven.org/#artifactdetails|org.jeasy|easy-batch-core|7.0.2|) | [documentation](https://github.com/j-easy/easy-batch/wiki) | [tutorials](https://github.com/j-easy/easy-batch/tree/easy-batch-7.0.2/easy-batch-tutorials) | [javadoc](http://javadoc.io/doc/org.jeasy/easy-batch-core/7.0.2) #### Development: The current development version is 7.0.3-SNAPSHOT: [![Build Status](https://github.com/j-easy/easy-batch/workflows/Java%20CI/badge.svg)](https://github.com/j-easy/easy-batch/actions) If you want to import a snapshot version, please check the [Getting started](https://github.com/j-easy/easy-batch/wiki/getting-started#use-a-snapshot-version) guide. ## Contribution You are welcome to contribute to the project with pull requests on GitHub. Please note that Easy Batch is in [maintenance mode](https://github.com/j-easy/easy-batch#project-status), which means only pull requests for bug fixes will be considered. If you believe you found a bug or have any question, please use the [issue tracker](https://github.com/j-easy/easy-batch/issues). ## Awesome contributors * [ammachado](https://github.com/ammachado) * [anandhi](https://github.com/anandhi) * [AussieGuy0](https://github.com/AussieGuy0) * [AymanDF](https://github.com/AymanDF) * [chsfleury](https://github.com/chsfleury) * [chellan](https://github.com/chellan) * [DanieleS82](https://github.com/DanieleS82) * [gs-spadmanabhan](https://github.com/gs-spadmanabhan) * [imranrajjad](https://github.com/imranrajjad) * [ipropper](https://github.com/ipropper) * [IvanAtanasov89](https://github.com/IvanAtanasov89) * [jawher](https://github.com/jawher) * [jlcanibe](https://github.com/jlcanibe) * [MALPI](https://github.com/MALPI) * [marcosvpcortes](https://github.com/marcosvpcortes) * [natlantisprog](https://github.com/natlantisprog) * [nicopatch](https://github.com/nicopatch) * [nihed](https://github.com/nihed) * [PascalSchumacher](https://github.com/PascalSchumacher) * [seseso](https://github.com/seseso) * [Toilal](https://github.com/Toilal) * [xenji](https://github.com/xenji) * [verdi8](https://github.com/verdi8) Thank you all for your contributions! ## Who is using Easy Batch? Easy Batch has been successfully used in production in a number of companies which I ([@benas](https://github.com/benas)) am not allowed to mention. That said, there are some companies which publicly mention that they use Easy Batch: * [Splunk](https://docs.splunk.com/Documentation/DBX/3.2.0/ReleaseNotes/easybatch) * [DeepData](https://deepdata-ltd.github.io/tenderbase/#/ted-xml-importer?id=implementation) You can also find some feedback from the community about the project in the [Testimonials](http://www.jeasy.org/#testimonials) section. ## Credits ![YourKit Java Profiler](https://www.yourkit.com/images/yklogo.png) Many thanks to [YourKit, LLC](https://www.yourkit.com/) for providing a free license of [YourKit Java Profiler](https://www.yourkit.com/java/profiler/index.jsp) to support the development of Easy Batch. ## License Easy Batch is released under the terms of the [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](http://opensource.org/licenses/MIT). ``` The MIT License (MIT) Copyright (c) 2021 Mahmoud Ben Hassine ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ```
139
Library to diff and merge Java objects with ease
## Introduction `java-object-diff` is a simple, yet powerful library to find differences between Java objects. It takes two objects and generates a tree structure that represents any differences between the objects and their children. This tree can then be traversed to extract more information or apply changes to the underlying data structures. [![Build Status](https://travis-ci.org/SQiShER/java-object-diff.svg?branch=master)](https://travis-ci.org/SQiShER/java-object-diff) [![Coverage Status](https://coveralls.io/repos/SQiShER/java-object-diff/badge.svg?branch=master&service=github)](https://coveralls.io/github/SQiShER/java-object-diff?branch=master) [![Download](https://api.bintray.com/packages/sqisher/maven/java-object-diff/images/download.svg)](https://bintray.com/sqisher/maven/java-object-diff/_latestVersion) [![Documentation Status](https://readthedocs.org/projects/java-object-diff/badge/?version=latest)](https://readthedocs.org/projects/java-object-diff/?badge=latest) ## Features * Works out-of-the-box with with almost any kind of object and arbitrarily deep nesting * Finds the differences between two objects * Returns the differences in shape of an easily traversable tree structure * Tells you everything there is to know about the detected changes * Provides read and write access to the underlying objects, allowing you not only to extract the changed values but even to apply the diff as a patch * Requires no changes to your existing classes (in most cases) * Provides a very flexible configuration API to tailor everything to your needs * Tiny, straightforward, yet very powerful API * Detects and handles circular references in the object graph * No runtime dependencies except for [SLF4J](http://www.slf4j.org/) * Compatible with Java 1.5 and above ## Support this Project If you like this project, there are a few things you can do to show your support: * [**Follow me** on Twitter (@SQiShER)](https://twitter.com/SQiShER) * [**Surprise me** with something from my Amazon Wishlist](http://www.amazon.de/registry/wishlist/2JFW27V71CBGM) * [**Contribute** code, documentation, ideas, or insights into your use-case](https://github.com/SQiShER/java-object-diff/blob/master/CONTRIBUTING.md) * Star this repository (stars make me very happy!) * Talk about it, write about it, recommend it to others But most importantly: **don't ever hesitate to ask me for help**, if you're having trouble getting this library to work. The only way to make it better is by hearing about your use-cases and pushing the limits! ## Getting Started To learn how to use **Java Object Diff** have a look at the [Getting Started Guide](http://java-object-diff.readthedocs.org/en/latest/getting-started/). ### Using with Maven ```xml <dependency> <groupId>de.danielbechler</groupId> <artifactId>java-object-diff</artifactId> <version>0.95</version> </dependency> ``` ### Using with Gradle ```groovy compile 'de.danielbechler:java-object-diff:0.95' ``` ## Documentation The documentation can be found over at [ReadTheDocs](http://java-object-diff.readthedocs.org/en/latest/). ## Caveats * Introspection of values other than primitives and collection types is curently done via standard JavaBean introspection, which requires your objects to provide getters and setters for their properties. However, you don't need to provide setters, if you don't need write access to the properties (e.g. you don't want to apply the diff as a patch.) If this does not work for you, don't worry: you can easily write your own introspectors and just plug them in via configuration API. * Ordered lists are currently not properly supported (they are just treated as Sets). While this is something I definitely want to add before version `1.0` comes out, its a pretty big task and will be very time consuming. So far there have been quite a few people who needed this feature, but not as many as I imagined. So your call to action: if you need to diff and/or merge collection types like `ArrayList`, perhaps even with multiple occurence of the same value, please let me know. The more I'm aware of the demand and about the use-cases, the more likely it is, that I start working on it. ## Why would you need this? Sometimes you need to figure out, how one version of an object differs from another one. One of the simplest solutions that'll cross your mind is most certainly to use reflection to scan the object for fields or getters and use them to compare the values of the different object instances. In many cases this is a perfectly valid strategy and the way to go. After all, we want to keep things simple, don't we? However, there are some cases that can increase the complexity dramatically. What if you need to find differences in collections or maps? What if you have to deal with nested objects that also need to be compared on a per-property basis? Or even worse: what if you need to merge such objects? You suddenly realize that you need to scan the objects recursively, figure out which collection items have been added, removed or changed; find a way to return your results in a way that allows you to easily access the information you are looking for and provide accessors to apply changes. While all this isn't exactly rocket science, it is complex enough to add quite a lot of extra code to your project. Code that needs to be tested and maintained. Since the best code is the code you didn't write, this library aims to help you with all things related to diffing and merging of Java objects by providing a robust foundation and a simple, yet powerful API. This library will hide all the complexities of deep object comparison behind one line of code: ```java DiffNode root = ObjectDifferBuilder.buildDefault().compare(workingObject, baseObject); ``` This generates a tree structure of the given object type and lets you traverse its nodes via visitors. Each node represents one property (or collection item) of the underlying object and tells you exactly if and how the value differs from the base version. It also provides accessors to read, write and remove the value from or to any given instance. This way, all you need to worry about is **how to treat** changes and **not how to find** them. This library has been battle-tested in a rather big project of mine, where I use it to generate **activity streams**, resolve database **update conflics**, display **change logs** and limit the scope of entity updates to only a **subset of properties**, based on the context or user permissions. It didn't let me down so far and I hope it can help you too! ## Contribute You discovered a bug or have an idea for a new feature? Great, why don't you send me a [Pull Request](https://help.github.com/articles/using-pull-requests) so everyone can benefit from it? To help you getting started, [here](https://github.com/SQiShER/java-object-diff/blob/master/CONTRIBUTING.md) is a brief guide with everyting you need to know to get involved! --- Thanks to JetBrains for supporting this project with a free open source license for their amazing IDE **IntelliJ IDEA**. [![IntelliJ IDEA](https://www.jetbrains.com/idea/docs/logo_intellij_idea.png)](https://www.jetbrains.com/idea/)
140
An extremely fast implementation of Aho Corasick algorithm based on Double Array Trie.
AhoCorasickDoubleArrayTrie ============ [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.hankcs/aho-corasick-double-array-trie/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.hankcs/aho-corasick-double-array-trie/) [![GitHub release](https://img.shields.io/github/release/hankcs/AhoCorasickDoubleArrayTrie.svg)](https://github.com/hankcs/AhoCorasickDoubleArrayTrie/releases) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) An extremely fast implementation of Aho Corasick algorithm based on Double Array Trie structure. Its speed is 5 to 9 times of naive implementations, perhaps it's the fastest implementation so far ;-) Introduction ------------ You may heard that Aho-Corasick algorithm is fast for parsing text with a huge dictionary, for example: * looking for certain words in texts in order to URL link or emphasize them * adding semantics to plain text * checking against a dictionary to see if syntactic errors were made But most implementation use a `TreeMap<Character, State>` to store the *goto* structure, which costs `O(lg(t))` time, `t` is the largest amount of a word's common prefixes. The final complexity is `O(n * lg(t))`, absolutely `t > 2`, so `n * lg(t) > n `. The others used a `HashMap`, which wasted too much memory, and still remained slowly. I improved it by replacing the `XXXMap` to a Double Array Trie, whose time complexity is just `O(1)`, thus we get a total complexity of exactly `O(n)`, and take a perfect balance of time and memory. Yes, its speed is not related to the length or language or common prefix of the words of a dictionary. This implementation has been widely used in my [HanLP: Han Language Processing](https://github.com/hankcs/HanLP) package. I hope it can serve as a common data structure library in projects handling text or NLP task. Dependency ---------- Include this dependency in your POM. Be sure to check for the latest version in Maven Central. ```xml <dependency> <groupId>com.hankcs</groupId> <artifactId>aho-corasick-double-array-trie</artifactId> <version>1.2.3</version> </dependency> ``` or include this dependency in your build.gradle.kts ```kotlin implementation("com.hankcs:aho-corasick-double-array-trie:1.2.2") ``` Usage ----- Setting up the `AhoCorasickDoubleArrayTrie` is a piece of cake: ```java // Collect test data set TreeMap<String, String> map = new TreeMap<String, String>(); String[] keyArray = new String[] { "hers", "his", "she", "he" }; for (String key : keyArray) { map.put(key, key); } // Build an AhoCorasickDoubleArrayTrie AhoCorasickDoubleArrayTrie<String> acdat = new AhoCorasickDoubleArrayTrie<String>(); acdat.build(map); // Test it final String text = "uhers"; List<AhoCorasickDoubleArrayTrie.Hit<String>> wordList = acdat.parseText(text); ``` Of course, there remains many useful methods to be discovered, feel free to try: * Use a `Map<String, SomeObject>` to assign a `SomeObject` as value to a keyword. * Store the `AhoCorasickDoubleArrayTrie` to disk by calling `save` method. * Restore the `AhoCorasickDoubleArrayTrie` from disk by calling `load` method. * Use it in concurrent code. `AhoCorasickDoubleArrayTrie` is thread safe after `build` method In other situations you probably do not need a huge wordList, then please try this: ```java acdat.parseText(text, new AhoCorasickDoubleArrayTrie.IHit<String>() { @Override public void hit(int begin, int end, String value) { System.out.printf("[%d:%d]=%s\n", begin, end, value); } }); ``` or a lambda function ``` acdat.parseText(text, (begin, end, value) -> { System.out.printf("[%d:%d]=%s\n", begin, end, value); }); ``` Comparison ----- I compared my AhoCorasickDoubleArrayTrie with robert-bor's aho-corasick, ACDAT represents for AhoCorasickDoubleArrayTrie and Naive represents for aho-corasick, the result is : ``` Parsing English document which contains 3409283 characters, with a dictionary of 127142 words. Naive ACDAT time 607 102 char/s 5616611.20 33424343.14 rate 1.00 5.95 =========================================================================== Parsing Chinese document which contains 1290573 characters, with a dictionary of 146047 words. Naive ACDAT time 319 35 char/s 2609156.74 23780600.00 rate 1.00 9.11 =========================================================================== ``` In English test, AhoCorasickDoubleArrayTrie is 5 times faster. When it comes to Chinese, AhoCorasickDoubleArrayTrie is 9 times faster. This test is conducted under i7 2.0GHz, -Xms512m -Xmx512m -Xmn256m. Feel free to re-run this test in TestAhoCorasickDoubleArrayTrie, the test data is ready for you. Thanks ----- This project is inspired by [aho-corasick](https://github.com/robert-bor/aho-corasick) and [darts-clone-java](https://github.com/hiroshi-manabe/darts-clone-java). Many thanks! License ------- 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.
141
Generate types and converters from JSON, Schema, and GraphQL
![](https://raw.githubusercontent.com/quicktype/quicktype/master/media/quicktype-logo.svg?sanitize=true) [![npm version](https://badge.fury.io/js/quicktype.svg)](https://badge.fury.io/js/quicktype) ![Build status](https://github.com/quicktype/quicktype/actions/workflows/master.yaml/badge.svg) `quicktype` generates strongly-typed models and serializers from JSON, JSON Schema, TypeScript, and [GraphQL queries](https://blog.quicktype.io/graphql-with-quicktype/), making it a breeze to work with JSON type-safely in many programming languages. - [Try `quicktype` in your browser](https://app.quicktype.io). - Read ['A first look at quicktype'](http://blog.quicktype.io/first-look/) for more introduction. - If you have any questions, check out the [FAQ](FAQ.md) first. ### Supported Inputs | JSON | JSON API URLs | [JSON Schema](https://app.quicktype.io/#s=coordinate) | | ---- | ------------- | ----------------------------------------------------- | | TypeScript | GraphQL queries | | ---------- | --------------- | ### Target Languages | [Ruby](https://app.quicktype.io/#l=ruby) | [JavaScript](https://app.quicktype.io/#l=js) | [Flow](https://app.quicktype.io/#l=flow) | [Rust](https://app.quicktype.io/#l=rust) | [Kotlin](https://app.quicktype.io/#l=kotlin) | | ---------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------- | -------------------------------------------- | | [Dart](https://app.quicktype.io/#l=dart) | [Python](https://app.quicktype.io/#l=python) | [C#](https://app.quicktype.io/#l=cs) | [Go](https://app.quicktype.io/#l=go) | [C++](https://app.quicktype.io/#l=cpp) | | ---------------------------------------- | -------------------------------------------- | ------------------------------------ | ------------------------------------ | -------------------------------------- | | [Java](https://app.quicktype.io/#l=java) | [TypeScript](https://app.quicktype.io/#l=ts) | [Swift](https://app.quicktype.io/#l=swift) | [Objective-C](https://app.quicktype.io/#l=objc) | [Elm](https://app.quicktype.io/#l=elm) | | ---------------------------------------- | -------------------------------------------- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- | | [JSON Schema](https://app.quicktype.io/#l=schema) | [Pike](https://app.quicktype.io/#l=pike) | [Prop-Types](https://app.quicktype.io/#l=javascript-prop-types) | [Haskell](https://app.quicktype.io/#l=haskell) | | | ------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | --- | _Missing your favorite language? Please implement it!_ ## Installation There are many ways to use `quicktype`. [app.quicktype.io](https://app.quicktype.io) is the most powerful and complete UI. The web app also works offline and doesn't send your sample data over the Internet, so paste away! For the best CLI, we recommend installing `quicktype` globally via `npm`: ```bash npm install -g quicktype ``` Other options: - [Homebrew](http://formulae.brew.sh/formula/quicktype) _(infrequently updated)_ - [Xcode extension](https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12)\* - [VSCode extension](https://marketplace.visualstudio.com/items/quicktype.quicktype)\* - [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs)\* <small>\* limited functionality</small> ## Using `quicktype` ```bash # Run quicktype without arguments for help and options quicktype # quicktype a simple JSON object in C# echo '{ "name": "David" }' | quicktype -l csharp # quicktype a top-level array and save as Go source echo '[1, 2, 3]' | quicktype -o ints.go # quicktype a sample JSON file in Swift quicktype person.json -o Person.swift # A verbose way to do the same thing quicktype \ --src person.json \ --src-lang json \ --lang swift \ --top-level Person \ --out Person.swift # quicktype a directory of samples as a C++ program # Suppose ./blockchain is a directory with files: # latest-block.json transactions.json marketcap.json quicktype ./blockchain -o blockchain-api.cpp # quicktype a live JSON API as a Java program quicktype https://api.somewhere.com/data -o Data.java ``` ### Generating code from JSON schema The recommended way to use `quicktype` is to generate a JSON schema from sample data, review and edit the schema, commit the schema to your project repo, then generate code from the schema as part of your build process: ```bash # First, infer a JSON schema from a sample. quicktype pokedex.json -l schema -o schema.json # Review the schema, make changes, # and commit it to your project repo. # Finally, generate model code from schema in your # build process for whatever languages you need: quicktype -s schema schema.json -o src/ios/models.swift quicktype -s schema schema.json -o src/android/Models.java quicktype -s schema schema.json -o src/nodejs/Models.ts # All of these models will serialize to and from the same # JSON, so different programs in your stack can communicate # seamlessly. ``` ### Generating code from TypeScript (Experimental) You can achieve a similar result by writing or generating a [TypeScript](http://www.typescriptlang.org/) file, then quicktyping it. TypeScript is a typed superset of JavaScript with simple, succinct syntax for defining types: ```typescript interface Person { name: string; nickname?: string; // an optional property luckyNumber: number; } ``` You can use TypeScript just like JSON schema was used in the last example: ```bash # First, infer a TypeScript file from a sample (or just write one!) quicktype pokedex.json -o pokedex.ts --just-types # Review the TypeScript, make changes, etc. quicktype pokedex.ts -o src/ios/models.swift ``` ### Calling `quicktype` from JavaScript You can use `quicktype` as a JavaScript function within `node` or browsers. First add the `quicktype-core` package: ```bash $ npm install quicktype-core ``` In general, first you create an `InputData` value with one or more JSON samples, JSON schemas, TypeScript sources, or other supported input types. Then you call `quicktype`, passing that `InputData` value and any options you want. ```javascript import { quicktype, InputData, jsonInputForTargetLanguage, JSONSchemaInput, FetchingJSONSchemaStore } from "quicktype-core"; async function quicktypeJSON(targetLanguage, typeName, jsonString) { const jsonInput = jsonInputForTargetLanguage(targetLanguage); // We could add multiple samples for the same desired // type, or many sources for other types. Here we're // just making one type from one piece of sample JSON. await jsonInput.addSource({ name: typeName, samples: [jsonString] }); const inputData = new InputData(); inputData.addInput(jsonInput); return await quicktype({ inputData, lang: targetLanguage }); } async function quicktypeJSONSchema(targetLanguage, typeName, jsonSchemaString) { const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore()); // We could add multiple schemas for multiple types, // but here we're just making one type from JSON schema. await schemaInput.addSource({ name: typeName, schema: jsonSchemaString }); const inputData = new InputData(); inputData.addInput(schemaInput); return await quicktype({ inputData, lang: targetLanguage }); } async function main() { const { lines: swiftPerson } = await quicktypeJSON("swift", "Person", jsonString); console.log(swiftPerson.join("\n")); const { lines: pythonPerson } = await quicktypeJSONSchema("python", "Person", jsonSchemaString); console.log(pythonPerson.join("\n")); } main(); ``` The argument to `quicktype` is a complex object with many optional properties. [Explore its definition](https://github.com/quicktype/quicktype/blob/master/src/quicktype-core/Run.ts#L119) to understand what options are allowed. ## Contributing `quicktype` is [Open Source](LICENSE) and we love contributors! In fact, we have a [list of issues](https://github.com/quicktype/quicktype/issues?utf8=โœ“&q=is%3Aissue+is%3Aopen+label%3Ahelp-wanted) that are low-priority for us, but for which we'd happily accept contributions. Support for new target languages is also strongly desired. If you'd like to contribute, need help with anything at all, or would just like to talk things over, come [join us on Slack](http://slack.quicktype.io/). ### Setup, Build, Run `quicktype` is implemented in TypeScript and requires `nodejs` and `npm` to build and run. First, install `typescript` globally via `npm`: Clone this repo and do: #### macOS / Linux ```bash nvm use npm install script/quicktype # rebuild (slow) and run (fast) ``` #### Windows ```bash npm install --ignore-scripts # Install dependencies npm install -g typescript # Install typescript globally tsc --project src/cli # Rebuild node dist\cli\index.js # Run ``` ### Edit Install [Visual Studio Code](https://code.visualstudio.com/), open this workspace, and install the recommended extensions: ```bash code . # opens in VS Code ``` ### Live-reloading for quick feedback When working on an output language, you'll want to view generated output as you edit. Use `npm start` to watch for changes and recompile and rerun `quicktype` for live feedback. For example, if you're developing a new renderer for `fortran`, you could use the following command to rebuild and reinvoke `quicktype` as you implement your renderer: ```bash npm start -- "--lang fortran pokedex.json" ``` The command in quotes is passed to `quicktype`, so you can render local `.json` files, URLs, or add other options. ### Test ```bash # Run full test suite npm run test # Test a specific language (see test/languages.ts) FIXTURE=golang npm test # Test a single sample or directory FIXTURE=swift npm test -- pokedex.json FIXTURE=swift npm test -- test/inputs/json/samples ```
142
A library for handling Problems in Spring Web MVC
# Problems for Spring MVC and Spring WebFlux [![Stability: Sustained](https://masterminds.github.io/stability/sustained.svg)](https://masterminds.github.io/stability/sustained.html) ![Build Status](https://github.com/zalando/problem-spring-web/workflows/build/badge.svg) [![Coverage Status](https://img.shields.io/coveralls/zalando/problem-spring-web/main.svg)](https://coveralls.io/r/zalando/problem-spring-web) [![Code Quality](https://img.shields.io/codacy/grade/0236149bf46749b1a582f9fbbde2a4eb/main.svg)](https://www.codacy.com/app/whiskeysierra/problem-spring-web) [![Release](https://img.shields.io/github/release/zalando/problem-spring-web.svg)](https://github.com/zalando/problem-spring-web/releases) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/zalando/problem-spring-web/main/LICENSE) *Problem Spring Web* is a set of libraries that makes it easy to produce [`application/problem+json`](http://tools.ietf.org/html/rfc7807) responses from a Spring application. It fills a niche, in that it connects the [Problem library](https://github.com/zalando/problem) and either [Spring Web MVC's exception handling](https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#using-controlleradvice-classes) or [Spring WebFlux's exception handling](https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-ann-controller-exceptions) so that they work seamlessly together, while requiring minimal additional developer effort. In doing so, it aims to perform a small but repetitive task โ€” once and for all. The way this library works is based on what we call *advice traits*. An advice trait is a small, reusable `@ExceptionHandler` implemented as a [default method](https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html) placed in a single method interface. Those advice traits can be combined freely and don't require to use a common base class for your [`@ControllerAdvice`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html). :mag_right: Please check out [Baeldung: A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) for a detailed introduction! ## Features - lets you choose traits *ร  la carte* - favors composition over inheritance - ~20 useful advice traits built in - Spring MVC and Spring WebFlux support - Spring Security support - customizable processing ## Dependencies - Java 8 - Any build tool using Maven Central, or direct download - Servlet Container for [problem-spring-web](problem-spring-web) or - Reactive, non-blocking runtime for [problem-spring-webflux](problem-spring-webflux) - Spring 5 - Spring 4 (or Spring Boot 1.5) users may use version [0.23.0](https://github.com/zalando/problem-spring-web/releases/tag/0.23.0) - Spring Security 5 (optional) - Failsafe 2.3.3 (optional) ## Installation and Configuration - [Spring Web MVC](problem-spring-web) - [Spring WebFlux](problem-spring-webflux) ## Customization The problem handling process provided by `AdviceTrait` is built in a way that allows for customization whenever the need arises. All of the following aspects (and more) can be customized by implementing the appropriate advice trait interface: | Aspect | Method(s) | Default | |---------------------|-----------------------------|-------------------------------------------------------------------------------------------------------| | Creation | `AdviceTrait.create(..)` | | | Logging | `AdviceTrait.log(..)` | 4xx as `WARN`, 5xx as `ERROR` including stack trace | | Content Negotiation | `AdviceTrait.negotiate(..)` | `application/json`, `application/*+json`, `application/problem+json` and `application/x.problem+json` | | Fallback | `AdviceTrait.fallback(..)` | `application/problem+json` | | Post-Processing | `AdviceTrait.process(..)` | n/a | The following example customizes the `MissingServletRequestParameterAdviceTrait` by adding a `parameter` extension field to the `Problem`: ```java @ControllerAdvice public class MissingRequestParameterExceptionHandler implements MissingServletRequestParameterAdviceTrait { @Override public ProblemBuilder prepare(Throwable throwable, StatusType status, URI type) { var exception = (MissingServletRequestParameterException) throwable; return Problem.builder() .withTitle(status.getReasonPhrase()) .withStatus(status) .withDetail(exception.getMessage()) .with("parameter", exception.getParameterName()); } } ``` ## Usage Assuming there is a controller like this: ```java @RestController @RequestMapping("/products") class ProductsResource { @RequestMapping(method = GET, value = "/{productId}", produces = APPLICATION_JSON_VALUE) public Product getProduct(String productId) { // TODO implement return null; } @RequestMapping(method = PUT, value = "/{productId}", consumes = APPLICATION_JSON_VALUE) public Product updateProduct(String productId, Product product) { // TODO implement throw new UnsupportedOperationException(); } } ``` The following HTTP requests will produce the corresponding response respectively: ```http GET /products/123 HTTP/1.1 Accept: application/xml ``` ```http HTTP/1.1 406 Not Acceptable Content-Type: application/problem+json { "title": "Not Acceptable", "status": 406, "detail": "Could not find acceptable representation" } ``` ```http POST /products/123 HTTP/1.1 Content-Type: application/json {} ``` ```http HTTP/1.1 405 Method Not Allowed Allow: GET Content-Type: application/problem+json { "title": "Method Not Allowed", "status": 405, "detail": "POST not supported" } ``` ### Stack traces and causal chains **Before you continue**, please read the section about [*Stack traces and causal chains*](https://github.com/zalando/problem#stack-traces-and-causal-chains) in [zalando/problem](https://github.com/zalando/problem). In case you want to enable stack traces, please configure your `ProblemModule` as follows: ```java ObjectMapper mapper = new ObjectMapper() .registerModule(new ProblemModule().withStackTraces()); ``` Causal chains of problems are **disabled by default**, but can be overridden if desired: ```java @ControllerAdvice class ExceptionHandling implements ProblemHandling { @Override public boolean isCausalChainsEnabled() { return true; } } ``` **Note** Since you have full access to the application context at that point, you can externalize the configuration to your `application.yml` and even decide to reuse Spring's `server.error.include-stacktrace` property. Enabling both features, causal chains and stacktraces, will yield: ```yaml { "title": "Internal Server Error", "status": 500, "detail": "Illegal State", "stacktrace": [ "org.example.ExampleRestController.newIllegalState(ExampleRestController.java:96)", "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:91)" ], "cause": { "title": "Internal Server Error", "status": 500, "detail": "Illegal Argument", "stacktrace": [ "org.example.ExampleRestController.newIllegalArgument(ExampleRestController.java:100)", "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:88)" ], "cause": { "title": "Internal Server Error", "status": 500, "detail": "Null Pointer", "stacktrace": [ "org.example.ExampleRestController.newNullPointer(ExampleRestController.java:104)", "org.example.ExampleRestController.nestedThrowable(ExampleRestController.java:86)", "sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", "sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)", "sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)", "java.lang.reflect.Method.invoke(Method.java:483)", "org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)", "org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)", "org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)", "org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)", "org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)", "org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)", "org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)", "org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)", "org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)", "org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)", "org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)", "org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)", "org.junit.runners.ParentRunner.run(ParentRunner.java:363)", "org.junit.runner.JUnitCore.run(JUnitCore.java:137)", "com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)", "com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)", "com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)" ] } } } ``` ## Known Issues Spring allows to restrict the scope of a `@ControllerAdvice` to a certain subset of controllers: ```java @ControllerAdvice(assignableTypes = ExampleController.class) public final class ExceptionHandling implements ProblemHandling ``` By doing this you'll loose the capability to handle certain types of exceptions namely: - `HttpRequestMethodNotSupportedException` - `HttpMediaTypeNotAcceptableException` - `HttpMediaTypeNotSupportedException` - `NoHandlerFoundException` We inherit this restriction from Spring and therefore recommend to use an unrestricted `@ControllerAdvice`. ## Getting Help If you have questions, concerns, bug reports, etc., please file an issue in this repository's [Issue Tracker](../../issues). ## Getting Involved/Contributing To contribute, simply make a pull request and add a brief description (1-2 sentences) of your addition or change. For more details, check the [contribution guidelines](.github/CONTRIBUTING.md). ## Credits and references - [Baeldung: A Guide to the Problem Spring Web Library](https://www.baeldung.com/problem-spring-web) - [Problem Details for HTTP APIs](http://tools.ietf.org/html/rfc7807) - [Problem library](https://github.com/zalando/problem) - [Exception Handling in Spring MVC](https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#using-controlleradvice-classes)
143
An open source data gateway
[![Maven Central](https://img.shields.io/maven-central/v/io.stargate/stargate.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/io.stargate/stargate/) # Stargate An open source data API gateway. Stargate is a data gateway deployed between client applications and a Cassandra database. For developers, it makes it easy to use Cassandra for any application workload by adding plugin support for new APIs, data types, and access methods - even secondary database models. It's built with extensibility as a first-class citizen to enable rapid innovation. For operators, Stargate introduces microservice architecture, allowing independent deployment and scale of storage nodes, API Service nodes, and coordinator nodes in Cassandra clusters. - For quick instructions on how to bring up Stargate on your desktop using Docker, check out the [Docker compose](docker-compose/README.md) instructions. - If you wish to deploy in Kubernetes, there is also a [Helm chart](helm/README.md) you can use to install Stargate alongside an existing Cassandra cluster, or visit the [K8ssandra](https://k8ssandra.io) project for a distribution that packages Cassandra, Stargate, and additional tooling. - For more information about how to deploy and use Stargate, visit [stargate.io](https://stargate.io/) - To learn how to participate in our community, visit our [community page](https://stargate.io/community) - To set up and use a Stargate development environment, visit the [dev guide](DEV_GUIDE.md) ## Contents - [Introduction](#introduction) - [Repositories](#repositories) - [Issue Management](#issue-management) ## Introduction We created Stargate because we got tired of using different databases and different APIs depending on the work that we were trying to get done. With "read the manual" fatigue and lengthy selection processes wearing on us every time we started a new project, we thought - *why not create a framework that can serve many APIs for a range of workloads?* This project enables customization of all aspects of data access and has modules for authentication, APIs, request handling / routing, and persistence backends. The current form is specific to Apache Cassandra (C*) compatible backends. As shown in the figure below, Stargate is often deployed behind a load balancer or proxy and exposes multiple endpoints to client applications, including HTTP APIs, gRPC, and the Cassandra Query Language (CQL). Stargate sits in front of a Cassandra cluster which is used as the storage backend. ![image](assets/stargate-arch-high-level.png#center) Stargate consists of the following components, which we introduce briefly here with links to the corresponding modules in this monorepo. ### API Services These are independently scalable microservices which various APIs, typically HTTP based. These modules can be found under the [apis](apis) directory: - [sgv2-restapi](apis/sgv2-restapi): API implementation for exposing Cassandra data over REST - [sgv2-graphqlapi](apis/sgv2-graphqlapi): API implementation for exposing Cassandra data over GraphQL - [sgv2-docsapi](apis/sgv2-docsapi): API implementation for exposing Cassandra data over a Document API Each API Service contains its own integration test suite that tests it against the coordinator node and supported Cassandra backends. There is also a [sgv2-quarkus-common](apis/sgv2-quarkus-common) module containing utilities that may be used by all Java/Quarkus based API services. **Warning:** Support for Cassandra 3.11 is considered deprecated and will be removed in the Stargate v3 release: [details](https://github.com/stargate/stargate/discussions/2242). - **Authentication Services**: Responsible for authentication to Stargate ### Coordinator Node Coordinator nodes participate as non-data storing nodes in the backing Cassandra cluster, which enables them to read and write data more efficiently. Stargate Coordinator nodes can also be scaled independently. Coordinator nodes expose gRPC and CQL interfaces for fast access by client applications. The following are the key modules comprising the coordinator and its exposed interfaces: - [core](core): Common classes used throughout the other coordinator modules - [cql](cql): API implementation for the Cassandra Query Language - [grpc](grpc): fast CQL over gRPC implementation (HTTP-based interface equivalent to CQL performance) - [bridge](bridge): gRPC-based interface used by API services - [health-checker](core): HTTP endpoints useful for health checking coordinator nodes - [metrics-jersey](core): metrics collection for the coordinator node and its exposed interfaces - [stargate-starter](stargate-starter): the main Java application used to start the coordinator via the `starctl` script #### Persistence Services Stargate coordinator nodes support a pluggable approach for implementing the coordination layer to execute requests passed by API services and other interfaces to underlying data storage instances. Persistence service implementations are responsible handling and converting requests to database queries, dispatching to a specific version of Cassandra, and returning and serving responses. - [persistence-api](persistence-api): Interface for working with persistence services - [persistence-common](persistence-common): Utilities shared by the persistence services - [persistence-cassandra-3.11](persistence-cassandra-3.11): Joins C* 3.11 cluster as coordinator-only node (does not store data) mocks C* system tables for native driver integration, executes requests with C* storage nodes using C* QueryHandler/QueryProcessor, converts internal C* objects and ResultSets to Stargate Datastore objects. - [persistence-cassandra-4.0](persistence-cassandra-4.0): (same as above but for Cassandra 4.0) - [persistence-dse-6.8](persistence-dse-6.8): (same as above but for DataStax Enterprise 6.8) #### Authentication and Authorization Services Stargate coordinator nodes also support a pluggable authentication and authorization approach. - [authnz](authnz): Interface for working with auth providers - [auth-api](auth-api): REST service for generating auth tokens - [auth-table-based-service](auth-table-based-service): Service to store tokens in the database - [auth-jtw-service](auth-jwt-service): Service to authenticate using externally generated JSON Web Tokens (JWTs) #### Coordinator Node Testing The following modules provide support for testing: - [testing](testing): Integration test suite for the coordinator node modules - [persistence-test](persistence-test): Common utilities for testing persistence services Instructions for running and extending the test suite can be found in the [developer guide](DEV_GUIDE.md). ## Repositories Here is an overview of the key repositories in the Stargate GitHub organization: - [stargate/stargate](https://github.com/stargate/stargate): This repository is the primary entry point to the project. It is a monorepo containing all of the Stargate modules - [stargate/docs](https://github.com/stargate/docs): This repository contains the user docs hosted on [stargate.io](https://stargate.io) - [stargate/website](https://github.com/stargate/website): This repository contains the code for the website hosted on [stargate.io](https://stargate.io) The organization also contains several gRPC client libraries for various languages. ## Issue Management You can reference the [CONTRIBUTING.md](CONTRIBUTING.md) for a full description of how to get involved, but the short of it is below. - If you've found a bug (use the bug label) or want to request a new feature (use the enhancement label), file a GitHub issue - If you're not sure about it or want to chat, reach out on our [Discord](https://discord.gg/GravUqY) - If you want to write some user docs ๐ŸŽ‰ head over to the [stargate/docs](https://github.com/stargate/docs) repo, Pull Requests accepted! ## Supported Versions and Branching Strategy The Stargate project maintains support for the current major version number and one major version number previous. We mark the previous major version number as deprecated in order to encourage usage of the latest version. We anticipate supporting a major version number release N for one year after the subsequent major version number release (N+1), or until the major version number release (N+2), whichever comes first. For example, v1 will be supported until when Stargate v3 is released, but no later than October 2023 (1 year after release date of Stargate v2). We anticipate producing a new major version number release every 6-12 months. Supporting a release entails making bug fixes, keeping dependencies up to date, and making sure Docker images are free from vulnerabilities. The current major version is maintained on the default `main` branch. The prior major version number is maintained on a version branch, for example, `v1`. We make bug fixes in all supported releases. The recommended approach is to commit a fix first to the previous major version branch (if applicable) and merge it forward into the current major version branch. We use minor version numbers to indicate any changes to the coordinator that would cause compatibility changes for Stargate APIs. For example, a breaking change to the [bridge](bridge) API in v2.0.x would cause creation of a v2.1.0 release, and any API implementations would need to explicitly update in order to be compatible. You can use any version of the coordinator and API that have same the major and minor version number without issues. We iterate forward rather than producing patch releases. For example, for a vulnerability found in `v2.0.3`, we'd make any required fixes and dependency updates and release `v2.0.4`. We maintain a regular release cadence of approximately twice a month but can iterate more quickly as the situation dictates. ## Thanks ![YourKit Logo](https://www.yourkit.com/images/yklogo.png) This project uses tools provided by YourKit, LLC. YourKit supports open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of <a href="https://www.yourkit.com/java/profiler/">YourKit Java Profiler</a> and <a href="https://www.yourkit.com/.net/profiler/">YourKit .NET Profiler</a>, innovative and intelligent tools for profiling Java and .NET applications.
144
Apache IoTDB
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> [English](./README.md) | [ไธญๆ–‡](./README_ZH.md) # IoTDB [![Main Mac and Linux](https://github.com/apache/iotdb/actions/workflows/main-unix.yml/badge.svg)](https://github.com/apache/iotdb/actions/workflows/main-unix.yml) [![Main Win](https://github.com/apache/iotdb/actions/workflows/main-win.yml/badge.svg)](https://github.com/apache/iotdb/actions/workflows/main-win.yml)<!--[![coveralls](https://coveralls.io/repos/github/apache/iotdb/badge.svg?branch=master)](https://coveralls.io/repos/github/apache/iotdb/badge.svg?branch=master)--> [![GitHub release](https://img.shields.io/github/release/apache/iotdb.svg)](https://github.com/apache/iotdb/releases) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) ![](https://github-size-badge.herokuapp.com/apache/iotdb.svg) ![](https://img.shields.io/github/downloads/apache/iotdb/total.svg) ![](https://img.shields.io/badge/platform-win%20%7C%20macos%20%7C%20linux-yellow.svg) ![](https://img.shields.io/badge/java--language-1.8%20%7C%2011%20%7C%2017-blue.svg) [![Language grade: Java](https://img.shields.io/lgtm/grade/java/g/apache/iotdb.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/apache/iotdb/context:java) [![IoTDB Website](https://img.shields.io/website-up-down-green-red/https/shields.io.svg?label=iotdb-website)](https://iotdb.apache.org/) [![Maven Version](https://maven-badges.herokuapp.com/maven-central/org.apache.iotdb/iotdb-parent/badge.svg)](http://search.maven.org/#search|gav|1|g:"org.apache.iotdb") [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/apache/iotdb) [![Slack Status](https://img.shields.io/badge/slack-join_chat-white.svg?logo=slack&style=social)](https://join.slack.com/t/apacheiotdb/shared_invite/zt-qvso1nj8-7715TpySZtZqmyG5qXQwpg) # Overview IoTDB (Internet of Things Database) is a data management system for time series data, which provides users with specific services including data collection, storage and analysis. Due to its light weight structure, high performance and usable features, together with its seamless integration with the Hadoop and Spark ecology, IoTDB meets the requirements of massive dataset storage, high throughput data input, and complex data analysis in the industrial IoT field. # Main Features Main features of IoTDB are as follows: 1. Flexible deployment strategy. IoTDB provides users a one-click installation tool on either the cloud platform or the terminal devices, and a data synchronization tool bridging the data on cloud platform and terminals. 2. Low cost on hardware. IoTDB can reach a high compression ratio of disk storage. 3. Efficient directory structure. IoTDB supports efficient organization for complex time series data structures from intelligent networking devices, organization for time series data from devices of the same type, and fuzzy searching strategy for massive and complex directory of time series data. 4. High-throughput read and write. IoTDB supports millions of low-power devices' strong connection data access, high-speed data read and write for intelligent networking devices and mixed devices mentioned above. 5. Rich query semantics. IoTDB supports time alignment for time series data across devices and measurements, computation in time series field (frequency domain transformation) and rich aggregation function support in time dimension. 6. Easy to get started. IoTDB supports SQL-Like language, JDBC standard API and import/export tools which is easy to use. 7. Seamless integration with state-of-the-practice Open Source Ecosystem. IoTDB supports analysis ecosystems such as, Hadoop, Spark, and visualization tool, such as, Grafana. For the latest information about IoTDB, please visit [IoTDB official website](https://iotdb.apache.org/). If you encounter any problems or identify any bugs while using IoTDB, please report an issue in [jira](https://issues.apache.org/jira/projects/IOTDB/issues). <!-- TOC --> ## Outline - [IoTDB](#iotdb) - [Overview](#overview) - [Main Features](#main-features) - [Outline](#outline) - [Quick Start](#quick-start) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Build from source](#build-from-source) - [Configurations](#configurations) - [Start](#start) - [Start IoTDB](#start-iotdb) - [Use IoTDB](#use-iotdb) - [Use Cli](#use-cli) - [Basic commands for IoTDB](#basic-commands-for-iotdb) - [Stop IoTDB](#stop-iotdb) - [Only build server](#only-build-server) - [Only build cli](#only-build-cli) - [Usage of CSV Import and Export Tool](#usage-of-csv-import-and-export-tool) <!-- /TOC --> # Quick Start This short guide will walk you through the basic process of using IoTDB. For a more detailed introduction, please visit our website's [User Guide](https://iotdb.apache.org/UserGuide/Master/QuickStart/QuickStart.html). ## Prerequisites To use IoTDB, you need to have: 1. Java >= 1.8 (1.8, 11 to 17 are verified. Please make sure the environment path has been set accordingly). 2. Maven >= 3.6 (If you want to compile and install IoTDB from source code). 3. Set the max open files num as 65535 to avoid "too many open files" error. 4. (Optional) Set the somaxconn as 65535 to avoid "connection reset" error when the system is under high load. ``` # Linux > sudo sysctl -w net.core.somaxconn=65535 # FreeBSD or Darwin > sudo sysctl -w kern.ipc.somaxconn=65535 ``` ## Installation IoTDB provides three installation methods, you can refer to the following suggestions, choose the one fits you best: * Installation from source code. If you need to modify the code yourself, you can use this method. * Installation from binary files. Download the binary files from the official website. This is the recommended method, in which you will get a binary released package which is out-of-the-box. * Using Docker๏ผšThe path to the dockerfile is https://github.com/apache/iotdb/tree/master/docker/src/main Here in the Quick Start, we give a brief introduction of using source code to install IoTDB. For further information, please refer to [User Guide](https://iotdb.apache.org/UserGuide/Master/QuickStart/QuickStart.html). ## Build from source ### Prepare Thrift compiler Skip this chapter if you are using Windows. As we use Thrift for our RPC module (communication and protocol definition), we involve Thrift during the compilation, so Thrift compiler 0.13.0 (or higher) is required to generate Thrift Java code. Thrift officially provides binary compiler for Windows, but unfortunately, they do not provide that for Unix OSs. If you have permission to install new softwares, use `apt install` or `yum install` or `brew install` to install the Thrift compiler (If you already have installed the thrift compiler, skip this step). Then, you may add the following parameter when running Maven: `-Dthrift.download-url=http://apache.org/licenses/LICENSE-2.0.txt -Dthrift.exec.absolute.path=<YOUR LOCAL THRIFT BINARY FILE>`. If not, then you have to compile the thrift compiler, and it requires you install a boost library first. Therefore, we compiled a Unix compiler ourselves and put it onto GitHub, and with the help of a maven plugin, it will be downloaded automatically during compilation. This compiler works fine with gcc8 or later, Ubuntu MacOS, and CentOS, but previous versions and other OSs are not guaranteed. If you can not download the thrift compiler automatically because of network problem, you can download it yourself, and then either: rename your thrift file to `{project_root}\thrift\target\tools\thrift_0.12.0_0.13.0_linux.exe`; or, add Maven commands: `-Dthrift.download-url=http://apache.org/licenses/LICENSE-2.0.txt -Dthrift.exec.absolute.path=<YOUR LOCAL THRIFT BINARY FILE>`. ### Compile IoTDB You can download the source code from: ``` git clone https://github.com/apache/iotdb.git ``` The default dev branch is the master branch, If you want to use a released version x.x.x: ``` git checkout vx.x.x ``` Or checkout to the branch of a big version, e.g., the branch of 1.0 is rel/1.0 ``` git checkout rel/x.x ``` ### Build IoTDB from source Under the root path of iotdb: ``` > mvn clean package -pl distribution -am -DskipTests ``` After being built, the IoTDB distribution is located at the folder: "distribution/target". ### Only build cli Under the root path of iotdb: ``` > mvn clean package -pl cli -am -DskipTests ``` After being built, the IoTDB cli is located at the folder "cli/target". ### Build Others Using `-P compile-cpp` for compiling cpp client (For more details, read client-cpp's Readme file.) **NOTE: Directories "`thrift/target/generated-sources/thrift`", "`thrift-sync/target/generated-sources/thrift`", "`thrift-cluster/target/generated-sources/thrift`", "`thrift-influxdb/target/generated-sources/thrift`" and "`antlr/target/generated-sources/antlr4`" need to be added to sources roots to avoid compilation errors in the IDE.** **In IDEA, you just need to right click on the root project name and choose "`Maven->Reload Project`" after you run `mvn package` successfully.** ### Configurations configuration files are under "conf" folder * environment config module (`datanode-env.bat`, `datanode-env.sh`), * system config module (`iotdb-datanode.properties`) * log config module (`logback.xml`). For more information, please see [Config Manual](https://iotdb.apache.org/UserGuide/Master/Reference/Config-Manual.html). ## Start You can go through the following steps to test the installation. If there is no error returned after execution, the installation is completed. ### Start IoTDB Users can start 1C1D IoTDB by the start-standalone script under the sbin folder. ``` # Unix/OS X > sbin/start-standalone.sh # Windows > sbin\start-standalone.bat ``` ### Use IoTDB #### Use Cli IoTDB offers different ways to interact with server, here we introduce the basic steps of using Cli tool to insert and query data. After installing IoTDB, there is a default user 'root', its default password is also 'root'. Users can use this default user to login Cli to use IoTDB. The startup script of Cli is the start-cli script in the folder sbin. When executing the script, user should assign IP, PORT, USER_NAME and PASSWORD. The default parameters are "-h 127.0.0.1 -p 6667 -u root -pw -root". Here is the command for starting the Cli: ``` # Unix/OS X > sbin/start-cli.sh -h 127.0.0.1 -p 6667 -u root -pw root # Windows > sbin\start-cli.bat -h 127.0.0.1 -p 6667 -u root -pw root ``` The command line cli is interactive, so you should see the welcome logo and statements if everything is ready: ``` _____ _________ ______ ______ |_ _| | _ _ ||_ _ `.|_ _ \ | | .--.|_/ | | \_| | | `. \ | |_) | | | / .'`\ \ | | | | | | | __'. _| |_| \__. | _| |_ _| |_.' /_| |__) | |_____|'.__.' |_____| |______.'|_______/ version x.x.x IoTDB> login successfully IoTDB> ``` #### Basic commands for IoTDB Now, let us introduce the way of creating timeseries, inserting data and querying data. The data in IoTDB is organized as timeseries. Each timeseries includes multiple data-time pairs, and is owned by a database. Before defining a timeseries, we should define a database using CREATE DATABASE first, and here is an example: ``` IoTDB> CREATE DATABASE root.ln ``` We can also use SHOW DATABASES to check the database being created: ``` IoTDB> SHOW DATABASES +-------------+ | Database| +-------------+ | root.ln| +-------------+ Total line number = 1 ``` After the database is set, we can use CREATE TIMESERIES to create a new timeseries. When creating a timeseries, we should define its data type and the encoding scheme. Here We create two timeseries: ``` IoTDB> CREATE TIMESERIES root.ln.wf01.wt01.status WITH DATATYPE=BOOLEAN, ENCODING=PLAIN IoTDB> CREATE TIMESERIES root.ln.wf01.wt01.temperature WITH DATATYPE=FLOAT, ENCODING=RLE ``` In order to query the specific timeseries, we can use SHOW TIMESERIES <Path>. <Path> represent the location of the timeseries. The default value is "null", which queries all the timeseries in the system(the same as using "SHOW TIMESERIES root"). Here are some examples: 1. Querying all timeseries in the system: ``` IoTDB> SHOW TIMESERIES +-----------------------------+-----+-------------+--------+--------+-----------+----+----------+ | Timeseries|Alias|Database|DataType|Encoding|Compression|Tags|Attributes| +-----------------------------+-----+-------------+--------+--------+-----------+----+----------+ |root.ln.wf01.wt01.temperature| null| root.ln| FLOAT| RLE| SNAPPY|null| null| | root.ln.wf01.wt01.status| null| root.ln| BOOLEAN| PLAIN| SNAPPY|null| null| +-----------------------------+-----+-------------+--------+--------+-----------+----+----------+ Total line number = 2 ``` 2. Querying a specific timeseries(root.ln.wf01.wt01.status): ``` IoTDB> SHOW TIMESERIES root.ln.wf01.wt01.status +------------------------+-----+-------------+--------+--------+-----------+----+----------+ | timeseries|alias|database|dataType|encoding|compression|tags|attributes| +------------------------+-----+-------------+--------+--------+-----------+----+----------+ |root.ln.wf01.wt01.status| null| root.ln| BOOLEAN| PLAIN| SNAPPY|null| null| +------------------------+-----+-------------+--------+--------+-----------+----+----------+ Total line number = 1 ``` Insert timeseries data is a basic operation of IoTDB, you can use โ€˜INSERTโ€™ command to finish this. Before insertion, you should assign the timestamp and the suffix path name: ``` IoTDB> INSERT INTO root.ln.wf01.wt01(timestamp,status) values(100,true); IoTDB> INSERT INTO root.ln.wf01.wt01(timestamp,status,temperature) values(200,false,20.71) ``` The data that you have just inserted will display as follows: ``` IoTDB> SELECT status FROM root.ln.wf01.wt01 +------------------------+------------------------+ | Time|root.ln.wf01.wt01.status| +------------------------+------------------------+ |1970-01-01T00:00:00.100Z| true| |1970-01-01T00:00:00.200Z| false| +------------------------+------------------------+ Total line number = 2 ``` You can also query several timeseries data using one SQL statement: ``` IoTDB> SELECT * FROM root.ln.wf01.wt01 +------------------------+-----------------------------+------------------------+ | Time|root.ln.wf01.wt01.temperature|root.ln.wf01.wt01.status| +------------------------+-----------------------------+------------------------+ |1970-01-01T00:00:00.100Z| null| true| |1970-01-01T00:00:00.200Z| 20.71| false| +------------------------+-----------------------------+------------------------+ Total line number = 2 ``` To change the time zone in Cli, you can use the following SQL: ``` IoTDB> SET time_zone=+08:00 Time zone has set to +08:00 IoTDB> SHOW time_zone Current time zone: Asia/Shanghai ``` Add then the query result will show using the new time zone. ``` IoTDB> SELECT * FROM root.ln.wf01.wt01 +-----------------------------+-----------------------------+------------------------+ | Time|root.ln.wf01.wt01.temperature|root.ln.wf01.wt01.status| +-----------------------------+-----------------------------+------------------------+ |1970-01-01T08:00:00.100+08:00| null| true| |1970-01-01T08:00:00.200+08:00| 20.71| false| +-----------------------------+-----------------------------+------------------------+ Total line number = 2 ``` The commands to exit the Cli are: ``` IoTDB> quit or IoTDB> exit ``` For more information about the commands supported by IoTDB SQL, please see [User Guide](https://iotdb.apache.org/UserGuide/Master/QuickStart/QuickStart.html). ### Stop IoTDB The server can be stopped with "ctrl-C" or the following script: ``` # Unix/OS X > sbin/stop-standalone.sh # Windows > sbin\stop-standalone.bat ``` # Usage of CSV Import and Export Tool see [Usage of CSV Import and Export Tool](https://iotdb.apache.org/UserGuide/Master/Write-And-Delete-Data/CSV-Tool.html) # Frequent Questions for Compiling see [Frequent Questions when Compiling the Source Code](https://iotdb.apache.org/Development/ContributeGuide.html#_Frequent-Questions-when-Compiling-the-Source-Code) # Contact Us ### QQ Group * Apache IoTDB User Group: 659990460 ### Wechat Group * Add friend: `tietouqiao` or `liutaohua001`, and then we'll invite you to the group. ### Slack * https://join.slack.com/t/apacheiotdb/shared_invite/zt-qvso1nj8-7715TpySZtZqmyG5qXQwpg see [Join the community](https://github.com/apache/iotdb/issues/1995) for more!
145
A curated list of awesome JavaFX libraries, books, frameworks, etc...
# Awesome JavaFX [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) A curated list of awesome JavaFX frameworks, libraries, books etc... . ---- ## Contents - [Libraries, Tools and Projects](#libraries-tools-and-projects) - [Frameworks](#frameworks) - [Books](#books) - [Blogs and Sites](#blogs-and-sites) - [People](#people) - [Tutorials](#tutorials) - [Talks](#talks) - [Slides](#slides) - [Articles](#articles) - [Real World Examples](#real-world-examples) ---- ## Libraries, Tools and Projects - [Advanced-Bindings for JavaFX (8)](https://github.com/lestard/advanced-bindings) - advanced-bindings is a collection of useful helpers and custom binding implementations like java.lang.Math or Switch-Case as JavaFX binding. - [AnchorFX](https://github.com/alexbodogit/AnchorFX) - Docking framework for JavaFX platform. - [Animated](https://github.com/iAmGio/animated) - Implicit animations for JavaFX, inspired by Flutter. - [AnimateFX](https://github.com/Typhon0/AnimateFX) - A JavaFX library containing ready-to-use animations. - [assertj-javafx](https://github.com/lestard/assertj-javafx) - AssertJ assertions for JavaFX Properties and Bindings. - [BootstrapFX](https://github.com/aalmiray/bootstrapfx/) - BootstrapFX is a partial port of Twitter Bootstrap for JavaFX. - [CalendarFX](https://github.com/dlemmermann/CalendarFX) - CalendarFX is a calendar framework for JavaFX 8. It contains a set of professional custom controls, which can be used to implement a calendar UI for any kind of application. - [ChartFx](https://github.com/GSI-CS-CO/chart-fx) - ChartFx is a scientific charting library developed at [GSI](https://www.gsi.de/en) for [FAIR] (https://www.gsi.de/en/researchaccelerators/fair.htm) with focus on performance optimised real-time data visualisation for data sets with up to millions of data point. - [CssFX](https://github.com/McFoggy/cssfx) - Enhances developer productivity by providing JavaFX CSS reloading functionnality in a running application. Usable as standalone library or integrated in [Scenic View](#ScenicView). - [Component-Inspector](https://github.com/TangoraBox/ComponentInspector) - A tool to help you inspect the location and properties of certain components in a window hierarchy. - [ControlsFX](http://fxexperience.com/controlsfx/) - ControlsFX is an open source project for JavaFX that aims to provide really high quality UI controls and other tools to complement the core JavaFX distribution. - [CustomStage](https://github.com/Oshan96/CustomStage) - CustomStage is a fully customizable Undecorated JavaFX stage (window) with amazing features. - [DesktopPaneFX](https://github.com/aalmiray/desktoppanefx) - MDI components for JavaFX. Think JDesktopPane/JInternalFrame for JavaFX. - [e(fx)clipse](http://www.efxclipse.org/) - JavaFX Tooling and Runtime for Eclipse and OSGi. - [FlexBoxFX](https://github.com/malikoski/FlexBoxFX) - FlexBoxFX is a JavaFX implementation of CSS3 flexbox layout manager. - [FlexGanttFX](http://dlsc.com/products/flexganttfx/) - FlexGanttFX is the most advanced JavaFX-based Gantt charting framework currently available for Java. - [Flowless](https://github.com/TomasMikula/Flowless) - Efficient VirtualFlow for JavaFX. - [FontAwesomeFX](https://bitbucket.org/Jerady/fontawesomefx) - FontAwesome in JavaFX with FontAwesomeFX. - [FormsFX](https://github.com/dlemmermann/FormsFX) - A framework for easily creating forms for a JavaFX UI. - [FroXty](https://github.com/iAmGio/froxty) - iOS frosty/translucent effect to JavaFX. - [FX-BorderlessScene](https://github.com/goxr3plus/FX-BorderlessScene) - Undecorated JavaFX Scene with implemented move, resize, minimise, maximise, close and Windows Aero Snap controls. - [FXFileChooser](https://oliver-loeffler.github.io/FXFileChooser/) - provides an alternative file chooser especially suitable for extreme large directories where an integrated live search and filtering can be helpful. - [FXForm2](https://github.com/dooApp/FXForm2) - A library providing automatic JavaFX form generation. The generated form is highly configurable and skinnable using code, annotations and CSS styling. FXForm2 is compatible with the JSR 303 for bean validation. - [FXGraphics2D](https://github.com/jfree/fxgraphics2d) - A library that provides a Graphics2D API for drawing on the JavaFX Canvas so that existing Java2D code can be reused easily. This library was created to provide JavaFX support for JFreeChart. - [FXLauncher](https://github.com/edvin/fxlauncher) - Auto updating launcher for JavaFX Applications. Combined with JavaFX native packaging, you get a native installer with automatic app updates. - [FXParallax](https://github.com/dukke/FXParallax) - Parallax framework for Java (JavaFX). - [FXRibbon](https://github.com/dukke/FXRibbon) - Microsoft like Ribbon control for Java (JavaFX). - [FXTaskbarProgressBar](https://github.com/Dansoftowner/FXTaskbarProgressBar) - A library for showing progress on the Windows taskbar. - [FXTrayIcon](https://github.com/dustinkredmond/FXTrayIcon) - System TrayIcon implementation for JavaFX that allows developers to use native JavaFX MenuItems and not have to worry with AWT or Swing. - [FXValidation](https://github.com/dukke/FXValidation) - Validation support for Java (JavaFX). - [FXyz](https://github.com/Birdasaur/FXyz) - F(X)yz is a new JavaFX 3D library that provides additional primitives, composite objects, controls and data visualizations that the base JavaFX 8 3D packages do not have. - [GemsFX](https://github.com/dlsc-software-consulting-gmbh/GemsFX) - A small library with useful controls: an on-screen keyboard, a PDF viewer control, and some more. - [GestureFX](https://github.com/tom91136/GestureFX) - A lightweight pinch-to-zoom pane for JavaFX. - [Getdown](https://github.com/threerings/getdown) - Getdown is a system for deploying Java applications to end-user computers, as well as keeping those applications up to date. - [Gluon Maps](http://gluonhq.com/labs/maps/) - Gluon Maps is built with high performance in mind, but that doesnโ€™t mean functionality is missing. Gluon Maps offers layer overlays, multiple tilesets, and much more. - [Gluon Scene Builder](http://gluonhq.com/labs/scene-builder/) - Scene Builder works with the JavaFX ecosystem โ€“ official controls, community projects, and Gluon offerings including Gluon Mobile, Gluon Desktop, and Gluon CloudLink. - [GMapFX](http://rterp.github.io/GMapsFX/) - GMapsFX provides a wrapper to the Google Map's Javascript API, allowing you to use and interact with maps using a pure Java API. - [graph editor](https://github.com/eckig/graph-editor) - A library for creating and editing graph-like diagrams in JavaFX. - [Grid](https://github.com/lestard/Grid) - A Component for grid based games like sudoku or chess. - [Ikonli](https://github.com/kordamp/ikonli) - Ikonli provides icon packs that can be used in Java applications. Currently Swing and JavaFX UI toolkits are supported. - [JavaFX DataViewer](https://github.com/jasrodis/javafx-dataviewer-wrapper) - JavaFX Charts library. Create Charts in JavaFX using the plotly.js library. - [javafx-d3](https://github.com/stefaneidelloth/javafx-d3) - javafx-d3 provides a Java API for using the JavaScript library d3.js with JavaFx Applications. - [JavaFXPorts](http://gluonhq.com/labs/javafxports/) - JavaFXPorts is the open source project that brings Java and JavaFX to mobile and embedded hardware, including iPhone, iPad, Android devices, and the Raspberry Pi. - [JCSG](https://github.com/miho/JCSG) - Java implementation of BSP based CSG (Constructive Solid Geometry). - [JFoenix](http://www.jfoenix.com/) - JavaFX Material Design Library. JFoenix is an open source Java library, that implements Google Material Design using Java components. - [JFXAnimation](https://github.com/schlegel11/JFXAnimation) - Builder for CSS keyframe animations in JavaFX. Create animations like you would do with CSS. - [JFXNodeMapper](https://github.com/CaptainParanoid/JFXNodeMapper) - Javafx Node mapping to various data formats like csv,xml,json and resultset. - [JFXScad](https://github.com/miho/JFXScad) - JavaFX 3D Printing IDE based on JCSG. - [JFXtras](http://jfxtras.org/) - A supporting library for JavaFX, containing helper classes, extended layouts, controls and other interesting widgets. - [JideFX](https://github.com/jidesoft/jidefx-oss)- JideFX Common Layer is a collection of various extensions and utilities for to JavaFX platform. The JideFX Common Layer is the equivalent to the JIDE Common Layer in the JIDE components for Swing. - [JMetro](https://www.pixelduke.com/jmetro) - Modern theme (or look and feel) for JavaFX inspired by Microsoft Metro / Fluent Design System. It is used for instance in NASA's app: [Deep Space Trajectory Explorer](https://www.youtube.com/watch?v=MotQ1PC1xT8). - [jpro](https://www.jpro.one/) - JavaFX for the Browser. jpro is a new technology which brings Java back into the browser - without Java Plugin. - [JSilhouette](https://github.com/aalmiray/jsilhouette) - JSilhouette provides additional shapes for Java applications. - [Kubed](https://github.com/hudsonb/kubed) - A port of the popular Javascript library D3.js to Kotlin/JavaFX. - [Lib-Tile](https://github.com/Naoghuman/lib-tile) - Lib-Tile is a multi Maven project written in JavaFX and NetBeans IDE 8.0.2 and provides the functionalities to use and handle easily Tiles in your JavaFX application. - [LiveDirsFX](https://github.com/TomasMikula/LiveDirsFX) - Directory tree model for JavaFX that watches the filesystem for changes. - [MaterialFX](https://github.com/palexdev/MaterialFX) - A new well documented and actively developed library which brings material design components to JavaFX and much more. - [Maven jpackage Template](https://github.com/wiverson/maven-jpackage-template) - GitHub template. Use Maven, jlink and jpackage to produce JavaFX macOS, Windows and Linux installers via GitHub Actions. - [Medusa](https://github.com/HanSolo/Medusa) - A JavaFX library for Gauges. The main focus of this project is to provide Gauges that can be configured in multiple ways. - [MigPane](http://miglayout.com) - MigLayout can produce flowing, grid based, absolute (with links), grouped and docking layouts. - [NetBeansIDE-AfterburnerFX-Plugin](https://github.com/Naoghuman/NetBeansIDE-AfterburnerFX-Plugin) - The NetBeansIDE-AfterburnerFX-Plugin is a NetBeans IDE plugin which supports the file generation in convention with the library afterburner.fx in a JavaFX project. - [Orson Charts](https://github.com/jfree/orson-charts) - An interactive 3D chart library for JavaFX and Swing. - [PI-Rail-FX](https://gitlab.com/pi-rail/pi-rail-fx) - A UI for a model railway control system. - [PreferencesFX](https://github.com/dlemmermann/PreferencesFX) - A library to easily create a UI for application settings / preferences. - [ReactorFX](https://github.com/shadskii/ReactorFX) - ReactorFX integrates Project Reactor and JavaFX by providing a simple API to create reactive Flux from JavaFX Controls, Dialogs, Observables, and Collections. - [ReactFX](https://github.com/TomasMikula/ReactFX) - Reactive event streams, observable values and more for JavaFX. - [redux-javafx-devtool](https://github.com/lestard/redux-javafx-devtool) - A developer-tool for ReduxFX. Visualizes the state and actions of the app. Enables time-traveling. - [RichTextFX](https://github.com/TomasMikula/RichTextFX) - Rich-text area for JavaFX. - [RxJavaFX: JavaFX bindings for RxJava](https://github.com/ReactiveX/RxJavaFX) - RxJavaFX is a simple API to convert JavaFX events into RxJava Observables and vice versa. It also has a scheduler to safely move emissions to the JavaFX Event Dispatch Thread. - [Scenic View](http://fxexperience.com/scenic-view/) - Scenic View is a JavaFX application designed to make it simple to understand the current state of your application scenegraph, and to also easily manipulate properties of the scenegraph without having to keep editing your code. This lets you find bugs, and get things pixel perfect without having to do the compile-check-compile dance. - [SmartCSVFX](https://github.com/frosch95/SmartCSV.fx) - A simple JavaFX application to load, save and edit a CSV file and provide a JSON configuration for columns to check the values in the columns. - [Stream-Pi](https://github.com/stream-pi) - A modular, free, Open Source, Cross-platform macro pad software. - [SynchronizeFX](https://github.com/lestard/SynchronizeFX) - Remote Data-Binding between different JVMs, both on a local machine and over the network. - [SyntheticaFX](http://www.jyloo.com/syntheticafx/) - SyntheticaFX provides themes and components mainly made for professional business applications on the desktop. The library is growing, new controls are under construction and will be added in future releases. The target platform of the final release is Java 9 or above. - [TestFX](https://github.com/TestFX/TestFX) - Simple and clean testing for JavaFX. - [TestFX-dsl](https://github.com/aalmiray/testfx-dsl/) - Java friendly DSL for defining TestFX tests. - [TilesFX](https://github.com/HanSolo/tilesfx) - A JavaFX library containing tiles for Dashboards. - [TiwulFX](https://bitbucket.org/panemu/tiwulfx) provides UI components: advanced TableView with various ready to use columns (TextColumn, NumberColumn, LookupColumn etc), DetachableTabPane that can be used as docking framework, MessageDialog, SideMenu etc. - [TuioFX](http://tuiofx.org/) - Toolkit for developing multi-touch, multi-user interactive tabletops and surfaces. - [Toggle Switch](https://www.pixelduke.com/projects#toggle-switch) - Toggle Switch control for Java (JavaFX). - [Undecorator](https://github.com/in-sideFX/Undecorator) - Decorate undecorated JavaFX stages with custom skin. This helper brings a custom look to your JavaFX stages. - [UndoFX](https://github.com/TomasMikula/UndoFX) - Undo manager for JavaFX. - [Update4j](https://github.com/update4j/update4j) - Auto-updater and launcher for your distributed applications. Built with Java 9's module system in mind. - [VWorkflows](https://github.com/miho/VWorkflows) - Interactive flow/graph visualization for building domain specific visual programming environments. Provides UI bindings for JavaFX. - [WebFX](https://webfx.dev) - A JavaFX application transpiler. Write your Web Application in JavaFX and WebFX will transpile it in pure JS. - [Webview Debugger](https://github.com/vsch/Javafx-WebView-Debugger) - JavaFx WebView debugging with Chrome Dev tools. - [WellBehavedFX](https://github.com/TomasMikula/WellBehavedFX) - Composable event handlers and skin scaffolding for JavaFX controls. - [Wordagam](https://github.com/gravetii/wordagam) - A fun little word game built with openjfx. ## Frameworks - [afterburner.fx](http://afterburner.adam-bien.com/) - afterburner.fx is a minimalistic (3 classes) JavaFX MVP framework based on Convention over Configuration and Dependency Injection. - [APX](https://github.com/othreecodes/APX) - A JavaFX Library for Creating and Implementing MVC Type applications. - [Basilisk](https://github.com/basilisk-fw/basilisk) - Desktop/Mobile JavaFX application framework. [Apache License V2](https://www.apache.org/licenses/LICENSE-2.0) - [DataFX](https://github.com/guigarage/DataFX) - DataFX is a JavaFX frameworks that provides additional features to create MVC based applications in JavaFX by providing routing and a context for CDI. - [Dolphin Platform](https://github.com/canoo/dolphin-platform) - Dolphin Platform is a client / server frameworks that provides a async communication between a server and a client based on the remote presentation model pattern. - [EasyBind](https://github.com/TomasMikula/EasyBind) - EasyBind leverages lambdas to reduce boilerplate when creating custom bindings. - [EasyFXML](https://github.com/Tristan971/EasyFXML) - EasyFXML is a fully-featured opinionated JavaFX framework based on Vavr and Spring Boot which manages most of the annoying boilerplate that comes with JavaFX. [Apache License V2](https://www.apache.org/licenses/LICENSE-2.0). - [FXGL](http://almasb.github.io/FXGL/) - JavaFX Game Development Framework. - [Griffon](http://griffon-framework.org/) - Next generation desktop application development platform for the JVM. [Apache License V2](https://www.apache.org/licenses/LICENSE-2.0). - [JacpFX](http://jacpfx.org/) - An UI application framework based on JavaFX. - [JRebirth](http://www.jrebirth.org/) - JRebirth JavaFX Application Framework provides a really simple way to write sophisticated and powerful RIA and Desktop applications. - [mvvmFX](https://github.com/sialcasa/mvvmFX) - mvvm(fx) is an application framework which provides you necessary components to implement the MVVM pattern with JavaFX. [Apache License V2](https://www.apache.org/licenses/LICENSE-2.0). - [Open Lowcode](https://github.com/openlowcode/Open-Lowcode) - A low-code framework for enterprise software with a JavaFX thin client. - [ReactiveDeskFX](https://github.com/TangoraBox/ReactiveDeskFX) - JavaFX micro-framework to develop JavaFX components very fast with minimal code following MVVM architecture pattern with passive view. - [ReduxFX](https://github.com/netopyr/reduxfx) - Functional Reactive Programming (FRP) for JavaFX inspired by the JavaScript library Redux.js. - [ScalaFX](http://www.scalafx.org/) - simplifies creation of JavaFX-based user interfaces in Scala. - [TornadoFX](https://github.com/edvin/tornadofx) - Lightweight JavaFX Framework for Kotlin. - [WorkbenchFX](https://github.com/dlemmermann/WorkbenchFX) - A lightweight RCP framework for JavaFX applications. ## Books - [Getting started with Java on the Raspberry Pi](https://leanpub.com/gettingstartedwithjavaontheraspberrypi/) - By [Frank Delporte](https://twitter.com/FrankDelporte)<br/> Get started with the latest versions of Java, JavaFX, Pi4J, Spring and so much more. Learn the power (and fun!) of experimenting with electronics. All explained in many small and easy to understand examples. - [Introducing JavaFX 8 Programming](https://www.mhprofessional.com/details.php?isbn=0071842551) - By Herbert Schildt<br/> Introducing JavaFX 8 Programming provides a fast-paced, practical introduction to JavaFX, Java's next-generation GUI programming framework. In this easy-to-read guide, best-selling author Herb Schildt presents the key topics and concepts you'll need to start developing modern, dynamic JavaFX GUI applications. - [JavaFX 9 by Example](https://www.apress.com/gp/book/9781484219607) - by [Carl Dea](https://twitter.com/carldea) , [Mark Heckler](https://twitter.com/MkHeck) , [Gerrit Grunwald](https://twitter.com/hansolo_) , [Josรฉ Pereda](https://twitter.com/JPeredaDnr) , [Sean Phillips](https://twitter.com/SeanMiPhillips)<br/> JavaFX 9 by Example is chock-full of engaging, fun-to-work examples that bring you up to speed on the major facets of JavaFX 9. - [JavaFX Essentials](https://www.packtpub.com/web-development/javafx-essentials) - By [Mohamed Taman](https://twitter.com/_tamanm)<br/> Create amazing Java GUI applications with this hands-on, fast-paced guide - [Learn JavaFX 8 Building User Experience and Interfaces with Java 8](http://www.apress.com/9781484211434) - by Kishori Sharan<br/> Start developing rich-client desktop applications using your Java skills. Learn MVC patterns, FXML, effects, transformations, charts, images, canvas, audio and video, DnD, and more. After reading and using Learn JavaFX 8, you'll come away with a comprehensive introduction to the JavaFX APIs as found in the new Java 8 platform. - [Mastering JavaFX 8 Controls](https://www.mhprofessional.com/details.php?isbn=0071833773) - By [Hendrik Ebbers](https://twitter.com/hendrikEbbers)<br/> Deliver state-of-the-art applications with visually stunning UIs. Mastering JavaFX 8 Controls provides clear instructions, detailed examples, and ready-to-use code samples. Find out how to work with the latest JavaFX APIs, configure UI components, automatically generate FXML, build cutting-edge controls, and effectively apply CSS styling. Troubleshooting, tuning, and deployment are also covered in this Oracle Press guide. - [Pro Java 9 Games Development Leveraging the JavaFX APIs](https://www.apress.com/gp/book/9781484209745) - By Wallace Jackson<br/> Use Java 9 and JavaFX 9 to write 3D games for the latest consumer electronics devices. - [Pro JavaFX 9 A Definitive Guide to Building Desktop, Mobile, and Embedded Java Clients](https://www.apress.com/gp/book/9781484230411) - By [Johan Vos](https://twitter.com/johanvos) , [Weiqi Gao](https://twitter.com/weiqigao) , [James Weaver](https://twitter.com/JavaFXpert) , [Stephen Chin](https://twitter.com/steveonjava) , [Dean Iverson](https://twitter.com/deanriverson)<br/> The expert authors cover the new more modular JavaFX 9 APIs, development tools, and best practices and provide code examples that explore the exciting new features provided with JavaFX 9, part of Oracle's new Java 9 release. ## Blogs and Sites - [falkhausen.de](http://www.falkhausen.de/JavaFX/index.html) - Class diagrams for JavaFX by Markus Falkhausen. - [FX Experience](http://fxexperience.com/) - FX Experience has been the premiere site for JavaFX code, posts, and insights since mid-2009, and readership continues to grow every month. You should absolutly follow their weekly links. - [FXAPss](http://fxapps.blogspot.com/) - A JavaFX blog. - [GUI Garage](http://www.guigarage.com/) - Open source UI stuff! - [Harmonic Code](http://harmoniccode.blogspot.de/) - You should see how he's playing with JavaFX! by [Gerrit Grunwald](https://twitter.com/hansolo_). - [JavaFX Daily](http://paper.li/net0pyr/1312275601) - JavaFX Daily Photos, Article and Links by [Michael Heinrichs](http://twitter.com/net0pyr). - [JavaFX Delight](http://www.jensd.de/wordpress/) - [Jens Deters](https://twitter.com/Jerady) blog about Java/JavaFX. - [JPereda's Coding Blog](http://jperedadnr.blogspot.de/) - Outstanding Java/JavaFX Articles by [Josรฉ Pereda](https://twitter.com/JPeredaDnr). - [Kware](http://www.kware.net/) - A blog about JavaFX by Christoph Keimel. - [Pixel Duke](https://www.pixelduke.com) - Several articles on JavaFX from someone who has worked with JavaFX since its first beta release, for example, he was the author of a component that allowed Swing and JavaFX interoperability in the first versions of JavaFX when that was still not possible. The blog owner is a [JavaFX and Swing Freelancer and Consultant](http://www.pixelduke.com) or more generally a Front End Freelancer and Consultant who's also a Software Designer. - [Pixel Perfect](http://dlsc.com/blog/) - You can find good articles about java and specially JavaFX by [Dirk Lemmermann](https://twitter.com/dlemmermann). ## People *These people share good stuff on their twitter accounts. Some of them are Legends, Champions and Rockstars. Follow them on Twitter. Descriptions from Twitter.* * [Andres Almiray](https://twitter.com/aalmiray) - JSR377 Spec lead, Groovy aficionado, Griffon project lead, Basilisk project lead, Java Champion http://manning.com/almiray. * [Alessio Vinerbi](https://twitter.com/Alessio_Vinerbi) - Java and JavaFX Senior software engineer. * [Alexander Casall](https://twitter.com/sialcasa) - interested in JavaFX, iOS, Angular2 development and product ownership. * [Andreas Billmann](https://twitter.com/frosch95) - Java and JavaFX developer. * [Arnaud Nouard](https://twitter.com/In_SideFX) - Play JavaFX, Drums, Keyboard (those with black and white keys!) and with my Kids. * [Bernard Traversat](https://twitter.com/BTraTra) - Java Language, JVM, JavaScript, JDK, JavaFX, Swing/AWT - Sr. Eng Director, Java Platform Group, Oracle. * [Bertrand Goetzmann](https://twitter.com/bgoetzmann) - Java EE architect, fan of Groovy/Grails (trainer), JavaFX, Drupal and Ionic... . * [Bruno Borges](https://twitter.com/brunoborges) - Java Champion, Principal Product Manager for Java at Mirosoft. * [Carl Dea](https://twitter.com/carldea) - Book Author, Blogger, a wannabe GUI guy, JavaFX enthusiast, mobile phones, AI.( He is a Legend!) * [Christian Campo](https://twitter.com/christiancampo) - Committer in multiple Eclipse projects, interested in JavaFX and Cloud Storage. * [Danno Ferrin](https://twitter.com/shemnon) - Java, JavaFX, Gradle, Groovy, Co-founded Griffon. * [David Grieve](https://twitter.com/dsgrieve) - Member of the JavaFX development team at Oracle. Primarily responsible for JavaFX's CSS implementation. * [Dean Iverson](https://twitter.com/deanriverson) - JavaFX Author. * [Delorme Loรฏc](https://twitter.com/delormeloic26) - Junior Java SE/EE developer, UI and mobile application lover (JavaFX, #GluonHQ). * [Dirk Lemmermann](https://twitter.com/dlemmermann) - Senior Java SE / EE software engineer. UI Lover (Swing, JavaFX). * [Felix](https://twitter.com/DeveloperFelix) - Software Developer in Android,Java,JavaFx, Opendata junkie & IOT(Raspberry Pi). * [Gerrit Grunwald](https://twitter.com/hansolo_) - JUG Leader, Java Champion, JavaONE Rockstar, โค๏ธ Java(FX) and IoT, may the force be with you... (He is a Legend!) * [Hendrik Ebbers](https://twitter.com/hendrikEbbers) - JUG Dortmund Lead, Java Champion, JavaOne Rockstar, JavaFX book author, JSR EG member * [James Weaver](https://twitter.com/JavaFXpert) - Java/JavaFX/IoT developer, author and speaker. * [Jasper Potts](https://twitter.com/jasperpotts) - Developer on the JavaFX & Swing teams at Oracle. Working on the new JavaFX Applications, JavaFX UI Controls and Graphics frameworks. * [Jeanette Winzenburg](https://twitter.com/kleopatra_jx) - Java desktop consultant: old-time Swing/X enthusiast, grudging adopter of JavaFX. * [Jens Deters](https://twitter.com/Jerady) - JavaFX, MQTT_fx leader, FontAwesomeFX leader, IoT, docker, dcos, NetBeans Dream Team. * [Johan Vos](https://twitter.com/johanvos) - Java developer, Java Champion, co-founder at Gluon, CTO at LodgON, Using JavaFX and Glassfish, working on Gluon, Java EE, DataFX,... . (He is a Legend!) * [Jonathan Giles](https://twitter.com/JonathanGiles) - UI Controls technical lead in JavaFX team @ Oracle. * [Josรฉ Pereda](https://twitter.com/JPeredaDnr) - PhD, Structural Engineer, love coding, Java & JavaFX, JavaFXPorts, mobile apps, IoT. Software Engineer at http://gluonhq.com/ (He is a Legend!) * [Mark Heckler](https://twitter.com/MkHeck) - Developer Advocate for Pivotal.io. Computer scientist and JavaFX author. * [Michael Heinrichs](https://twitter.com/net0pyr) - Java, Web, JavaFX developer. Interested in agile development and public speaking. * [Michael Hoffer](https://twitter.com/mihosoft) - Computer Scientist, Mathematician, Software Developer, Artist. (He is a Legend!) * [Mohamed Taman](https://twitter.com/_tamanm) - JCP, Java Champions, Hacker, Speaks Java, Enterprise Architect & Software Development Sr. Manager, Mobile/ Web Architect,international speaker, IoT Geek, Author. * [Pedro Duque Vieira](https://www.pixelduke.com) - JavaFX and Swing Freelancer and Consultant or more generally a Front End Freelancer, Consultant and Software Designer specialized in user interfaces, contributor to open source. Owner of [Pixel Duke a JavaFX, Swing and Front End consultancy company](http://www.pixelduke.com). * [Peter Pilgrim](https://twitter.com/peter_pilgrim) - Java EE, JavaFX and Scala software developer. * [Peter Rogge](https://twitter.com/naoghuman) - Java, Java EE, JavaFX, NetBeans, NetBeans RCP, Creativity, Inspiration, Motivation. * [Sean Phillips](https://twitter.com/SeanMiPhillips) - NASA contractor. JavaFX, NetBeans Platform. Develops Deep Space Trajectory Design tools and also JavaFX author. * [Stephen Chin](https://twitter.com/steveonjava) - JavaFX evangelist, author, speaker, and open-source hacker. * [Thierry Wasylczenko](https://twitter.com/twasyl) - Java, JavaFX, Agile, Speaker, RebelLabs author, SlideshowFX leader. * [Tobias Bley](https://twitter.com/tobibley) - Software Developer & graphic designer skills: java, jpro, JavaFX, Swing, JNI, JavaEE... . * [Tom Schindl](https://twitter.com/tomsontom) - Eclipse Committer, [e(fx)clipse](http://www.efxclipse.org/) project lead and CTO at [BestSolution.at](http://bestsolution.at/en/index.html) * [Weiqi Gao](https://twitter.com/weiqigao) - JavaFX Author * [William Antรดnio](https://twitter.com/William_Antonio) - JBoss Support Enginner and JavaFX enthusiast. Java* Blogger. ## Tutorials *Good online resources including free and paid courses to learn JavaFX.* - [Building Your First JavaFX Application](http://www.pluralsight.com/courses/java-se-java-fx-application-building-your-first) - This course will provide you with a quick introduction to basic JavaFX features and help you build your first JavaFX Application. - [code.makery](http://code.makery.ch/library/javafx-8-tutorial/) - Multiple Language Online Site with great materials and examples to teach you JavaFX. - [FXTutorials](https://github.com/AlmasB/FXTutorials) - A wide range of practical YouTube video tutorials focusing on Java/JavaFX. - [JavaFXTutorials](http://www.javafxtutorials.com/) - Online Materials and Examples for learning JavaFX. - [JavaFXTuts](http://javafxtuts.com/javafx-tutorials/) - Complete javafx tutorials for beginners with a lot of examples. - [Jenkov JavaFX](http://tutorials.jenkov.com/javafx/index.html) - Jenkov JavaFX Tutorials and Articles with good examples to demonstrate you how you can use JavaFX Features. - [Lynda JavaFX GUI Development](https://www.lynda.com/Java-tutorials/JavaFX-GUI-Development/466182-2.html) - Learn how to develop graphical user interfaces (GUIs) for enterprise apps with JavaFX. - [TeamTreeHouse Build a JavaFX Application](https://teamtreehouse.com/library/build-a-javafx-application) - Learn JavaFX fundamentals, Event driven application development and Client based application layout. - [TheNewBoston JavaFX](https://www.youtube.com/watch?v=FLkOX4Eez6o&list=PL6gx4Cwl9DGBzfXLWLSYVy8EbTdpGbUIG) - Youtube JavaFX Video Tutorial. It's Simple and it's good place to start JavaFX. - [Udemy Build Outstanding JavaFX](https://www.udemy.com/javafx-gui-programming/) - Udemy Video Tutorial for JavaFX. Build Outstanding Java Apps with JavaFX much faster. Launch a beautiful Java app by the end of the week. Learn smarter Programming with the JavaFX GUI Framework. ## Talks *Interesting talks in conferences like JavaOne, Devoxx and others* - [Creating Amazing Visualization Tools With JavaFX 8 (3D)](https://www.youtube.com/watch?v=xk-YfIdH0_Y) - By [Michael Hoffer](https://twitter.com/mihosoft)<br/> Screencast that covers most topics from JavaOne 2013 Tutorial TUT6705: http://mihosoft.eu/?p=928<br/> JavaFX is a powerful rich-client platform that is ideal for complex visualizations. In this tutorial, you will learn how to create amazing 2-D and 3-D visualization tools such as an interactive function plotter with Java 8 and JavaFX 8. For 2-D plotting, you will learn how to use the powerful charting API that comes with JavaFX. In addition, you will find out how to load 3-D geometries from text files (and a subset of .obj), render movies from JavaFX 3D via its snapshot functionality, and use the ray picking API for retrieving detailed information on parts of 3-D visualizations. To create nice-looking applications, the tutorial utilizes open source controls from the JFXtras project (jfxtras.org). - [DataFX: The Best Way to Get Real-World Data into Your JavaFX Application](https://www.youtube.com/watch?v=EN4fo6x0DcQ) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers) and [Johan Vos](https://twitter.com/johanvos)<br/> The real value in most client-oriented business applications is the data sitting on remote servers and cloud systems. Unfortunately, retrieving and displaying this data is an exercise left to the developer, and it must be done (correctly!) before end users can interact with it. Fortunately, the open source DataFX framework aims to simplify this by enabling JavaFX developers to easily retrieve data from a variety of sources in several formats and rapidly integrate it with JavaFX components (such as TableView), using typical JavaFX patterns. This session introduces the free and open source DataFX project, gives practical advice for using it, and provides insight into future plans for this project. - [DataFX: From External Data to a UI Flow and Back](https://www.youtube.com/watch?v=q65436KIuJ0) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers) and [Johan Vos](https://twitter.com/johanvos)<br/>The open source project DataFX 8 builds on the core principle of DataFX 2: make it easy for JavaFX developers to retrieve external data (using REST calls, database systems, or custom methods) and visualize this data in JavaFX controls. Using DataFX, you can populate UI controls by using the most-common protocols, including REST, SSE, or WebSocket. Apart from retrieving data, the Flow component in DataFX enables developers to describe different flows between UI components and to inject data models into the flows. This session shows how the different DataFX components make it easy to manage external data by using well-known Java technologies. - [Enterprise JavaFX](https://www.youtube.com/watch?v=5yk6d8vjNE4) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers)<br/> The talks shows several APIs and technologies that usefull to create JavaFX applications that communicate with a server - [Java on Mobile is a thing... and it's really good!](https://www.youtube.com/watch?v=oUMcWxvamWs) - by [Johan Vos](https://twitter.com/johanvos)<br/> In this session, we show how to use your favourite IDE to write a Java Client application, and how to use that same IDE to create native applications that can be uploaded to the different appstores. These native applications use exactly the same code as a Java desktop application. We talk about the status of JavaFX on Mobile, and about the options for running Java code on mobile devices (e.g. Dalvik/ART, RoboVM AOT, OpenJDK with the Mobile OpenJDK project). - [Letโ€™s Get Wet! AquaFX and Best Practices for Skinning JavaFX Controls](https://www.youtube.com/watch?v=ucvdYGLWLT0) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers) and [Claudine Zillmann](https://twitter.com/etteClaudette)<br/> JavaFX offers a wide range of default controls for creating cool and great applications, from business to entertainment use cases. Because JavaFX is a multiplatform UI framework that can be used mainly on desktop-based platforms and embedded devices, a cross-platform skin named Caspian is provided by JavaFX. As of Java 8, Modena will be a official second cross-platform skin for JavaFX, but some applications and developers have a definite need for native or custom skins for their controls and applications. This session points out how to create custom skins for JavaFX controls. You will learn that with AquaFX, this custom skin can even feel like a native one. - [Test-Driven Development with JavaFX](https://www.youtube.com/watch?v=PaB0t8NP3Oc&t=1479s) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers) and [Sven Ruppert](https://twitter.com/SvenRuppert)<br/> This session presents existing testing tools and frameworks in their current stage of development. It compares the capabilities and the kinds of impacts of existing projects. The presentation pays particular attention to questions such as How can a cross-platform GUI test be created?โ€™With many legacy (Java Swingโ€“based) applications in need of migrating to the new JavaFX 8 platform, it is imperative for GUI code to be testable. The industry needs better strategies and tools for efficient migration from Swing to JavaFX 8. - [The JavaFX Community and Ecosystem](https://www.youtube.com/watch?v=MVIKZyqpnMY) - by [Hendrik Ebbers](https://twitter.com/hendrikEbbers) and Alexander Casall<br/> Do you want to start working with JavaFX but donโ€™t know where you can find all the cool tutorials and open source APIs? This session is the perfect place to be! Leading up to the Java 8 release, a huge ecosystem with a lot of good tutorials and open source frameworks surrounds JavaFX. The community is getting bigger and bigger. The presentation introduces some of the most important parts of the JavaFX ecosystem such as third-party frameworks and popular knowledgebases and illustrates the functionality and synergy effects between the libraries with a live coding session. The session ends with real-world applications demonstrating the techniques and APIs discussed earlier. ## Slides *Useful slides from Slideshare* - [JavaFX 10 things I love about you](http://www.slideshare.net/alexandercasall/javafx-10-things-i-love-about-you). An Introduction to JavaFX. - [JavaFX Pitfalls](http://www.slideshare.net/alexandercasall/javafx-pitfalls). Tips and tricks regarding JavaFX. - [The JavaFX Community and Ecosystem](http://www.slideshare.net/alexandercasall?utm_campaign=profiletracking&utm_medium=sssite&utm_source=ssslideview). JavaOne talk about the Ecosystem in the year 2014. - [The JavaFX Ecosystem](http://www.slideshare.net/aalmiray/the-javafx-ecosystem-63538844). A collection of Open Source libraries for building JavaFX applications. ## Articles *Interesting Articles about JavaFX* - [Building a JavaFX Search Bar](https://vocabhunter.github.io/2017/01/15/Search-Bar.html) - How to add a search bar to your JavaFX user interface. The article is based on a real application and includes links to all of the source code. - [Dependency Injection in JavaFX](https://vocabhunter.github.io/2016/11/13/JavaFX-Dependency-Injection.html) - A guide to implementing Dependency Injection in a JavaFX application. - [How JavaFX was used to build a desktop application](https://medium.com/techking/how-javafx-was-used-to-build-a-desktop-application-7d4c680d8dc) - A look at some of the features of JavaFX and how they were used in building an application. The article includes links to all of the source code on GitHub. - [JavaFX 8 Refcard](https://dzone.com/refcardz/javafx-8-1) - Gives you what you need to start using the powerful JavaFX 8 UI and graphics tool with code snippets and visual examples of shapes and controls. - [JavaFX Refcard](https://dzone.com/refcardz/getting-started-javafx) - Gets you started with JavaFX, which makes it easier to build better RIAs with graphics, animation, and media. - [User Interface Testing with TestFX](https://vocabhunter.github.io/2016/07/27/TestFX.html) - A guide to using TestFX to automate JavaFX user interface testing. - [Using the Java Packager with JDK 11](https://medium.com/@adam_carroll/java-packager-with-jdk11-31b3d620f4a8) - How to create installable bundles for your JavaFX application for Mac, Linux and Windows using the Java Packager on JDK 11. ## Real World Examples *Real World Examples of JavaFX and Applications* - [20 real world examples on JAXenter](https://jaxenter.com/20-javafx-real-world-applications-123653.html) - [AsciidocFX](http://asciidocfx.com/) - Asciidoc FX is a book/document editor to build PDF, Epub, Mobi and HTML books, documents and slides. AsciidocFX is also a winner of [Dukeโ€™s Choice Award 2015](https://www.oracle.com/corporate/pressrelease/dukes-award-102815.html). - [binjr](https://github.com/binjr/binjr) - binjr is a time series data browser; it renders time series data produced by other applications as dynamically editable charts and provides many features to navigate through the data in a natural and fluent fashion (drag & drop, zoom, history, detacheable tabs, advanced time-range picker). - [Boomega](https://github.com/Dansoftowner/Boomega) - A modern book explorer & catalog application - [Bounding Box Editor](https://github.com/mfl28/BoundingBoxEditor) - A multi-platform JavaFX image annotation application to create and edit ground-truth labels for object detection and segmentation machine learning models. - [Deep Space Trajectory Explorer](https://www.youtube.com/watch?v=MotQ1PC1xT8) - This is an application used by NASA. This tool allows a trajectory designer to identify, compare and export deep space 3 body system trajectories. - [Everest](https://github.com/RohitAwate/Everest) - Everest (formerly RESTaurant) is an upcoming REST API testing client written in JavaFX. Looks like Postman but writen in Java. - [FX2048](https://github.com/brunoborges/fx2048) - The game 2048 built using JavaFX and Java 11. - [FXDesktopSearch](https://github.com/mirkosertic/FXDesktopSearch) - FXDesktopSearch is a Java and JavaFX based Desktop Search Application. It crawls a configured set of directories and allows you to do fulltext search with different languages support on the content. - [JStackFX](https://github.com/twasyl/jstackfx) - It is not an easy task to analyse thread dumps as files generated by the jstack tool provides raw text files. JStackFX will help you to do that with a nice FX GUI. - [Modellus](https://www.pixelduke.com/projects#modellus) - Modellus is a freely available Swing and JavaFX app. It was the first application to integrate both Swing and JavaFX together in a single app (back then using a custom made solution - JXScene - not available at the time). It is used all over the world, specially in High School and Universities, and has appeared in several published scientific papers. Samples range from Physics to Mathematics, going through Mechanics, Chemistry, Statistics, Algebra, Geometry, among others. - [Musicott](http://octaviospain.github.io/Musicott/) - Musicott is an application that manages and plays music files. Coded in Java 8 with JavaFX. - [PDFsam Basic](https://pdfsam.org/) - PDFsam Basic is an opensource JavaFX application to merge, split, extract pages, rotate and mix PDF files. - [PrettyZoo](https://github.com/vran-dev/PrettyZoo) - Pretty nice Zookeeper GUI created by JavaFX & Apache Curator - [Recaf](https://github.com/Col-E/Recaf) - An easy to use modern Java bytecode editor. - [ResumeFX](https://github.com/TangoraBox/ResumeFX) - ResumeFX renders a JavaFX view of .json file that follows [jsonresume.org](https://jsonresume.org) standard and has the necessary configuration to be embedded in the web browser thanks to [JPro](https://www.jpro.one). - [SkedPal](https://www.skedpal.com/) - SkedPalโ„ข combines the best elements of creativity and structure to optimize your time and productivity. - [VocabHunter](https://vocabhunter.github.io/) - VocabHunter is a system to help learners of foreign languages. - [WavesFX](https://github.com/wavesfx/wavesfx) - A community-driven Waves desktop wallet which offers users multi-network and multi-address functionality. - [XR3Player](https://github.com/goxr3plus/XR3Player) - XR3Player is an opensource Java/JavaFX Media Player, WebBrowser, Media File Organizer, aiming to be something more than a Media Player. ---- ## Contribute Contributions are always welcome!
146
JWT auth service using Spring Boot, Springย Security and MySQL
# Spring Boot JWT ![](https://img.shields.io/badge/build-success-brightgreen.svg) # Stack ![](https://img.shields.io/badge/java_8-โœ“-blue.svg) ![](https://img.shields.io/badge/spring_boot-โœ“-blue.svg) ![](https://img.shields.io/badge/mysql-โœ“-blue.svg) ![](https://img.shields.io/badge/jwt-โœ“-blue.svg) ![](https://img.shields.io/badge/swagger_2-โœ“-blue.svg) *** <h3 align="center">Please help this repo with a :star: if you find it useful! :blush:</h3> *** # File structure ``` spring-boot-jwt/ โ”‚ โ”œโ”€โ”€ src/main/java/ โ”‚ โ””โ”€โ”€ murraco โ”‚ โ”œโ”€โ”€ configuration โ”‚ โ”‚ โ””โ”€โ”€ SwaggerConfig.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ controller โ”‚ โ”‚ โ””โ”€โ”€ UserController.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ dto โ”‚ โ”‚ โ”œโ”€โ”€ UserDataDTO.java โ”‚ โ”‚ โ””โ”€โ”€ UserResponseDTO.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ exception โ”‚ โ”‚ โ”œโ”€โ”€ CustomException.java โ”‚ โ”‚ โ””โ”€โ”€ GlobalExceptionController.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ model โ”‚ โ”‚ โ”œโ”€โ”€ AppUserRole.java โ”‚ โ”‚ โ””โ”€โ”€ AppUser.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ repository โ”‚ โ”‚ โ””โ”€โ”€ UserRepository.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ security โ”‚ โ”‚ โ”œโ”€โ”€ JwtTokenFilter.java โ”‚ โ”‚ โ”œโ”€โ”€ JwtTokenFilterConfigurer.java โ”‚ โ”‚ โ”œโ”€โ”€ JwtTokenProvider.java โ”‚ โ”‚ โ”œโ”€โ”€ MyUserDetails.java โ”‚ โ”‚ โ””โ”€โ”€ WebSecurityConfig.java โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ service โ”‚ โ”‚ โ””โ”€โ”€ UserService.java โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ JwtAuthServiceApp.java โ”‚ โ”œโ”€โ”€ src/main/resources/ โ”‚ โ””โ”€โ”€ application.yml โ”‚ โ”œโ”€โ”€ .gitignore โ”œโ”€โ”€ LICENSE โ”œโ”€โ”€ mvnw/mvnw.cmd โ”œโ”€โ”€ README.md โ””โ”€โ”€ pom.xml ``` # Introduction (https://jwt.io) Just to throw some background in, we have a wonderful introduction, courtesy of **jwt.io**! Letโ€™s take a look: ## What is JSON Web Token? JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA. Let's explain some concepts of this definition further. **Compact**: Because of their smaller size, JWTs can be sent through a URL, POST parameter, or inside an HTTP header. Additionally, the smaller size means transmission is fast. **Self-contained**: The payload contains all the required information about the user, avoiding the need to query the database more than once. ## When should you use JSON Web Tokens? Here are some scenarios where JSON Web Tokens are useful: **Authentication**: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. **Information Exchange**: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signedโ€”for example, using public/private key pairsโ€”you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with. ## What is the JSON Web Token structure? JSON Web Tokens consist of three parts separated by dots **(.)**, which are: 1. Header 2. Payload 3. Signature Therefore, a JWT typically looks like the following. `xxxxx`.`yyyyy`.`zzzzz` Let's break down the different parts. **Header** The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA. For example: ```json { "alg": "HS256", "typ": "JWT" } ``` Then, this JSON is Base64Url encoded to form the first part of the JWT. **Payload** The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: reserved, public, and private claims. - **Reserved claims**: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others. > Notice that the claim names are only three characters long as JWT is meant to be compact. - **Public claims**: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace. - **Private claims**: These are the custom claims created to share information between parties that agree on using them. An example of payload could be: ```json { "sub": "1234567890", "name": "John Doe", "admin": true } ``` The payload is then Base64Url encoded to form the second part of the JSON Web Token. **Signature** To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way: ``` HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret) ``` The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way. Putting all together The output is three Base64 strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML. The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret. Encoded JWT ![](https://camo.githubusercontent.com/a56953523c443d6a97204adc5e39b4b8c195b453/68747470733a2f2f63646e2e61757468302e636f6d2f636f6e74656e742f6a77742f656e636f6465642d6a7774332e706e67) ## How do JSON Web Tokens work? In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie. Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following: `Authorization: Bearer <token>` This is a stateless authentication mechanism as the user state is never saved in server memory. The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources. As JWTs are self-contained, all the necessary information is there, reducing the need to query the database multiple times. This allows you to fully rely on data APIs that are stateless and even make requests to downstream services. It doesn't matter which domains are serving your APIs, so Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies. The following diagram shows this process: ![](https://camo.githubusercontent.com/5871e9f0234542cd89bab9b9c100b20c9eb5b789/68747470733a2f2f63646e2e61757468302e636f6d2f636f6e74656e742f6a77742f6a77742d6469616772616d2e706e67) # JWT Authentication Summary Token based authentication schema's became immensely popular in recent times, as they provide important benefits when compared to sessions/cookies: - CORS - No need for CSRF protection - Better integration with mobile - Reduced load on authorization server - No need for distributed session store Some trade-offs have to be made with this approach: - More vulnerable to XSS attacks - Access token can contain outdated authorization claims (e.g when some of the user privileges are revoked) - Access tokens can grow in size in case of increased number of claims - File download API can be tricky to implement - True statelessness and revocation are mutually exclusive **JWT Authentication flow is very simple** 1. User obtains Refresh and Access tokens by providing credentials to the Authorization server 2. User sends Access token with each request to access protected API resource 3. Access token is signed and contains user identity (e.g. user id) and authorization claims. It's important to note that authorization claims will be included with the Access token. Why is this important? Well, let's say that authorization claims (e.g user privileges in the database) are changed during the life time of Access token. Those changes will not become effective until new Access token is issued. In most cases this is not big issue, because Access tokens are short-lived. Otherwise go with the opaque token pattern. # Implementation Details Let's see how can we implement the JWT token based authentication using Java and Spring, while trying to reuse the Spring security default behavior where we can. The Spring Security framework comes with plug-in classes that already deal with authorization mechanisms such as: session cookies, HTTP Basic, and HTTP Digest. Nevertheless, it lacks from native support for JWT, and we need to get our hands dirty to make it work. ## H2 DB This demo is currently using an H2 database called **test_db** so you can run it quickly and out-of-the-box without much configuration. If you want to connect to a different database you have to specify the connection in the `application.yml` file inside the resource directory. Note that `hibernate.hbm2ddl.auto=create-drop` will drop and create a clean database each time we deploy (you may want to change it if you are using this in a real project). Here's the example from the project, see how easily you can swap comments on the `url` and `dialect` properties to use your own MySQL database: ```yml spring: datasource: url: jdbc:h2:mem:test_db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE # url: jdbc:mysql://localhost:3306/user_db username: root password: root tomcat: max-wait: 20000 max-active: 50 max-idle: 20 min-idle: 15 jpa: hibernate: ddl-auto: create-drop properties: hibernate: dialect: org.hibernate.dialect.H2Dialect # dialect: org.hibernate.dialect.MySQL8Dialect format_sql: true id: new_generator_mappings: false ``` ## Core Code 1. `JwtTokenFilter` 2. `JwtTokenFilterConfigurer` 3. `JwtTokenProvider` 4. `MyUserDetails` 5. `WebSecurityConfig` **JwtTokenFilter** The `JwtTokenFilter` filter is applied to each API (`/**`) with exception of the signin token endpoint (`/users/signin`) and singup endpoint (`/users/signup`). This filter has the following responsibilities: 1. Check for access token in Authorization header. If Access token is found in the header, delegate authentication to `JwtTokenProvider` otherwise throw authentication exception 2. Invokes success or failure strategies based on the outcome of authentication process performed by JwtTokenProvider Please ensure that `chain.doFilter(request, response)` is invoked upon successful authentication. You want processing of the request to advance to the next filter, because very last one filter *FilterSecurityInterceptor#doFilter* is responsible to actually invoke method in your controller that is handling requested API resource. ```java String token = jwtTokenProvider.resolveToken((HttpServletRequest) req); if (token != null && jwtTokenProvider.validateToken(token)) { Authentication auth = jwtTokenProvider.getAuthentication(token); SecurityContextHolder.getContext().setAuthentication(auth); } filterChain.doFilter(req, res); ``` **JwtTokenFilterConfigurer** Adds the `JwtTokenFilter` to the `DefaultSecurityFilterChain` of spring boot security. ```java JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider); http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class); ``` **JwtTokenProvider** The `JwtTokenProvider` has the following responsibilities: 1. Verify the access token's signature 2. Extract identity and authorization claims from Access token and use them to create UserContext 3. If Access token is malformed, expired or simply if token is not signed with the appropriate signing key Authentication exception will be thrown **MyUserDetails** Implements `UserDetailsService` in order to define our own custom *loadUserbyUsername* function. The `UserDetailsService` interface is used to retrieve user-related data. It has one method named *loadUserByUsername* which finds a user entity based on the username and can be overridden to customize the process of finding the user. It is used by the `DaoAuthenticationProvider` to load details about the user during authentication. **WebSecurityConfig** The `WebSecurityConfig` class extends `WebSecurityConfigurerAdapter` to provide custom security configuration. Following beans are configured and instantiated in this class: 1. `JwtTokenFilter` 3. `PasswordEncoder` Also, inside `WebSecurityConfig#configure(HttpSecurity http)` method we'll configure patterns to define protected/unprotected API endpoints. Please note that we have disabled CSRF protection because we are not using Cookies. ```java // Disable CSRF (cross site request forgery) http.csrf().disable(); // No session will be created or used by spring security http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Entry points http.authorizeRequests()// .antMatchers("/users/signin").permitAll()// .antMatchers("/users/signup").permitAll()// // Disallow everything else.. .anyRequest().authenticated(); // If a user try to access a resource without having enough permissions http.exceptionHandling().accessDeniedPage("/login"); // Apply JWT http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider)); // Optional, if you want to test the API from a browser // http.httpBasic(); ``` # How to use this code? 1. Make sure you have [Java 8](https://www.java.com/download/) and [Maven](https://maven.apache.org) installed 2. Fork this repository and clone it ``` $ git clone https://github.com/<your-user>/spring-boot-jwt ``` 3. Navigate into the folder ``` $ cd spring-boot-jwt ``` 4. Install dependencies ``` $ mvn install ``` 5. Run the project ``` $ mvn spring-boot:run ``` 6. Navigate to `http://localhost:8080/swagger-ui.html` in your browser to check everything is working correctly. You can change the default port in the `application.yml` file ```yml server: port: 8080 ``` 7. Make a GET request to `/users/me` to check you're not authenticated. You should receive a response with a `403` with an `Access Denied` message since you haven't set your valid JWT token yet ``` $ curl -X GET http://localhost:8080/users/me ``` 8. Make a POST request to `/users/signin` with the default admin user we programatically created to get a valid JWT token ``` $ curl -X POST 'http://localhost:8080/users/signin?username=admin&password=admin' ``` 9. Add the JWT token as a Header parameter and make the initial GET request to `/users/me` again ``` $ curl -X GET http://localhost:8080/users/me -H 'Authorization: Bearer <JWT_TOKEN>' ``` 10. And that's it, congrats! You should get a similar response to this one, meaning that you're now authenticated ```javascript { "id": 1, "username": "admin", "email": "[email protected]", "roles": [ "ROLE_ADMIN" ] } ``` # Contribution - Report issues - Open pull request with improvements - Spread the word - Reach out to me directly at <[email protected]>
147
Yet Another Validation for Java (A lambda based type safe validation framework)
## YAVI (*Y*et *A*nother *V*al*I*dation) [![Apache 2.0](https://img.shields.io/github/license/making/yavi.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/am.ik.yavi/yavi/badge.svg)](https://maven-badges.herokuapp.com/maven-central/am.ik.yavi/yavi) [![Javadocs](https://www.javadoc.io/badge/am.ik.yavi/yavi.svg)](https://www.javadoc.io/doc/am.ik.yavi/yavi) [![Actions Status](https://github.com/making/yavi/workflows/CI/badge.svg)](https://github.com/making/yavi/actions) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/4232a408001840e994e707ff6a7d4e04)](https://app.codacy.com/manual/making/yavi?utm_source=github.com&utm_medium=referral&utm_content=making/yavi&utm_campaign=Badge_Grade_Dashboard) [![Codacy Badge](https://api.codacy.com/project/badge/Coverage/8ae26f1168ad479ebea8f1f6e6329ac5)](https://www.codacy.com/manual/making/yavi?utm_source=github.com&utm_medium=referral&utm_content=making/yavi&utm_campaign=Badge_Coverage) ![YAVI Logo](https://user-images.githubusercontent.com/106908/120071055-66770380-c0c8-11eb-83f1-d7eff04bad54.png) YAVI (pronounced jษ‘-vฮฌษช) is a lambda based type safe validation for Java. ### Why YAVI? YAVI sounds as same as a Japanese slang "YABAI (ใƒคใƒใ‚ค)" that means awesome or awful depending on the context (like "Crazy"). If you use YAVI, you will surely understand that it means the former. The concepts are * No reflection! * No (runtime) annotation! * Not only Java Beans! * Zero dependency! If you are not a fan of [Bean Validation](https://beanvalidation.org/), YAVI will be an awesome alternative. YAVI has the following features: * Type-safe constraints, unsupported constraints cannot be applied to the wrong type * Fluent and intuitive API * Constraints on any object. Java Beans, [Records](https://openjdk.java.net/jeps/395), [Protocol Buffers](https://developers.google.com/protocol-buffers), [Immutables](https://immutables.github.io/) and anything else. * Lots of powerful built-in constraints * Easy custom constraints * Validation for groups, conditional validation * Validation for arguments before creating an object * Support for API and combination of validation results and validators that incorporate the concept of functional programming See [the reference documentation](https://yavi.ik.am) for details. ### Presentations * 2021-07-01 YAVIใฎ็ดนไป‹ (Japanese) [[Deck](https://docs.google.com/presentation/d/1aw5cXqTxvMbBvTUU4TiF2oTUkG8orDujA5IRQGtIDiw/edit#slide=id.p)] [[Recording](https://www.youtube.com/watch?v=o0-u6QSBlv8)] ### Getting Started > This content is derived from https://hibernate.org/validator/documentation/getting-started/ Welcome to YAVI. The following paragraphs will guide you through the initial steps required to integrate YAVI into your application. #### Prerequisites * [Java Runtime](http://www.oracle.com/technetwork/java/index.html) >= 8 * [Apache Maven](http://maven.apache.org/) #### Project set up In order to use YAVI within a Maven project, simply add the following dependency to your `pom.xml`: ```xml <dependency> <groupId>am.ik.yavi</groupId> <artifactId>yavi</artifactId> <version>0.12.0</version> </dependency> ``` This tutorial uses JUnit 5 and AssertJ. Add the following dependencies as needed: ```xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.9.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.23.1</version> <scope>test</scope> </dependency> ``` #### Applying constraints Letโ€™s dive into an example to see how to apply constraints: Create `src/main/java/com/example/Car.java` and write the following code. ```java package com.example; import am.ik.yavi.builder.ValidatorBuilder; import am.ik.yavi.core.Validator; public class Car { private final String manufacturer; private final String licensePlate; private final int seatCount; public static final Validator<Car> validator = ValidatorBuilder.<Car>of() .constraint(Car::getManufacturer, "manufacturer", c -> c.notNull()) .constraint(Car::getLicensePlate, "licensePlate", c -> c.notNull().greaterThanOrEqual(2).lessThanOrEqual(14)) .constraint(Car::getSeatCount, "seatCount", c -> c.greaterThanOrEqual(2)) .build(); public Car(String manufacturer, String licencePlate, int seatCount) { this.manufacturer = manufacturer; this.licensePlate = licencePlate; this.seatCount = seatCount; } public String getManufacturer() { return manufacturer; } public String getLicensePlate() { return licensePlate; } public int getSeatCount() { return seatCount; } } ``` The `ValidatorBuilder.constraint` is used to declare the constraints which should be applied to the return values of getter for the `Car` instance: * `manufacturer` must never be null * `licensePlate` must never be null and must be between 2 and 14 characters long * `seatCount` must be at least 2 > You can find [the complete source code](https://github.com/making/gs-yavi) on GitHub. #### Validating constraints To perform a validation of these constraints, you use a `Validator` instance. To demonstrate this, letโ€™s have a look at a simple unit test: Create `src/test/java/com/example/CarTest.java` and write the following code. ```java package com.example; import am.ik.yavi.core.ConstraintViolations; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class CarTest { @Test void manufacturerIsNull() { final Car car = new Car(null, "DD-AB-123", 4); final ConstraintViolations violations = Car.validator.validate(car); assertThat(violations.isValid()).isFalse(); assertThat(violations).hasSize(1); assertThat(violations.get(0).message()).isEqualTo("\"manufacturer\" must not be null"); } @Test void licensePlateTooShort() { final Car car = new Car("Morris", "D", 4); final ConstraintViolations violations = Car.validator.validate(car); assertThat(violations.isValid()).isFalse(); assertThat(violations).hasSize(1); assertThat(violations.get(0).message()).isEqualTo("The size of \"licensePlate\" must be greater than or equal to 2. The given size is 1"); } @Test void seatCountTooLow() { final Car car = new Car("Morris", "DD-AB-123", 1); final ConstraintViolations violations = Car.validator.validate(car); assertThat(violations.isValid()).isFalse(); assertThat(violations).hasSize(1); assertThat(violations.get(0).message()).isEqualTo("\"seatCount\" must be greater than or equal to 2"); } @Test void carIsValid() { final Car car = new Car("Morris", "DD-AB-123", 2); final ConstraintViolations violations = Car.validator.validate(car); assertThat(violations.isValid()).isTrue(); assertThat(violations).hasSize(0); } } ``` `Validator` instances are thread-safe and may be reused multiple times. The `validate()` method returns a `ConstraintViolations` instance, which you can iterate in order to see which validation errors occurred. The first three test methods show some expected constraint violations: * The `notNull()` constraint on `manufacturer` is violated in `manufacturerIsNull()` * The `greaterThanOrEqual(int)` constraint on `licensePlate` is violated in `licensePlateTooShort()` * The `greaterThanOrEqual(int)` constraint on `seatCount` is violated in `seatCountTooLow()` If the object validates successfully, `validate()` returns an empty `ConstraintViolations` as you can see in `carIsValid()`. You can also check if the validation was successful with the `ConstraintViolations.isValid` method. #### Where to go next? That concludes the 5 minutes tour through the world of YAVI. If you want a more complete introduction, it is recommended to read "[Using YAVI](https://yavi.ik.am/#using-yavi)" in the reference document. ### Required * Java 8+ ### License Licensed under the Apache License, Version 2.0.
148
๐ŸŒŸ An universal React isomorphic boilerplate for building server-side render web app.
# React Isomorphic Boilerplate An universal React isomorphic boilerplate for building server-side render web app. [![dependencies Status](https://david-dm.org/chikara-chan/react-isomorphic-boilerplate/status.svg)](https://david-dm.org/chikara-chan/react-isomorphic-boilerplate) [![devDependencies Status](https://david-dm.org/chikara-chan/react-isomorphic-boilerplate/dev-status.svg)](https://david-dm.org/chikara-chan/react-isomorphic-boilerplate?type=dev) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/chikara-chan/react-isomorphic-boilerplate/pulls) [![npm](https://img.shields.io/npm/l/express.svg)](https://github.com/chikara-chan/react-isomorphic-boilerplate/blob/master/LICENSE) ## Introduction This repository is an universal React isomorphic boilerplate for developer to quickly build a super fast and powerful web app that can be rendered both on the client and on the server using the most cutting-edge technology. Compared to others, this boilerplate has more pithily and more elegant configuration file based on environment variables, one for development, one for production. In addition, the directory structure is organized corresponding to mvc principle aim at the best practice. ## Technology Stack - [React](https://github.com/facebook/react) - [React Router](https://github.com/ReactTraining/react-router) - [Redux](https://github.com/reactjs/redux) - [Redux+](https://github.com/xgrommx/awesome-redux) - [Sass](https://github.com/sass/sass) - [PostCSS](https://github.com/postcss/postcss) - [CSS Modules](https://github.com/css-modules/css-modules) - [Koa](https://github.com/koajs/koa) - [Koa+](https://github.com/koajs) - [Webpack](https://github.com/webpack/webpack) - [Webpack+](https://webpack.js.org/loaders/) - [Babel](https://github.com/babel/babel) - [Babel+](http://babeljs.io/docs/plugins/) - [ESLint](https://github.com/eslint/eslint) - [Hot Module Replacement](https://webpack.github.io/docs/hot-module-replacement.html) - [Code Splitting](https://webpack.github.io/docs/code-splitting.html) - ~~Database~~ - ~~Test Framework~~ ## Getting Started - Require Node.js v6 or later. - `npm install` to install dependencies and devDependencies. - `npm run dev` to start up the development environment. - `npm run build` to compile and bundle the client and server files. - `npm start` to deploy the production server. ## What's included ``` react-isomorphic-boilerplate/ // root directory โ”œโ”€โ”€ build/ // webpack config directory โ”‚ โ”œโ”€โ”€ webpack.dev.config.js // config for webpack when run development bundle โ”‚ โ””โ”€โ”€ webpack.prod.config.js // config for webpack when run production bundle โ”œโ”€โ”€ client/ // client directory โ”‚ โ”œโ”€โ”€ about/ // `about` module โ”‚ โ”œโ”€โ”€ common/ // `common` module โ”‚ โ”œโ”€โ”€ home/ // `home` module โ”‚ โ”œโ”€โ”€ shared/ // shared module โ”‚ โ”œโ”€โ”€ explore/ // `explore` module โ”‚ โ”œโ”€โ”€ index.js // client entry file โ”‚ โ””โ”€โ”€ routes.js // client route config โ”œโ”€โ”€ dist/ // bundle output directory โ”‚ โ”œโ”€โ”€ client/ // the client side output directory โ”‚ โ””โ”€โ”€ server/ // the server side output directory โ”œโ”€โ”€ server/ // server directory โ”‚ โ”œโ”€โ”€ controllers/ // controllers in server โ”‚ โ”œโ”€โ”€ middlewares/ // custom middlewares in server โ”‚ โ”œโ”€โ”€ models/ // models in server โ”‚ โ”œโ”€โ”€ routes/ // routes in server โ”‚ โ”œโ”€โ”€ app.js // create koa instance in server โ”‚ โ”œโ”€โ”€ server.dev.js // entry file in development mode โ”‚ โ””โ”€โ”€ server.prod.js // entry file in production mode โ”œโ”€โ”€ views/ // views directory โ”‚ โ”œโ”€โ”€ dev/ // output files generated by tpl in development mode โ”‚ โ”œโ”€โ”€ prod/ // output files generated by tpl in production mode โ”‚ โ””โ”€โ”€ tpl // templates injected by html-webpack-plugin โ”œโ”€โ”€ .editorconfig // uniform the text editor behavior โ”œโ”€โ”€ .eslintignore // which paths should be omitted from linting โ”œโ”€โ”€ .eslintrc.json // specific rules for eslint โ”œโ”€โ”€ .gitattributes // uniform the new line perform behavior โ”œโ”€โ”€ .gitignore // ignore the specific files when using git โ”œโ”€โ”€ LICENSE // license information โ”œโ”€โ”€ package.json // npm entry file โ”œโ”€โ”€ README.md // just what you see now โ””โ”€โ”€ yarn.lock // lock file autogenerated by yarn ``` ## Why Isomorphic #### SEO An application that can only run in the client-side cannot serve HTML to crawlers, so it will have poor [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization) by default. Web crawlers function by making a request to a web server and interpreting the result. but if the server returns a blank page, itโ€™s not of much value. There are workarounds, but not without jumping through some hoops. #### Performance By the same token, if the server doesnโ€™t render a full page of HTML but instead waits for client-side JavaScript to do so, users will experience a few critical seconds of blank page or loading spinner before seeing the content on the page. There are plenty of studies showing the drastic effect a slow site has on users, and thus revenue. #### Maintainability While the ideal case can lead to a nice, clean separation of concerns, inevitably some bits of application logic or view logic end up duplicated between client and server, often in different languages. Common examples are date and currency formatting, form validations, and routing logic. This makes maintenance a nightmare, especially for more complex apps. ## Problem exists yet #### [FOUC](https://www.google.com.hk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0ahUKEwimhPqTrofRAhXHkJQKHTEYCfMQFggjMAE&url=https%3a%2f%2fen%2ewikipedia%2eorg%2fwiki%2fFlash_of_unstyled_content&usg=AFQjCNGjAnNtZtjPb5oLsT9Wlf9az7hXTw) It happens when run in development mode. This is caused by deprecated using [extract-text-webpack-plugin](https://github.com/webpack/extract-text-webpack-plugin) in development for getting a seamless hmr experience.(Why deprecated? See this [Issue](https://github.com/webpack/extract-text-webpack-plugin/issues/30)) If you are not an OCD, go ahead, ignore it. #### Mismatch It happens also when run in development mode. This is caused by when you update the react component code and reload the page, the markup generated mismatches that on server render. However, once you restart the server, the checksum will be valid. So it is harmless, ignore it also. ## Links [http://www.jianshu.com/p/0ecd727107bb](http://www.jianshu.com/p/0ecd727107bb) ## License [MIT](https://github.com/chikara-chan/react-isomorphic-boilerplate/blob/master/LICENSE)
149
๐Ÿ“š Study guide and introduction to the modern front end stack.
Grab Front End Guide == [![Front End Developer Desk](images/desk.png)](https://dribbble.com/shots/3577639-Isometric-Developer-Desk) _Credits: [Illustration](https://dribbble.com/shots/3577639-Isometric-Developer-Desk) by [@yangheng](https://dribbble.com/yangheng)_ _This guide has been cross-posted on [Free Code Camp](https://medium.freecodecamp.com/grabs-front-end-guide-for-large-teams-484d4033cc41)._ [Grab](https://www.grab.com) is Southeast Asia (SEA)'s leading transportation platform and our mission is to drive SEA forward, leveraging on the latest technology and the talented people we have in the company. As of May 2017, we handle [2.3 million rides daily](https://www.bloomberg.com/news/videos/2017-05-11/tans-says-company-has-more-than-850-000-drivers-video) and we are growing and hiring at a rapid scale. To keep up with Grab's phenomenal growth, our web team and web platforms have to grow as well. Fortunately, or unfortunately, at Grab, the web team has been [keeping up](https://blog.daftcode.pl/hype-driven-development-3469fc2e9b22) with the latest best practices and has incorporated the modern JavaScript ecosystem in our web apps. The result of this is that our new hires or back end engineers, who are not necessarily well-acquainted with the modern JavaScript ecosystem, may feel overwhelmed by the barrage of new things that they have to learn just to complete their feature or bug fix in a web app. Front end development has never been so complex and exciting as it is today. New tools, libraries, frameworks and plugins emerge every other day and there is so much to learn. It is imperative that newcomers to the web team are guided to embrace this evolution of the front end, learn to navigate the ecosystem with ease, and get productive in shipping code to our users as fast as possible. We have come up with a study guide to introduce why we do what we do, and how we handle front end at scale. This study guide is inspired by ["A Study Plan to Cure JavaScript Fatigue"](https://medium.freecodecamp.com/a-study-plan-to-cure-javascript-fatigue-8ad3a54f2eb1#.g9egaapps) and is mildly opinionated in the sense that we recommend certain libraries/frameworks to learn for each aspect of front end development, based on what is currently deemed most suitable at Grab. We explain why a certain library/framework/tool is chosen and provide links to learning resources to enable the reader to pick it up on their own. Alternative choices that may be better for other use cases are provided as well for reference and further self-exploration. If you are familiar with front end development and have been consistently keeping up with the latest developments, this guide will probably not be that useful to you. It is targeted at newcomers to front end. If your company is exploring a modern JavaScript stack as well, you may find this study plan useful to your company too! Feel free to adapt it to your needs. We will update this study plan periodically, according to our latest work and choices. *- Grab Web Team* **Pre-requisites** - Good understanding of core programming concepts. - Comfortable with basic command line actions and familiarity with source code version control systems such as Git. - Experience in web development. Have built server-side rendered web apps using frameworks like Ruby on Rails, Django, Express, etc. - Understanding of how the web works. Familiarity with web protocols and conventions like HTTP and RESTful APIs. ### Table of Contents - [Single-page Apps (SPAs)](#single-page-apps-spas) - [New-age JavaScript](#new-age-javascript) - [User Interface](#user-interface---react) - [State Management](#state-management---fluxredux) - [Coding with Style](#coding-with-style---css-modules) - [Maintainability](#maintainability) - [Testing](#testing---jest--enzyme) - [Linting JavaScript](#linting-javascript---eslint) - [Linting CSS](#linting-css---stylelint) - [Formatting Code](#formatting-code---prettier) - [Types](#types---flow) - [Build System](#build-system---webpack) - [Package Management](#package-management---yarn) - [Continuous Integration](#continuous-integration) - [Hosting and CDN](#hosting-and-cdn) - [Deployment](#deployment) - [Monitoring](#monitoring) Certain topics can be skipped if you have prior experience in them. ## Single-page Apps (SPAs) Web developers these days refer to the products they build as web apps, rather than websites. While there is no strict difference between the two terms, web apps tend to be highly interactive and dynamic, allowing the user to perform actions and receive a response for their action. Traditionally, the browser receives HTML from the server and renders it. When the user navigates to another URL, a full-page refresh is required and the server sends fresh new HTML for the new page. This is called server-side rendering. However in modern SPAs, client-side rendering is used instead. The browser loads the initial page from the server, along with the scripts (frameworks, libraries, app code) and stylesheets required for the whole app. When the user navigates to other pages, a page refresh is not triggered. The URL of the page is updated via the [HTML5 History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API). New data required for the new page, usually in JSON format, is retrieved by the browser via [AJAX](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) requests to the server. The SPA then dynamically updates the page with the data via JavaScript, which it has already downloaded in the initial page load. This model is similar to how native mobile apps work. The benefits: - The app feels more responsive and users do not see the flash between page navigations due to full-page refreshes. - Fewer HTTP requests are made to the server, as the same assets do not have to be downloaded again for each page load. - Clear separation of the concerns between the client and the server; you can easily build new clients for different platforms (e.g. mobile, chatbots, smart watches) without having to modify the server code. You can also modify the technology stack on the client and server independently, as long as the API contract is not broken. The downsides: - Heavier initial page load due to loading of framework, app code, and assets required for multiple pages.<sup><a href="#fn1" id="ref1">1</a></sup> - There's an additional step to be done on your server which is to configure it to route all requests to a single entry point and allow client-side routing to take over from there. - SPAs are reliant on JavaScript to render content, but not all search engines execute JavaScript during crawling, and they may see empty content on your page. This inadvertently hurts the Search Engine Optimization (SEO) of your app. <sup><a href="#fn2" id="ref2">2</a></sup>. However, most of the time, when you are building apps, SEO is not the most important factor, as not all the content needs to be indexable by search engines. To overcome this, you can either server-side render your app or use services such as [Prerender](https://prerender.io/) to "render your javascript in a browser, save the static HTML, and return that to the crawlers". While traditional server-side rendered apps are still a viable option, a clear client-server separation scales better for larger engineering teams, as the client and server code can be developed and released independently. This is especially so at Grab when we have multiple client apps hitting the same API server. As web developers are now building apps rather than pages, organization of client-side JavaScript has become increasingly important. In server-side rendered pages, it is common to use snippets of jQuery to add user interactivity to each page. However, when building large apps, just jQuery is insufficient. After all, jQuery is primarily a library for DOM manipulation and it's not a framework; it does not define a clear structure and organization for your app. JavaScript frameworks have been created to provide higher-level abstractions over the DOM, allowing you to keep state in memory, out of the DOM. Using frameworks also brings the benefits of reusing recommended concepts and best practices for building apps. A new engineer on the team who is unfamiliar with the code base, but has experience with a framework, will find it easier to understand the code because it is organized in a structure that they are familiar with. Popular frameworks have a lot of tutorials and guides, and tapping on the knowledge and experience from colleagues and the community will help new engineers get up to speed. #### Study Links - [Single Page App: advantages and disadvantages](http://stackoverflow.com/questions/21862054/single-page-app-advantages-and-disadvantages) - [The (R)Evolution of Web Development](http://blog.isquaredsoftware.com/presentations/2016-10-revolution-of-web-dev/) - [Here's Why Client Side Rendering Won](https://medium.freecodecamp.com/heres-why-client-side-rendering-won-46a349fadb52) ## New-age JavaScript Before you dive into the various aspects of building a JavaScript web app, it is important to get familiar with the language of the web - JavaScript, or ECMAScript. JavaScript is an incredibly versatile language which you can also use to build [web servers](https://nodejs.org/en/), [native mobile apps](https://facebook.github.io/react-native/) and [desktop apps](https://electron.atom.io/). Prior to 2015, the last major update was ECMAScript 5.1, in 2011. However, in the recent years, JavaScript has suddenly seen a huge burst of improvements within a short span of time. In 2015, ECMAScript 2015 (previously called ECMAScript 6) was released and a ton of syntactic constructs were introduced to make writing code less unwieldy. If you are curious about it, Auth0 has written a nice article on the [history of JavaScript](https://auth0.com/blog/a-brief-history-of-javascript/). Till this day, not all browsers have fully implemented the ES2015 specification. Tools such as [Babel](https://babeljs.io/) enable developers to write ES2015 in their apps and Babel transpiles them down to ES5 to be compatible for browsers. Being familiar with both ES5 and ES2015 is crucial. ES2015 is still relatively new and a lot of open source code and Node.js apps are still written in ES5. If you are doing debugging in your browser console, you might not be able to use ES2015 syntax. On the other hand, documentation and example code for many modern libraries that we will introduce later below are still written in ES2015. At Grab, we use [babel-preset-env](https://github.com/babel/babel-preset-env) to enjoy the productivity boost from the syntactic improvements the future of JavaScript provides and we have been loving it so far. `babel-preset-env` intelligently determines which Babel plugins are necessary (which new language features are not supported and have to be transpiled) as browsers increase native support for more ES language features. If you prefer using language features that are already stable, you may find that [babel-preset-stage-3](https://babeljs.io/docs/plugins/preset-stage-3/), which is a complete specification that will most likely be implemented in browsers, will be more suitable. Spend a day or two revising ES5 and exploring ES2015. The more heavily used features in ES2015 include "Arrows and Lexical This", "Classes", "Template Strings", "Destructuring", "Default/Rest/Spread operators", and "Importing and Exporting modules". **Estimated Duration: 3-4 days.** You can learn/lookup the syntax as you learn the other libraries and try building your own app. #### Study Links - [Learn ES5 on Codecademy](https://www.codecademy.com/learn/learn-javascript) - [Learn ES6 on Codecademy](https://www.codecademy.com/learn/introduction-to-javascript) - [Learn ES2015 on Babel](https://babeljs.io/learn-es2015/) - [ES6 Katas](http://es6katas.org/) - [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) (Advanced content, optional for beginners) - [Answers to Front End Job Interview Questionsโ€Šโ€”โ€ŠJavaScript](https://github.com/yangshun/front-end-interview-handbook/blob/master/questions/javascript-questions.md) ## User Interface - React <img alt="React Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/react-logo.svg" width="256px" /> If any JavaScript project has taken the front end ecosystem by storm in recent years, that would be [React](https://facebook.github.io/react/). React is a library built and open-sourced by the smart people at Facebook. In React, developers write components for their web interface and compose them together. React brings about many radical ideas and encourages developers to [rethink best practices](https://www.youtube.com/watch?v=DgVS-zXgMTk). For many years, web developers were taught that it was a good practice to write HTML, JavaScript and CSS separately. React does the exact opposite, and encourages that you write your HTML and [CSS in your JavaScript](https://speakerdeck.com/vjeux/react-css-in-js) instead. This sounds like a crazy idea at first, but after trying it out, it actually isn't as weird as it sounds initially. Reason being the front end development scene is shifting towards a paradigm of component-based development. The features of React: - **Declarative** - You describe what you want to see in your view and not how to achieve it. In the jQuery days, developers would have to come up with a series of steps to manipulate the DOM to get from one app state to the next. In React, you simply change the state within the component and the view will update itself according to the state. It is also easy to determine how the component will look like just by looking at the markup in the `render()` method. - **Functional** - The view is a pure function of `props` and `state`. In most cases, a React component is defined by `props` (external parameters) and `state` (internal data). For the same `props` and `state`, the same view is produced. Pure functions are easy to test, and the same goes for functional components. Testing in React is made easy because a component's interfaces are well-defined and you can test the component by supplying different `props` and `state` to it and comparing the rendered output. - **Maintainable** - Writing your view in a component-based fashion encourages reusability. We find that defining a component's `propTypes` make React code self-documenting as the reader can know clearly what is needed to use that component. Lastly, your view and logic is self-contained within the component, and should not be affected nor affect other components. That makes it easy to shift components around during large-scale refactoring, as long as the same `props` are supplied to the component. - **High Performance** - You might have heard that React uses a virtual DOM (not to be confused with [shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)) and it re-renders everything when there is a change in state. Why is there a need for a virtual DOM? While modern JavaScript engines are fast, reading from and writing to the DOM is slow. React keeps a lightweight virtual representation of the DOM in memory. Re-rendering everything is a misleading term. In React it actually refers to re-rendering the in-memory representation of the DOM, not the actual DOM itself. When there's a change in the underlying data of the component, a new virtual representation is created, and compared against the previous representation. The difference (minimal set of changes required) is then patched to the real browser DOM. - **Ease of Learning** - Learning React is pretty simple. The React API surface is relatively small compared to [this](https://angular.io/docs/ts/latest/api/); there are only a few APIs to learn and they do not change often. The React community is one of the largest, and along with that comes a vibrant ecosystem of tools, open-sourced UI components, and a ton of great resources online to get you started on learning React. - **Developer Experience** - There are a number of tools that improves the development experience with React. [React Developer Tools](https://github.com/facebook/react-devtools) is a browser extension that allows you to inspect your component, view and manipulate its `props` and `state`. [Hot reloading](https://github.com/gaearon/react-hot-loader) with webpack allows you to view changes to your code in your browser, without you having to refresh the browser. Front end development involves a lot of tweaking code, saving and then refreshing the browser. Hot reloading helps you by eliminating the last step. When there are library updates, Facebook provides [codemod scripts](https://github.com/reactjs/react-codemod) to help you migrate your code to the new APIs. This makes the upgrading process relatively pain-free. Kudos to the Facebook team for their dedication in making the development experience with React great. <br> ![React Devtools Demo](images/react-devtools-demo.gif) Over the years, new view libraries that are even more performant than React have emerged. React may not be the fastest library out there, but in terms of the ecosystem, overall usage experience and benefits, it is still one of the greatest. Facebook is also channeling efforts into making React even faster with a [rewrite of the underlying reconciliation algorithm](https://github.com/acdlite/react-fiber-architecture). The concepts that React introduced has taught us how to write better code, more maintainable web apps and made us better engineers. We like that. We recommend going through the [tutorial](https://facebook.github.io/react/tutorial/tutorial.html) on building a tic-tac-toe game on the React homepage to get a feel of what React is and what it does. For more in-depth learning, check out the Egghead course, [Build Your First Production Quality React App](https://egghead.io/courses/build-your-first-production-quality-react-app). It covers some advanced concepts and real-world usages that are not covered by the React documentation. [Create React App](https://github.com/facebookincubator/create-react-app) by Facebook is a tool to scaffold a React project with minimal configuration and is highly recommended to use for starting new React projects. React is a library, not a framework, and does not deal with the layers below the view - the app state. More on that later. **Estimated Duration: 3-4 days.** Try building simple projects like a to-do list, Hacker News clone with pure React. You will slowly gain an appreciation for it and perhaps face some problems along the way that isn't solved by React, which brings us to the next topic... #### Study Links - [React Official Tutorial](https://facebook.github.io/react/tutorial/tutorial.html) - [Egghead Course - Build Your First Production Quality React App](https://egghead.io/courses/build-your-first-production-quality-react-app) - [Simple React Development in 2017](https://hackernoon.com/simple-react-development-in-2017-113bd563691f) - [Presentational and Container Components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.5iexphyg5) #### Alternatives - [Angular](https://angular.io/) - [Ember](https://www.emberjs.com/) - [Vue](https://vuejs.org/) - [Cycle](https://cycle.js.org/) ## State Management - Flux/Redux <img alt="Redux Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/redux-logo.svg" width="256px" /> As your app grows bigger, you may find that the app structure becomes a little messy. Components throughout the app may have to share and display common data but there is no elegant way to handle that in React. After all, React is just the view layer, it does not dictate how you structure the other layers of your app, such as the model and the controller, in traditional MVC paradigms. In an effort to solve this, Facebook invented Flux, an app architecture that complements React's composable view components by utilizing a unidirectional data flow. Read more about how Flux works [here](https://facebook.github.io/flux/docs/in-depth-overview.html). In summary, the Flux pattern has the following characteristics: - **Unidirectional data flow** - Makes the app more predictable as updates can be tracked easily. - **Separation of concerns** - Each part in the Flux architecture has clear responsibilities and are highly decoupled. - **Works well with declarative programming** - The store can send updates to the view without specifying how to transition views between states. As Flux is not a framework per se, developers have tried to come up with many implementations of the Flux pattern. Eventually, a clear winner emerged, which was [Redux](http://redux.js.org/). Redux combines the ideas from Flux, [Command pattern](https://www.wikiwand.com/en/Command_pattern) and [Elm architecture](https://guide.elm-lang.org/architecture/) and is the de facto state management library developers use with React these days. Its core concepts are: - App **state** is described by a single plain old JavaScript object (POJO). - Dispatch an **action** (also a POJO) to modify the state. - **Reducer** is a pure function that takes in current state and action to produce a new state. The concepts sound simple, but they are really powerful as they enable apps to: - Have their state rendered on the server, booted up on the client. - Trace, log and backtrack changes in the whole app. - Implement undo/redo functionality easily. The creator of Redux, [Dan Abramov](https://github.com/gaearon), has taken great care in writing up detailed documentation for Redux, along with creating comprehensive video tutorials for learning [basic](https://egghead.io/courses/getting-started-with-redux) and [advanced](https://egghead.io/courses/building-react-applications-with-idiomatic-redux) Redux. They are extremely helpful resources for learning Redux. **Combining View and State** While Redux does not necessarily have to be used with React, it is highly recommended as they play very well with each other. React and Redux have a lot of ideas and traits in common: - **Functional composition paradigm** - React composes views (pure functions) while Redux composes pure reducers (also pure functions). Output is predictable given the same set of input. - **Easy To Reason About** - You may have heard this term many times but what does it actually mean? We interpret it as having control and understanding over our code - Our code behaves in ways we expect it to, and when there are problems, we can find them easily. Through our experience, React and Redux makes debugging simpler. As the data flow is unidirectional, tracing the flow of data (server responses, user input events) is easier and it is straightforward to determine which layer the problem occurs in. - **Layered Structure** - Each layer in the app / Flux architecture is a pure function, and has clear responsibilities. It is relatively easy to write tests for pure functions. You have to centralize changes to your app within the reducer, and the only way to trigger a change is to dispatch an action. - **Development Experience** - A lot of effort has gone into creating tools to help in debugging and inspecting the app while development, such as [Redux DevTools](https://github.com/gaearon/redux-devtools). <br> ![Redux Devtools Demo](images/redux-devtools-demo.gif) Your app will likely have to deal with async calls like making remote API requests. [redux-thunk](https://github.com/gaearon/redux-thunk) and [redux-saga](https://github.com/redux-saga/redux-saga) were created to solve those problems. They may take some time to understand as they require understanding of functional programming and generators. Our advice is to deal with it only when you need it. [react-redux](https://github.com/reactjs/react-redux) is an official React binding for Redux and is very simple to learn. **Estimated Duration: 4 days.** The egghead courses can be a little time-consuming but they are worth spending time on. After learning Redux, you can try incorporating it into the React projects you have built. Does Redux solve some of the state management issues you were struggling with in pure React? #### Study Links - [Flux Homepage](http://facebook.github.io/flux) - [Redux Homepage](http://redux.js.org/) - [Egghead Course - Getting Started with Redux](https://egghead.io/courses/getting-started-with-redux) - [Egghead Course - Build React Apps with Idiomatic Redux](https://egghead.io/courses/building-react-applications-with-idiomatic-redux) - [React Redux Links](https://github.com/markerikson/react-redux-links) - [You Might Not Need Redux](https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367) #### Alternatives - [MobX](https://github.com/mobxjs/mobx) ## Coding with Style - CSS Modules <img alt="CSS Modules Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/css-modules-logo.svg" width="256px" /> CSS (Cascading Style Sheets) are rules to describe how your HTML elements look. Writing good CSS is hard. It usually takes many years of experience and frustration of shooting yourself in the foot before one is able to write maintainable and scalable CSS. CSS, having a global namespace, is fundamentally designed for web documents, and not really for web apps that favor a components architecture. Hence, experienced front end developers have designed methodologies to guide people on how to write organized CSS for complex projects, such as using [SMACSS](https://smacss.com/), [BEM](http://getbem.com/), [SUIT CSS](http://suitcss.github.io/), etc. However, the encapsulation of styles that these methodologies bring about are artificially enforced by conventions and guidelines. They break the moment developers do not follow them. As you might have realized by now, the front end ecosystem is saturated with tools, and unsurprisingly, tools have been invented to [partially solve some of the problems](https://speakerdeck.com/vjeux/react-css-in-js) with writing CSS at scale. "At scale" means that many developers are working on the same large project and touching the same stylesheets. There is no community-agreed approach on writing [CSS in JS](https://github.com/MicheleBertoli/css-in-js) at the moment, and we are hoping that one day a winner would emerge, just like Redux did, among all the Flux implementations. For now, we are banking on [CSS Modules](https://github.com/css-modules/css-modules). CSS modules is an improvement over existing CSS that aims to fix the problem of global namespace in CSS; it enables you to write styles that are local by default and encapsulated to your component. This feature is achieved via tooling. With CSS modules, large teams can write modular and reusable CSS without fear of conflict or overriding other parts of the app. However, at the end of the day, CSS modules are still being compiled into normal globally-namespaced CSS that browsers recognize, and it is still important to learn and understand how raw CSS works. If you are a total beginner to CSS, Codecademy's [HTML & CSS course](https://www.codecademy.com/learn/learn-html-css) will be a good introduction to you. Next, read up on the [Sass preprocessor](http://sass-lang.com/), an extension of the CSS language which adds syntactic improvements and encourages style reusability. Study the CSS methodologies mentioned above, and lastly, CSS modules. **Estimated Duration: 3-4 days.** Try styling up your app using the SMACSS/BEM approach and/or CSS modules. #### Study Links - [Learn HTML & CSS course on Codecademy](https://www.codecademy.com/learn/learn-html-css) - [Intro to HTML/CSS on Khan Academy](https://www.khanacademy.org/computing/computer-programming/html-css) - [SMACSS](https://smacss.com/) - [BEM](http://getbem.com/introduction/) - [SUIT CSS](http://suitcss.github.io/) - [CSS Modules Specification](https://github.com/css-modules/css-modules) - [Sass Homepage](http://sass-lang.com/) - [Answers to Front End Job Interview Questionsโ€Šโ€”โ€ŠHTML](https://github.com/yangshun/tech-interview-handbook/blob/master/front-end/interview-questions.md#html-questions) - [Answers to Front End Job Interview Questionsโ€Šโ€”โ€ŠCSS](https://github.com/yangshun/tech-interview-handbook/blob/master/front-end/interview-questions.md#css-questions) #### Alternatives - [JSS](https://github.com/cssinjs/jss) - [Styled Components](https://github.com/styled-components/styled-components) ## Maintainability Code is read more frequently than it is written. This is especially true at Grab, where the team size is large and we have multiple engineers working across multiple projects. We highly value readability, maintainability and stability of the code and there are a few ways to achieve that: "Extensive testing", "Consistent coding style" and "Typechecking". Also when you are in a team, sharing same practices becomes really important. Check out these [JavaScript Project Guidelines](https://github.com/wearehive/project-guidelines) for instance. ## Testing - Jest + Enzyme <img alt="Jest Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/jest-logo.svg" width="164px" /> [Jest](http://facebook.github.io/jest/) is a testing library by Facebook that aims to make the process of testing pain-free. As with Facebook projects, it provides a great development experience out of the box. Tests can be run in parallel resulting in shorter duration. During watch mode, by default, only the tests for the changed files are run. One particular feature we like is "Snapshot Testing". Jest can save the generated output of your React component and Redux state and save it as serialized files, so you wouldn't have to manually come up with the expected output yourself. Jest also comes with built-in mocking, assertion and test coverage. One library to rule them all! ![Jest Demo](images/jest-demo.gif) React comes with some testing utilities, but [Enzyme](http://airbnb.io/enzyme/) by Airbnb makes it easier to generate, assert, manipulate and traverse your React components' output with a jQuery-like API. It is recommended that Enzyme be used to test React components. Jest and Enzyme makes writing front end tests fun and easy. When writing tests becomes enjoyable, developers write more tests. It also helps that React components and Redux actions/reducers are relatively easy to test because of clearly defined responsibilities and interfaces. For React components, we can test that given some `props`, the desired DOM is rendered, and that callbacks are fired upon certain simulated user interactions. For Redux reducers, we can test that given a prior state and an action, a resulting state is produced. The documentation for Jest and Enzyme are pretty concise, and it should be sufficient to learn them by reading it. **Estimated Duration: 2-3 days.** Try writing Jest + Enzyme tests for your React + Redux app! #### Study Links - [Jest Homepage](http://facebook.github.io/jest/) - [Testing React Applications with Jest](https://auth0.com/blog/testing-react-applications-with-jest/) - [Enzyme Homepage](http://airbnb.io/enzyme/) - [Enzyme: JavaScript Testing utilities for React](https://medium.com/airbnb-engineering/enzyme-javascript-testing-utilities-for-react-a417e5e5090f) #### Alternatives - [AVA](https://github.com/avajs/ava) - [Karma](https://karma-runner.github.io/) ## Linting JavaScript - ESLint <img alt="ESLint Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/eslint-logo.svg" width="256px" /> A linter is a tool to statically analyze code and finds problems with them, potentially preventing bugs/runtime errors and at the same time, enforcing a coding style. Time is saved during pull request reviews when reviewers do not have to leave nitpicky comments on coding style. [ESLint](http://eslint.org/) is a tool for linting JavaScript code that is highly extensible and customizable. Teams can write their own lint rules to enforce their custom styles. At Grab, we use Airbnb's [`eslint-config-airbnb`](https://www.npmjs.com/package/eslint-config-airbnb) preset, that has already been configured with the common good coding style in the [Airbnb JavaScript style guide](https://github.com/airbnb/javascript). For the most part, using ESLint is as simple as tweaking a configuration file in your project folder. There's nothing much to learn about ESLint if you're not writing new rules for it. Just be aware of the errors when they surface and Google it to find out the recommended style. **Estimated Duration: 1/2 day.** Nothing much to learn here. Add ESLint to your project and fix the linting errors! #### Study Links - [ESLint Homepage](http://eslint.org/) - [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) #### Alternatives - [Standard](https://github.com/standard/standard) - [JSHint](http://jshint.com/) - [XO](https://github.com/xojs/xo) ## Linting CSS - stylelint <img alt="stylelint Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/stylelint-logo.svg" width="256px" /> As mentioned earlier, good CSS is notoriously hard to write. Usage of static analysis tools on CSS can help to maintain our CSS code quality and coding style. For linting CSS, we use stylelint. Like ESLint, stylelint is designed in a very modular fashion, allowing developers to turn rules on/off and write custom plugins for it. Besides CSS, stylelint is able to parse SCSS and has experimental support for Less, which lowers the barrier for most existing code bases to adopt it. ![stylelint Demo](images/stylelint-demo.png) Once you have learnt ESLint, learning stylelint would be effortless considering their similarities. stylelint is currently being used by big companies like [Facebook](https://code.facebook.com/posts/879890885467584/improving-css-quality-at-facebook-and-beyond/), [Github](https://github.com/primer/stylelint-config-primer) and [Wordpress](https://github.com/WordPress-Coding-Standards/stylelint-config-wordpress). One downside of stylelint is that the autofix feature is not fully mature yet, and is only able to fix for a limited number of rules. However, this issue should improve with time. **Estimated Duration: 1/2 day.** Nothing much to learn here. Add stylelint to your project and fix the linting errors! #### Study Links - [stylelint Homepage](https://stylelint.io/) - [Lint your CSS with stylelint](https://css-tricks.com/stylelint/) #### Alternatives - [Sass Lint](https://github.com/sasstools/sass-lint) - [CSS Lint](http://csslint.net/) ## Formatting Code - Prettier <img alt="Prettier Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/prettier-logo.png" width="256px" /> Another tool for enforcing consistent coding style for JavaScript and CSS is [Prettier](https://github.com/prettier/prettier). In most cases, it is recommended to setup Prettier on top of ESLint and stylelint and integrate it into the workflow. This allows the code to be formatted into consistent style automatically via commit hooks, so that developers do not need to spend time formatting the coding style manually. Note that Prettier only enforces coding style, but does not check for logic errors in the code. Hence it is not a replacement for linters. **Estimated Duration: 1/2 day.** Nothing much to learn here. Add Prettier to your project and add hooks to enforce the coding style! #### Study Links - [Prettier Homepage](https://prettier.io/) - [Prettier GitHub repo](https://github.com/prettier/prettier) - [Comparison between tools that allow you to use ESLint and Prettier together](https://gist.github.com/yangshun/318102f525ec68033bf37ac4a010eb0c) ## Types - Flow <img alt="Flow Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/flow-logo.png" width="256px" /> Static typing brings about many benefits when writing apps. They can catch common bugs and errors in your code early. Types also serve as a form of documentation for your code and improves the readability of your code. As a code base grows larger, we see the importance of types as they gives us greater confidence when we do refactoring. It is also easier to onboard new members of the team to the project when it is clear what kind of values each object holds and what each function expects. Adding types to your code comes with the trade-off of increased verbosity and a learning curve of the syntax. But this learning cost is paid upfront and amortized over time. In complex projects where the maintainability of the code matters and the people working on it change over time, adding types to the code brings about more benefits than disadvantages. Recently, I had to fix a bug in a code base that I havenโ€™t touched in months. It was thanks to types that I could easily refresh myself on what the code was doing, and gave me confidence in the fix I made. The two biggest contenders in adding static types to JavaScript are [Flow](https://flow.org/) (by Facebook) and [TypeScript](https://www.typescriptlang.org/) (by Microsoft). As of date, there is no clear winner in the battle. For now, we have made the choice of using Flow. We find that Flow has a lower learning curve as compared to TypeScript and it requires relatively less effort to migrate an existing code base to Flow. Being built by Facebook, Flow has better integration with the React ecosystem out of the box. [James Kyle](https://twitter.com/thejameskyle), one of the authors of Flow, has [written](http://thejameskyle.com/adopting-flow-and-typescript.html) on a comparison between adopting Flow and TypeScript. Anyway, it is not extremely difficult to move from Flow to TypeScript as the syntax and semantics are quite similar, and we will re-evaluate the situation in time to come. After all, using one is better than not using any at all. Flow recently revamped their homepage and it's pretty neat now! **Estimated Duration: 1 day.** Flow is pretty simple to learn as the type annotations feel like a natural extension of the JavaScript language. Add Flow annotations to your project and embrace the power of type systems. #### Study Links - [Flow Homepage](https://flow.org/) - [TypeScript vs Flow](https://github.com/niieani/typescript-vs-flowtype) #### Alternatives - [TypeScript](https://www.typescriptlang.org/) ## Build System - webpack <img alt="webpack Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/webpack-logo.svg" width="256px" /> This part will be kept short as setting up webpack can be a tedious process and might be a turn-off to developers who are already overwhelmed by the barrage of new things they have to learn for front end development. In a nutshell, [webpack](https://webpack.js.org/) is a module bundler that compiles a front end project and its dependencies into a final bundle to be served to users. Usually, projects will already have the webpack configuration set up and developers rarely have to change it. Having an understanding of webpack is still a good to have in the long run. It is due to webpack that features like hot reloading and CSS modules are made possible. We have found the [webpack walkthrough](https://survivejs.com/webpack/foreword/) by SurviveJS to be the best resource on learning webpack. It is a good complement to the official documentation and we recommend following the walkthrough first and referring to the documentation later when the need for further customization arises. **Estimated Duration: 2 days (Optional).** #### Study Links - [webpack Homepage](https://webpack.js.org/) - [SurviveJS - Webpack: From apprentice to master](https://survivejs.com/webpack/foreword/) #### Alternatives - [Rollup](https://rollupjs.org/) - [Browserify](http://browserify.org/) - [Parcel](https://parceljs.org/) ## Package Management - Yarn <img alt="Yarn Logo" src="https://cdn.rawgit.com/grab/front-end-guide/master/images/yarn-logo.png" width="256px" /> If you take a peek into your `node_modules` directory, you will be appalled by the number of directories that are contained in it. Each babel plugin, lodash function, is a package on its own. When you have multiple projects, these packages are duplicated across each project and they are largely similar. Each time you run `npm install` in a new project, these packages are downloaded over and over again even though they already exist in some other project in your computer. There was also the problem of non-determinism in the installed packages via `npm install`. Some of our CI builds fail because at the point of time when the CI server installs the dependencies, it pulled in minor updates to some packages that contained breaking changes. This would not have happened if library authors respected [semver](http://semver.org/) and engineers did not assume that API contracts would be respected all the time. [Yarn](https://yarnpkg.com/) solves these problems. The issue of non-determinism of installed packages is handled via a `yarn.lock` file, which ensures that every install results in the exact same file structure in `node_modules` across all machines. Yarn utilizes a global cache directory within your machine, and packages that have been downloaded before do not have to be downloaded again. This also enables offline installation of dependencies! The most common Yarn commands can be found [here](https://yarnpkg.com/en/docs/usage). Most other yarn commands are similar to the `npm` equivalents and it is fine to use the `npm` versions instead. One of our favorite commands is `yarn upgrade-interactive` which makes updating dependencies a breeze especially when the modern JavaScript project requires so many dependencies these days. Do check it out! [email protected] was [released in May 2017](https://github.com/npm/npm/releases/tag/v5.0.0) and it seems to address many of the issues that Yarn aims to solve. Do keep an eye on it! **Estimated Duration: 2 hours.** #### Study Links - [Yarn Homepage](https://yarnpkg.com/) - [Yarn: A new package manager for JavaScript](https://code.facebook.com/posts/1840075619545360) #### Alternatives - [Good old npm](https://github.com/npm/npm/releases/tag/v5.0.0) ## Continuous Integration We used [Travis CI](https://travis-ci.com/) for our continuous integration (CI) pipeline. Travis is a highly popular CI on Github and its [build matrix](https://docs.travis-ci.com/user/customizing-the-build#Build-Matrix) feature is useful for repositories which contain multiple projects like Grab's. We configured Travis to do the following: - Run linting for the project. - Run unit tests for the project. - If the tests pass: - Test coverage generated by Jest is uploaded to [Codecov](https://codecov.io/). - Generate a production bundle with webpack into a `build` directory. - `tar` the `build` directory as `<hash>.tar` and upload it to an S3 bucket which stores all our tar builds. - Post a notification to Slack to inform about the Travis build result. #### Study Links - [Travis Homepage](https://travis-ci.com/) - [Codecov Homepage](https://codecov.io/) #### Alternatives - [Jenkins](https://jenkins.io/) - [CircleCI](https://circleci.com/) - [GitLab CI/CD](https://about.gitlab.com/product/continuous-integration/) ## Hosting and CDN Traditionally, web servers that receive a request for a webpage will render the contents on the server, and return a HTML page with dynamic content meant for the requester. This is known as server-side rendering. As mentioned earlier in the section on Single-page Apps, modern web applications do not involve server-side rendering, and it is sufficient to use a web server that serves static asset files. Nginx and Apache are possible options and not much configuration is required to get things up and runnning. The caveat is that the web server will have to be configured to route all requests to a single entry point and allow client-side routing to take over. The flow for front end routing goes like this: 1. Web server receives a HTTP request for a particular route, for example `/user/john`. 1. Regardless of which route the server receives, serve up `index.html` from the static assets directory. 1. The `index.html` should contain scripts that load up a JavaScript framework/library that handles client-side routing. 1. The client-side routing library reads the current route, and communicates to the MVC (or equivalent where relevant) framework about the current route. 1. The MVC JavaScript framework renders the desired view based on the route, possibly after fetching data from an API if required. Example, load up `UsersController`, fetch user data for the username `john` as JSON, combine the data with the view, and render it on the page. A good practice for serving static content is to use caching and putting them on a CDN. We use [Amazon Simple Storage Service (S3)](https://aws.amazon.com/s3/) for hosting our static website content and [Amazon CloudFront](https://aws.amazon.com/cloudfront/) as the CDN. We find that it is an affordable and reliable solution that meets our needs. S3 provides the option to "Use this bucket to host a website", which essentially directs the requests for all routes to the root of the bucket, which means we do not need our own web servers with special routing configurations. An example of a web app that we host on S3 is [Hub](https://hub.grab.com/). Other than hosting the website, we also use S3 to host the build `.tar` files generated from each successful CI build. #### Study Links - [Amazon S3 Homepage](https://aws.amazon.com/s3/) - [Hosting a Static Website on Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html) #### Alternatives - [Google Cloud Platform](https://cloud.google.com/storage/docs/hosting-static-website) - [Now](https://zeit.co/now) ## Deployment The last step in shipping the product to our users is deployment. We used [Ansible Tower](https://www.ansible.com/tower) which is a powerful automation software that enables us to deploy our builds easily. As mentioned earlier, all our commits, upon successful build, are being uploaded to a central S3 bucket for builds. We follow semver for our releases and have commands to automatically generate release notes for the latest release. When it is time to release, we run a command to tag the latest commit and push to our code hosting environment. Travis will run the CI steps on that tagged commit and upload a tar file (such as `1.0.1.tar`) with the version to our S3 bucket for builds. On Tower, we simply have to specify the name of the `.tar` we want to deploy to our hosting bucket, and Tower does the following: 1. Download the desired `.tar` file from our builds S3 bucket. 1. Extracts the contents and swap in the configuration file for specified environment. 1. Upload the contents to the hosting bucket. 1. Post a notification to Slack to inform about the successful deployment. This whole process is done under 30 seconds and using Tower has made deployments and rollbacks easy. If we realize that a faulty deployment has occurred, we can simply find the previous stable tag and deploy it. #### Study Links - [Ansible Tower Homepage](https://www.ansible.com/tower) #### Alternatives - [Jenkins](https://jenkins.io/) ## Monitoring After shipping the product, you would also want to monitor it for any errors. Apart from network level monitoring from our CDN service provider and hosting provider, we use [Sentry](https://sentry.io/) to monitor errors that originates from the app logic. #### Study Links - [Sentry Homepage](https://sentry.io/) ### The Journey has Just Begun Congratulations on making it this far! Front end development today is [hard](https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f), but it is also more interesting than before. What we have covered so far will help any new engineer to Grab's web team to get up to speed with our technologies pretty quickly. There are many more things to be learnt, but building up a solid foundation in the essentials will aid in learning the rest of the technologies. This helpful [front end web developer roadmap](https://github.com/kamranahmedse/developer-roadmap#-front-end-roadmap) shows the alternative technologies available for each aspect. We made our technical decisions based on what was important to a rapidly growing Grab Engineering team - maintainability and stability of the code base. These decisions may or may not apply to smaller teams and projects. Do evaluate what works best for you and your company. As the front end ecosystem grows, we are actively exploring, experimenting and evaluating how new technologies can make us a more efficient team and improve our productivity. We hope that this post has given you insights into the front end technologies we use at Grab. If what we are doing interests you, [we are hiring](https://grab.careers)! *Many thanks to [Joel Low](https://github.com/lowjoel), [Li Kai](https://github.com/li-kai) and [Tan Wei Seng](https://github.com/xming13) who reviewed drafts of this article.* ### More Reading **General** - [State of the JavaScript Landscape: A Map for Newcomers](http://www.infoq.com/articles/state-of-javascript-2016) - [The Hitchhiker's guide to the modern front end development workflow](http://marcobotto.com/the-hitchhikers-guide-to-the-modern-front-end-development-workflow/) - [How it feels to learn JavaScript in 2016](https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.tmy8gzgvp) - [Roadmap to becoming a web developer in 2017](https://github.com/kamranahmedse/developer-roadmap#-frontend-roadmap) - [Modern JavaScript for Ancient Web Developers](https://trackchanges.postlight.com/modern-javascript-for-ancient-web-developers-58e7cae050f9) **Other Study Plans** - [A Study Plan To Cure JavaScript Fatigue](https://medium.freecodecamp.com/a-study-plan-to-cure-javascript-fatigue-8ad3a54f2eb1#.c0wnrrcwd) - [JS Stack from Scratch](https://github.com/verekia/js-stack-from-scratch) - [A Beginnerโ€™s JavaScript Study Plan](https://medium.freecodecamp.com/a-beginners-javascript-study-plan-27f1d698ea5e#.bgf49xno2) ### Footnotes <p id="fn1">1. This can be solved via <a href="https://webpack.js.org/guides/code-splitting/">webpack code splitting</a>. <a href="#ref1" title="Jump back to footnote 1 in the text.">โ†ฉ</a></p> <p id="fn2">2. <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal JS</a> to the rescue! <a href="#ref2" title="Jump back to footnote 1 in the text.">โ†ฉ</a></p>
150
iOS Debugging Tool ๐Ÿš€
| <img alt="logo" src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/logo.png" width="250"/> | <ul align="left"><li><a href="#introduction">Introduction</a><li><a href="#installation">Installation</a><li><a href="#usage">Usage</a><li><a href="#parameters">Parameters</a></ul> | | -------------- | -------------- | | Version | [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/CocoaDebug.svg)](https://img.shields.io/cocoapods/v/CocoaDebug.svg) | | Platform | ![Platform](https://img.shields.io/badge/platforms-iOS%208.0+-blue.svg) | | Languages | ![Languages](https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-blue.svg) | <span style="float:none" /> ## Screenshot <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a1.png" width="250"> <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a2.png" width="250"> <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a3.png" width="250"> <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a4.png" width="250"> <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a5.png" width="250"> <img src="https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/pic/a6.png" width="250"> ## Introduction - [x] Shake to hide or show the black bubble. (Support iPhone device and simulator) - [x] Share network details via email or copy to clipboard when you are in the *Network Details* page. - [x] Copy logs. (Long press the text, then select all or select copy) - [x] Search logs by keyword. - [x] Long press the black bubble to clean all network logs. - [x] Detect *UI Blocking*. - [x] List crash errors. - [x] List application and device informations, including: *version*, *build*, *bundle name*, *bundle id*, *screen resolution*, *device*, *iOS version* - [x] List all network requests sent by the application. (Support *JSON* and Google's *Protocol buffers*) - [x] List all sandbox folders and files, supporting to preview and edit. - [x] List all *WKWebView* consoles. - [x] List all *React Native* JavaScript consoles and Native logs. - [x] List all *print()* and *NSLog()* messages which have been written by developer in Xcode. ## Installation ### *CocoaPods* *(Preferred)* ```ruby target 'YourTargetName' do use_frameworks! pod 'CocoaDebug', :configurations => ['Debug'] end ``` ### *Carthage* ```ruby github "CocoaDebug/CocoaDebug" ``` ### *Framework* *[CocoaDebug.framework](https://raw.githubusercontent.com/CocoaDebug/CocoaDebug/master/CocoaDebug.framework.zip) (Version 1.7.2)* > WARNING: Never ship a product which has been linked with the CocoaDebug framework. The [Integration Guide](https://github.com/CocoaDebug/CocoaDebug/wiki/Integration-Guide) outline a way to use build configurations to isolate linking the framework to Debug builds. > [Xcode12 build error solution](https://stackoverflow.com/questions/63267897/building-for-ios-simulator-but-the-linked-framework-framework-was-built) ## Usage - Don't need to do anything. CocoaDebug will start automatically. - To capture logs from Xcode with codes: (You can also set this in *CocoaDebug->App->Monitor->Applogs* without any codes.) ```swift CocoaDebugSettings.shared.enableLogMonitoring = true //The default value is false ``` - Check [AppDelegate.m](https://github.com/CocoaDebug/CocoaDebug/blob/master/Example_Objc/Example_Objc/AppDelegate.m) OR [AppDelegate.swift](https://github.com/CocoaDebug/CocoaDebug/blob/master/Example_Swift/Example_Swift/AppDelegate.swift) for more advanced usage. ## Parameters When you initialize CocoaDebug, you can customize the following parameter values before `CocoaDebug.enable()`. - `serverURL` - If the captured URLs contain server URL, CocoaDebug set server URL bold font to be marked. Not mark when this value is nil. Default value is **nil**. - `ignoredURLs` - Set the URLs which should not been captured, CocoaDebug capture all URLs when the value is nil. Default value is **nil**. - `onlyURLs` - Set the URLs which are only been captured, CocoaDebug capture all URLs when the value is nil. Default value is **nil**. - `ignoredPrefixLogs` - Set the prefix Logs which should not been captured, CocoaDebug capture all Logs when the value is nil. Default value is **nil**. - `onlyPrefixLogs` - Set the prefix Logs which are only been captured, CocoaDebug capture all Logs when the value is nil. Default value is **nil**. - `additionalViewController` - Add an additional UIViewController as child controller of CocoaDebug's main UITabBarController. Default value is **nil**. - `emailToRecipients` - Set the initial recipients to include in the emailโ€™s โ€œToโ€ field when share via email. Default value is **nil**. - `emailCcRecipients` - Set the initial recipients to include in the emailโ€™s โ€œCcโ€ field when share via email. Default value is **nil**. - `mainColor` - Set CocoaDebug's main color with hexadecimal format. Default value is **#42d459**. - `protobufTransferMap` - Protobuf data transfer to JSON map. Default value is **nil**. ## Thanks Special thanks to [remirobert](https://github.com/remirobert). ## Reference [https://developer.apple.com/library/archive/samplecode/CustomHTTPProtocol/Introduction/Intro.html](https://developer.apple.com/library/archive/samplecode/CustomHTTPProtocol/Introduction/Intro.html)
151
Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.
[![Apache License](https://img.shields.io/github/license/google/promises.svg)](LICENSE) [![Travis](https://api.travis-ci.org/google/promises.svg?branch=master)](https://travis-ci.org/google/promises) [![Gitter Chat](https://badges.gitter.im/google/promises.svg)](https://gitter.im/google/promises) ![Platforms](https://img.shields.io/badge/platforms-macOS%20%7C%20iOS%20%7C%20tvOS%20%7C%20watchOS-blue.svg?longCache=true&style=flat) ![Languages](https://img.shields.io/badge/languages-Swift%20%7C%20ObjC-orange.svg?longCache=true&style=flat) ![Package Managers](https://img.shields.io/badge/supports-Bazel%20%7C%20SwiftPM%20%7C%20CocoaPods%20%7C%20Carthage-yellow.svg?longCache=true&style=flat) # Promises Promises is a modern framework that provides a synchronization construct for Objective-C and Swift to facilitate writing asynchronous code. * [Introduction](g3doc/index.md) * [The problem with async code](g3doc/index.md#the-problem-with-async-code) * [Promises to the rescue](g3doc/index.md#promises-to-the-rescue) * [What is a promise?](g3doc/index.md#what-is-a-promise) * [Framework](g3doc/index.md#framework) * [Features](g3doc/index.md#features) * [Benchmark](g3doc/index.md#benchmark) * [Getting started](g3doc/index.md#getting-started) * [Add dependency](g3doc/index.md#add-dependency) * [Import](g3doc/index.md#import) * [Adopt](g3doc/index.md#adopt) * [Basics](g3doc/index.md#basics) * [Creating promises](g3doc/index.md#creating-promises) * [Async](g3doc/index.md#async) * [Do](g3doc/index.md#do) * [Pending](g3doc/index.md#pending) * [Resolved](g3doc/index.md#create-a-resolved-promise) * [Observing fulfillment](g3doc/index.md#observing-fulfillment) * [Then](g3doc/index.md#then) * [Observing rejection](g3doc/index.md#observing-rejection) * [Catch](g3doc/index.md#catch) * [Extensions](g3doc/index.md#extensions) * [All](g3doc/index.md#all) * [Always](g3doc/index.md#always) * [Any](g3doc/index.md#any) * [AwaitPromise](g3doc/index.md#awaitpromise) * [Delay](g3doc/index.md#delay) * [Race](g3doc/index.md#race) * [Recover](g3doc/index.md#recover) * [Reduce](g3doc/index.md#reduce) * [Retry](g3doc/index.md#retry) * [Timeout](g3doc/index.md#timeout) * [Validate](g3doc/index.md#validate) * [Wrap](g3doc/index.md#wrap) * [Advanced topics](g3doc/index.md#advanced-topics) * [Default dispatch queue](g3doc/index.md#default-dispatch-queue) * [Ownership and retain cycles](g3doc/index.md#ownership-and-retain-cycles) * [Testing](g3doc/index.md#testing) * [Objective-C <-> Swift interoperability](g3doc/index.md#objective-c---swift-interoperability) * [Dot-syntax in Objective-C](g3doc/index.md#dot-syntax-in-objective-c) * [Anti-patterns](g3doc/index.md#anti-patterns) * [Broken chain](g3doc/index.md#broken-chain) * [Nested promises](g3doc/index.md#nested-promises)
152
A curated collection of iOS, ML, AR resources sprinkled with some UI additions
# iowncode The below resources largely pertain to iOS 13. For iOS 14 and above, do check out [this repository](https://github.com/anupamchugh/iOS14-Resources) ## SwiftUI * [SwiftUI Bar Charts](https://medium.com/better-programming/swiftui-bar-charts-274e9fbc8030?source=friends_link&sk=30da347d33abcfb89cb0eb7a0c7d5d82) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIBarCharts) * [Gestures in SwiftUI](https://medium.com/better-programming/gestures-in-swiftui-e94b784ecc7?source=friends_link&sk=937a377f00fe038a669a6f16b74a55f2) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIGestures) * [SwiftUI Line Charts](https://medium.com/better-programming/create-a-line-chart-in-swiftui-using-paths-183d0ddd4578?source=friends_link&sk=d768ace231eecc90028e39d8d2d95111) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUILineChart) * [SwiftUI UIViewRepresentable](https://medium.com/better-programming/how-to-use-uiviewrepresentable-with-swiftui-7295bfec312b?source=friends_link&sk=c12c8924189352b3e9f381a6aea314ba) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIViewRepresentable) * [SwiftUI WebSockets](https://medium.com/better-programming/build-a-bitcoin-price-ticker-in-swiftui-b16d9ca566a8?source=friends_link&sk=4ac88d157b3d35feaf8139462b9cb5bf) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIWebSockets) * [SwiftUI WebView ProgressBar: Modify States During View Updates](https://medium.com/better-programming/how-to-modify-states-during-view-updates-in-swiftui-923bf7cea44f) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIWebViewsProgressBars) * [SwiftUI Change App Icon](https://medium.com/better-programming/how-to-change-your-apps-icon-in-swiftui-1f2ff3c44344?source=friends_link&sk=687ac692bb6df5ce97669066d799fa2f) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIAlternateIcons) * [SwiftUI Contact Search](https://medium.com/better-programming/build-a-swiftui-contacts-search-application-d41b414fe046?source=friends_link&sk=38c67b34ada448c52827f5be1f70ada8) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIContactSearch) * [SwiftUI Pull To Refresh Workaround](https://medium.com/better-programming/pull-to-refresh-in-swiftui-6604f54a01d5) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIPullToRefresh) * [SwiftUI Alamofire](https://medium.com/better-programming/combine-swiftui-with-alamofire-abb4cd4a0aca?source=friends_link&sk=46215390a2df56654ae240d06755a905) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIAlamofire) * [SwiftUI COVID-19 Maps Visualisation](https://heartbeat.comet.ml/coronavirus-visualisation-on-maps-with-swiftui-and-combine-on-ios-c3f6e04c2634) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUICoronaMapTracker) * [SwiftUI Combine URLSession Infinite Scrolling](https://medium.com/better-programming/build-an-endless-scrolling-list-with-swiftui-combine-and-urlsession-8a697a8318cb?source=friends_link&sk=d0ed3a0e29bc59b9faf0176e000dbe68) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUICombineURLSession) ## CoreML and CreateML * CoreML 3 On Device Training [Part 1: Build Updatable Model](https://medium.com/better-programming/how-to-create-updatable-models-using-core-ml-3-cc7decd517d5?source=friends_link&sk=b34c2f90ec24f355dcad7e0c075e2f5e) | [Part 2: Re-train On Device](https://medium.com/better-programming/how-to-train-a-core-ml-model-on-your-device-cccd0bee19d?source=friends_link&sk=efa2297be5c42ca26c0971f4888f73d1) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSCoreMLOnDeviceTraining) * [PencilKit Run Core ML Model MNIST](https://medium.com/better-programming/pencilkit-meets-core-ml-aefe3cde6a96?source=friends_link&sk=f3cf758575adb9c6391af3bd18fd65a6) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSPencilKitCoreMLMNIST) * [Sound Classifier Using CoreML and CreateML](https://betterprogramming.pub/sound-classification-using-core-ml-3-and-create-ml-fc73ca20aff5) | [Code](https://github.com/anupamchugh/iowncode/tree/master/CoreML3SoundClassifier) * [CoreML CreateML Recommender System](https://betterprogramming.pub/build-a-core-ml-recommender-engine-for-ios-using-create-ml-e8a748d01ba3) | [Code](https://github.com/anupamchugh/iowncode/tree/master/CoreMLRecommender) * [CoreML NSFW Classifier Using CreateML](https://medium.com/better-programming/nsfw-image-detector-using-create-ml-core-ml-and-vision-79792d805bab?source=friends_link&sk=6b1007eab8dce2aa5079953409b9e63d) | [Code](https://github.com/anupamchugh/iowncode/tree/master/NSFWCreateMLImageClassifier) * [SwiftUI CoreML Emoji Hunter Game](https://betterprogramming.pub/build-a-swiftui-core-ml-emoji-hunt-game-for-ios-eb4465ec4153) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIVisionEmojiHunt) * * [CoreML Background Removal](https://betterprogramming.pub/coreml-image-segmentation-background-remove-ca11e6f6a083) | [Code](https://github.com/anupamchugh/iowncode/tree/master/CoreMLBackgroundChangeSwiftUI) * [Real-time Style Transfer On A Live Camera Feed](https://betterprogramming.pub/train-and-run-a-create-ml-style-transfer-model-in-an-ios-camera-application-84aab3b85458) | [Code](https://github.com/anupamchugh/iOS14-Resources/tree/master/CreateMLVideoStyleTransfer) ## Vision Framework * [Built-in Animal Classifier](https://medium.com/swlh/ios-vision-cat-vs-dog-image-classifier-in-5-minutes-f9fd6f264762?source=friends_link&sk=2d03ffb703aa0d15415f4690e8d81c3f) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13VisionPetAnimalClassifier) * [Built-in Text Recognition](https://medium.com/better-programming/ios-vision-text-document-scanner-effc0b7f4635) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13VisionTextRecogniser) * [Image Similarity](https://betterprogramming.pub/compute-image-similarity-using-computer-vision-in-ios-75b4dcdd095f) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSImageSimilarityUsingVision) * [Scanning Credit Card Using Rectangle Detection and Text Recognition](https://betterprogramming.pub/scanning-credit-cards-with-computer-vision-on-ios-c3f4d8912de4) | [Code](https://github.com/anupamchugh/iowncode/tree/master/VisionCreditScan) * [Cropping Using Saliency](https://medium.com/better-programming/cropping-areas-of-interest-using-vision-in-ios-e83b5e53440b?source=friends_link&sk=e14d1979ec429468e5a5f63ec44c5a75) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSVisionCroppingSalientFeatures) * [Find Best Face Captured In A Live Photo](https://betterprogramming.pub/computer-vision-in-ios-determine-the-best-facial-expression-in-live-photos-452a2eaf6512) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSVisionFaceQualityLivePhoto) * [Vision Contour Detection](https://betterprogramming.pub/new-in-ios-14-vision-contour-detection-68fd5849816e) | [Code](https://github.com/anupamchugh/iOS14-Resources/tree/master/iOS14VisionContourDetection) * [Vision Hand Pose Estimation](https://betterprogramming.pub/swipeless-tinder-using-ios-14-vision-hand-pose-estimation-64e5f00ce45c) | [Code](https://github.com/anupamchugh/iOS14-Resources/tree/master/iOS14VisionHandPoseSwipe) ## Natural Language Framework * [Classify Movie Reviews Using Sentiment Analysis and also CoreML](https://towardsdatascience.com/classifying-movie-reviews-with-natural-language-framework-12dfe2fc3308) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSNLPRottenTomatoes) * [Sentiment Analysis Of Hacker News Feed Using SwiftUI](https://betterprogramming.pub/sentiment-analysis-on-ios-using-swift-natural-language-and-combine-hacker-news-top-stories-d1b8d8f4f798) | [Code](https://github.com/anupamchugh/iowncode/tree/master/SwiftUIHNSentiments) ## RealityKit * [Introduction To Entities, Gestures and Raycasting](https://betterprogramming.pub/introduction-to-realitykit-on-ios-entities-gestures-and-ray-casting-8f6633c11877) | [Code](https://github.com/anupamchugh/iowncode/tree/master/RealityKitEntitiesVision) * [Collisions](https://betterprogramming.pub/realitykit-on-ios-part-2-applying-collision-events-d64b6e10421f) | [Code](https://github.com/anupamchugh/iowncode/tree/master/RealityKitCollisions) ## UIKit and other changes in iOS 13 * [Compositional Layouts](https://medium.com/better-programming/ios-13-compositional-layouts-in-collectionview-90a574b410b8) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13CompostionalLayouts) * [Diffable Datasources](https://medium.com/better-programming/applying-diffable-data-sources-70ce65b368e4) | [Code](https://github.com/anupamchugh/iowncode/tree/master/DiffableDataSources) * [ContextMenu and SFSymbols](https://medium.com/better-programming/ios-context-menu-collection-view-a03b032fe330) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13ContextMenu) * [Multi Selection on TableView and CollectionView](https://medium.com/better-programming/ios-13-multi-selection-gestures-in-tableview-and-collectionview-619d515eef16) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13TableViewAndCollectionView) * [What's New In MapKit](https://medium.com/better-programming/exploring-mapkit-on-ios-13-1a7a1439e3b6?source=friends_link&sk=5e333f42b70e9adff945a73a2ec922a2) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13MapKit) * [iOS 13 Location Permissions: CoreLocation](https://medium.com/better-programming/handling-ios-13-location-permissions-5482abc77961) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13CoreLocationChanges) * [iOS 13 On-Device Speech Recognition](https://medium.com/better-programming/ios-speech-recognition-on-device-e9a54a4468b5) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13OnDeviceSpeechRecognition) * [Introduction To PencilKit](https://medium.com/better-programming/an-introduction-to-pencilkit-in-ios-4d40aa62ba5b) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOS13OnDeviceSpeechRecognition) * [PencilKit Meets MapKit](https://medium.com/better-programming/cropping-ios-maps-with-pencilkit-da7f7dd7ec52) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iOSMapAndPencilKit) * [iPadOS MultiWindow Support](https://medium.com/better-programming/implementing-multiple-window-support-in-ipados-5b9a3ceeac6f?source=friends_link&sk=85b7f435bc341eac7ee420bb0a9da366) | [Code](https://github.com/anupamchugh/iowncode/tree/master/iPadOSMultiWindowExample) </br> Let's connect on [Twitter](https://twitter.com/chughanupam)! </a>
153
All Subjects of 42 School
# All subjects of 42 School (Paris) __All these subjects are the exclusive property of 42 School.__<br /> Any reproduction, use outside the school context of 42 or without authorization is prohibited and may be treated as copyright infringement. __If you want to see corrections files for these projects, go [HERE](https://github.com/Binary-Hackers/42_Corrections).__ ## Norme 42 - [Norme 2.0.0](https://github.com/BenjaminSouchet/42_Subjects/blob/master/04_Norme/norme_2_0_0.pdf) - [Norme 2.0.1](https://github.com/BenjaminSouchet/42_Subjects/blob/master/04_Norme/norme_2_0_1.pdf) ## Projects ### Global - [42 Commandements (T0)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/00_Global/42_commandements.pdf) - [Piscine Reloaded (T0)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/00_Global/piscine_reloaded.pdf) - [Libft (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/00_Global/libft.pdf) - [Fillit (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/00_Global/fillit.pdf) - [Get Next Line (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/00_Global/get_next_line.pdf) ### Unix branch - [Ft_ls (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_ls.pdf) - [minishell (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/minishell.pdf) - [ft_select (Optional Project) (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_select.pdf) - [21sh (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/21sh.pdf) - [Taskmaster (Optional Project) (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/taskmaster.pdf) - [42sh (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/42sh.pdf) - [Malloc (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/malloc.pdf) - [ft_script (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_script.pdf) - [Philosophers (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/philosophers.pdf) - [Nm-otool (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/nm-otool.pdf) - [Dr Quine (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/dr_quine.pdf) - [Famine (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/famine.pdf) - [LibftASM (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/asm_lib.pdf) - [Root-me | App-Systeme (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/root_me_app_systeme.pdf) - [Root-me | Cracking (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/root_me_cracking.pdf) - [Snow Crash (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/snow_crash.pdf) - [RainFall (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/Rain-Fall.pdf) - [strace (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_strace.pdf) - [GBmu (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/GBmu.pdf) - [ft_linux (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_linux.pdf) - [little-penguin-1 (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/little_penguin_1.pdf) - [Process and Memory (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/lk_process_and_mem.pdf) - [Drivers and Interrupts (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/lk_driver_and_keyboard.pdf) - [Filesystem (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/lk_filesystem.pdf) - [KFS-1 (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/kfs_1.pdf) - [KFS-2 (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/kfs_2.pdf) - [KFS-3 (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/kfs_3.pdf) - [KFS-4 (T3) _NEW_](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/kfs_4.pdf) - [Woody Woodpacker (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/woody_woodpacker.pdf) - [ft_p (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_p.pdf) - [IRC (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_irc.pdf) - [Matt Daemon (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/Matt_daemon.pdf) - [Lem-ipc (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/lemipc.pdf) - [Zappy (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/zappy.pdf) - [ft_ping (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_ping.pdf) - [ft_traceroute (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_traceroute.pdf) - [ft_nmap (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/01_Unix/ft_nmap.pdf) ### Algorithmic branch - [Ft_printf (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/ft_printf.pdf) - [Push Swap (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/push_swap.pdf) - [Filler (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/filler.pdf) - [Lem_in (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/lem-in.pdf) - [Mod1 (Optional Project) (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/mod1.pdf) - [Corewar (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/corewar.pdf) - [Corewar Championship (Optional Project) (T0)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/corewar-championship.pdf) - [ComputorV1 (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/computorv1.pdf) - [Expert System (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/expertsystem.pdf) - [N-puzzle (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/npuzzle.pdf) - [Ft_linear_regression (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/ft_linear_regression.pdf) - [Rubik (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/rubik.pdf) - [KrpSim (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/krpsim.pdf) - [Gomoku (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/02_Algorithmic/gomoku.pdf) ### Graphic branch - [FDF (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/fdf.pdf) - [Fract'Ol (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/fract_ol.pdf) - [Wolf3D (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/wolf3d.pdf) - [RTv1 (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/rtv1.pdf) - [RT (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/rt.pdf) - [Scop (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/scop.pdf) - [42run (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/42run.pdf) - [HumanGL (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/humangl.pdf) - [Particle System (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/03_Graphic/ParticleSystem.pdf) ### Web branch - [Camagru (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/camagru.pdf) - [Matcha (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/matcha.pdf) - [Hypertube (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/hypertube.pdf) - [Friends with Benefits (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/friends_with_benefits.pdf) - [Red Tetris (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/red_tetris.pdf) - [Darkly (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/04_Web/darkly.pdf) ### OCaml branch - [H42N42 (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/05_OCaml/subject.pdf) - [ft_turing (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/05_OCaml/ft_turing.pdf) - [ft_ality (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/05_OCaml/ft_ality.pdf) ### Android / iOS branch - [Swifty Companion (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/06_Android-iOS/swifty-companion.pdf) - [Swifty Proteins (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/06_Android-iOS/swifty-protein.pdf) - [ft_hangouts (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/06_Android-iOS/ft_hangouts.pdf) ### C++ branch - [Abstract VM (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/07_CPP/abstract-vm.pdf) - [Nibbler (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/07_CPP/nibbler.pdf) - [Bomberman (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/07_CPP/bomberman.pdf) ### Unity branch - [XV (T3)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/08_Unity/XV.pdf) - [In the Shadows (T2)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/08_Unity/In_the_shadow.pdf) ### Others - [cloud-1 (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/09_Others/cloud-1.pdf) - [roger-skyline-1 (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/09_Others/roger-skyline-1.pdf) - [roger-skyline-2 (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/09_Others/roger-skyline-2.pdf) - [Docker (T1)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/09_Others/docker.pdf) - [Projet Libre (T4)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/00_Projects/09_Others/ProjetLibre.pdf) ## Piscines - [C (Languages EN & FR)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/C) - [C++ (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/CPP) - [PHP (T1)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/PHP) - [Python-Django (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/Python-Django) - [Ocaml (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/OCaml) - [Ruby On Rails (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/Ruby_On_Rails) - [Swift iOS (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/iOS_Swift) - [Unity (T2)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/01_Piscines/Unity) ## Rushes - AlCu (Not Available) - [Alum1](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/alum1.pdf) - [Arkanoid](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/arkanoid.pdf) - [Carnifex (LISP)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/Carniflex.pdf) - [Cluedo (Prolog)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/cluedo.pdf) - [Domino](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/Domino.pdf) - [Factrace](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/factrace.pdf) - [Hotrace](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/hotrace.pdf) - [Introduction to iOS](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/sujet_ios.pdf) - [Introduction to Wordpress](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/wordpress.pdf) - [LLDB](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/LLDB.pdf) - [Mexican Standoff](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/mexican_standoff.pdf) - [Puissance 4](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/puissance4.pdf) - Rage Against The aPi (Not Available) - Rush admin sys et rรฉseau 0 (Not Available) - Rush admin sys et rรฉseau 1 (Not Available) - [wong_kar_wai (2048)](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/wong_kar_wai_2048.pdf) - [YASL](https://github.com/BenjaminSouchet/42_Subjects/blob/master/02_Rushes/yasl.pdf) ## Exam C Beginner - [See all subjects (Langs : EN / FR / RO)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/03_Exam_C) ## Others - [Peer-Evaluation (Langs : EN / FR)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/05_Others/Peer-Evaluation) - [Vogsphere Manual (Langs : EN / FR)](https://github.com/BenjaminSouchet/42_Subjects/tree/master/05_Others/Vogsphere)
154
A collection of awesome loading animations
# NVActivityIndicatorView [![Build Status](https://github.com/ninjaprox/NVActivityIndicatorView/actions/workflows/ios.yml/badge.svg?event=push)](https://github.com/ninjaprox/NVActivityIndicatorView/actions/workflows/ios.yml) [![Cocoapods Compatible](https://img.shields.io/cocoapods/v/NVActivityIndicatorView.svg)](https://img.shields.io/cocoapods/v/NVActivityIndicatorView.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) โš ๏ธ Check out [LoaderUI](https://github.com/ninjaprox/LoaderUI) (ready to use with Swift Package Mananger supported) for SwiftUI implementation of this. ๐ŸŽ‰ ## Introduction `NVActivityIndicatorView` is a collection of awesome loading animations. ![Demo](https://raw.githubusercontent.com/ninjaprox/NVActivityIndicatorView/master/Demo.gif) ## Animation types | Type | Type | Type | Type | | ---------------------- | --------------------------- | ---------------------- | -------------------------- | | 1. ballPulse | 2. ballGridPulse | 3. ballClipRotate | 4. squareSpin | | 5. ballClipRotatePulse | 6. ballClipRotateMultiple | 7. ballPulseRise | 8. ballRotate | | 9. cubeTransition | 10. ballZigZag | 11. ballZigZagDeflect | 12. ballTrianglePath | | 13. ballScale | 14. lineScale | 15. lineScaleParty | 16. ballScaleMultiple | | 17. ballPulseSync | 18. ballBeat | 19. lineScalePulseOut | 20. lineScalePulseOutRapid | | 21. ballScaleRipple | 22. ballScaleRippleMultiple | 23. ballSpinFadeLoader | 24. lineSpinFadeLoader | | 25. triangleSkewSpin | 26. pacman | 27. ballGridBeat | 28. semiCircleSpin | | 29. ballRotateChase | 30. orbit | 31. audioEqualizer | 32. circleStrokeSpin | ## Installation ### Cocoapods [Cocoapods](https://cocoapods.org/#install) is a dependency manager for Swift and Objective-C Cocoa projects. To use NVActivityIndicatorView with CocoaPods, add it in your `Podfile`. ```ruby pod 'NVActivityIndicatorView' ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage#installing-carthage) is intended to be the simplest way to add frameworks to your Cocoa application. To use NVActivityIndicatorView with Carthage, add it in your `Cartfile`. ```ruby github "ninjaprox/NVActivityIndicatorView" ``` ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a tool for managing the distribution of Swift code. To use NVActivityIndicatorView with Swift Package Manger, add it to `dependencies` in your `Package.swift` ```swift dependencies: [ .package(url: "https://github.com/ninjaprox/NVActivityIndicatorView.git") ] ``` ## Migration Version [5.0.0](https://github.com/ninjaprox/NVActivityIndicatorView/releases/tag/5.0.0) comes with breaking changes. Please refer to the release note for details. ## Usage Firstly, import `NVActivityIndicatorView`. ```swift import NVActivityIndicatorView ``` ### Initialization Then, there are two ways you can create `NVActivityIndicatorView`: - By storyboard, changing class of any `UIView` to `NVActivityIndicatorView`. _**Note:** Set `Module` to `NVActivityIndicatorView`._ - By code, using initializer. All parameters other than `frame` are optional and [`NVActivityIndicatorView.DEFAULT_*`](https://nvactivityindicatorview.vinhis.me/Classes/NVActivityIndicatorView.html) are used as default values. ```swift NVActivityIndicatorView(frame: frame, type: type, color: color, padding: padding) ``` ### Control Start animating. ```swift activityIndicatorView.startAnimating() ``` Stop animating. ```swift activityIndicatorView.stopAnimating() ``` Determine if it is animating. ```swift animating = activityIndicatorView.isAnimating ``` ### Change properties In storyboard, you can change all properties in Attributes inspector tab of Utilities panel. _**Note:** Use one of values (case-insensitive) in [Animation types](#animation-types) for `Type Name`._ All properties are public so you can change them after initializing. _**Note:** All changes must be made before calling `startAnimating()`._ ## Documentation https://nvactivityindicatorview.vinhis.me/ ## Acknowledgment Thanks [Connor Atherton](https://github.com/ConnorAtherton) for inspired [Loaders.css](https://github.com/ConnorAtherton/loaders.css) and [Danil Gontovnik](https://github.com/gontovnik) for [DGActivityIndicatorView](https://github.com/gontovnik/DGActivityIndicatorView). ## License The MIT License (MIT) Copyright (c) 2016 Vinh Nguyen [@ninjaprox](http://twitter.com/ninjaprox)
155
Reference and documentation for Perfect (Server-side Swift). Perfect (ๆ”ฏๆŒๆœๅŠกๅ™จ็ซฏSwift่ฏญ่จ€็š„่ฝฏไปถๅ‡ฝๆ•ฐๅบ“๏ผ‰ไฝฟ็”จๆ–‡ๆกฃๅ’Œๅ‚่€ƒๆ‰‹ๅ†Œ.
# Perfect Documentation Library [็ฎ€ไฝ“ไธญๆ–‡](README.zh_CN.md) <p align="center"> <a href="http://perfect.org/get-involved.html" target="_blank"> <img src="http://perfect.org/assets/github/perfect_github_2_0_0.jpg" alt="Get Involved with Perfect!" width="854" /> </a> </p> <p align="center"> <a href="https://github.com/PerfectlySoft/Perfect" target="_blank"> <img src="http://www.perfect.org/github/Perfect_GH_button_1_Star.jpg" alt="Star Perfect On Github" /> </a> <a href="http://stackoverflow.com/questions/tagged/perfect" target="_blank"> <img src="http://www.perfect.org/github/perfect_gh_button_2_SO.jpg" alt="Stack Overflow" /> </a> <a href="https://twitter.com/perfectlysoft" target="_blank"> <img src="http://www.perfect.org/github/Perfect_GH_button_3_twit.jpg" alt="Follow Perfect on Twitter" /> </a> <a href="http://perfect.ly" target="_blank"> <img src="http://www.perfect.org/github/Perfect_GH_button_4_slack.jpg" alt="Join the Perfect Slack" /> </a> </p> <p align="center"> <a href="https://developer.apple.com/swift/" target="_blank"> <img src="https://img.shields.io/badge/Swift-4.1-orange.svg?style=flat" alt="Swift 4.1"> </a> <a href="https://developer.apple.com/swift/" target="_blank"> <img src="https://img.shields.io/badge/Platforms-OS%20X%20%7C%20Linux%20-lightgray.svg?style=flat" alt="Platforms OS X | Linux"> </a> <a href="http://perfect.org/licensing.html" target="_blank"> <img src="https://img.shields.io/badge/License-Apache-lightgrey.svg?style=flat" alt="License Apache"> </a> <a href="http://twitter.com/PerfectlySoft" target="_blank"> <img src="https://img.shields.io/badge/[email protected]?style=flat" alt="PerfectlySoft Twitter"> </a> <a href="http://perfect.ly" target="_blank"> <img src="http://perfect.ly/badge.svg" alt="Slack Status"> </a> </p> This library contains all the reference documentation and API reference-related material you need to run and use Perfect. ## Table of Contents * [Introduction](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/introduction.md) * [Getting Started](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/gettingStarted.md) * [Getting Started From Scratch](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/gettingStartedFromScratch.md) * [An HTTP and Web Services Primer](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/WebServicesPrimer.md) * [Repository Layout](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/repositoryLayout.md) * [Building with Swift Package Manager](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/buildingWithSPM.md) * [Configuring and Launching HTTPServer](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HTTPServer.md) * [Handling Requests](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/handlingRequests.md) * [Routing](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/routing.md) * [HTTPRequest](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HTTPRequest.md) * [Using Form Data](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/formData.md) * [File Uploads](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/fileUploads.md) * [HTTPResponse](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HTTPResponse.md) * [Request &amp; Response Filters](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/filters.md) * [Web Redirect Filters](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/webRedirects.md) * [Sessions](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/sessions.md) * [CSRF Security](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/csrf.md) * [CORS Security](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/cors.md) * [Local Authentication modules](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/authentication.md) * [GSS-SPNEGO Security Feature](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/SPNEGO.md) * [JSON](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/JSON.md) * [Static File Content](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/staticFileContent.md) * [Mustache](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/mustache.md) * [Markdown](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Markdown.md) * [HTTP Request Logging](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HTTPRequestLogging.md) * [CRUD](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/crud.md) * [WebSockets](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/webSockets.md) * [Utilities](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/utilities.md) * [Bytes](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/bytes.md) * [File](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/file.md) * [Dir](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/dir.md) * [Environmental Variables](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/env.md) * [Threading](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/thread.md) * [Networking](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/net.md) @kjessup * [OAuth2 and Providers](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/OAuth2.md) * [UUID](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/UUID.md) * [SysProcess](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/sysProcess.md) * [Log](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/log.md) * [Log Files](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/logFiles.md) * [Remote Logging](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/logRemote.md) * [CURL](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/cURL.md) * [XML](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/xml.md) * [INI](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/ini.md) * [Zip](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/zip.md) * [Crypto](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/crypto.md) * [SMTP](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/SMTP.md) * [Google Analytics Measurement Protocol](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/GoogleAnalytics.md) * [Repeater](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/repeater.md) * [Database Connectors](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/databaseConnectors.md) * [SQLite](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/SQLite.md) * [MySQL](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MySQL.md) * [MariaDB](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MariaDB.md) * [PostgreSQL](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/PostgreSQL.md) * [MongoDB](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB.md) * [MongoDB Databases](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB-Database.md) * [MongoDB Collections](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB-Collections.md) * [MongoDB Client](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB-Client.md) * [Working with BSON](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB-BSON.md) * [GridFS](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/MongoDB-GridFS.md) * [CouchDB](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/CouchDB.md) * [LDAP](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/LDAP.md) * [Redis](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Redis.md) @kjessup * [FileMaker](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/filemaker.md) * [iOS Notifications](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/iOSNotifications.md) @kjessup * [Deployment](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/deployment.md) * [Ubuntu](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/deployment-Ubuntu.md) * Docker * [Heroku](https://github.com/PerfectlySoft/Perfect/wiki/Deploying-with-Heroku) * Azure * AWS * Linode * [Digital Ocean](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/deployment-DigitalOcean.md) * Performance Profiling & Remote Monitoring * [SysInfo](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/SYSINFO.md) * [New Relic](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/NEWRELIC.md) * Message Queue & Cluster Control * [Kafka](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Kafka.md) * [Mosquitto](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/mosquitto.md) * [ZooKeeper (Linux Only)](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/ZooKeeper.md) * Big Data / Artificial Intelligence & Machine Learning * [TensorFlow](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/tensorflow.md) * [Hadoop](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Hadoop.md) * [HDFS](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HadoopWebHDFS.md) * [MapReduce Master](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HadoopMapReduceMaster.md) * [MapReduce History](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HadoopMapReduceHistory.md) * [YARN Node Manager](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HadoopYARNNodeManager.md) * [YARN Resource Manager](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/HadoopYARNResourceManager.md) * Platform specific Notes * [Ubuntu 16.04: Starting Services at System Boot](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/starting-services.md) * Language Extensions: * [Python](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/python.md) ## StORM, a Swift ORM StORM is not distributed as a Perfect.org project; however, the Perfect libraries are integral to its operation, and some authors are common. * [StORM, a Swift ORM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM.md) * [Introduction to StORM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM.md) * [Setting up a class](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-Setting-up-a-class.md) * [Saving, Retrieving and Deleting Rows](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-Saving-Retrieving-and-Deleting-Rows.md) * [StORMCursor](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-Cursor.md) * [Inserting rows](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-Insert.md) * [Updating rows](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-Update.md) * [StORM Lifecycle Events](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORMLifecycleEvents.md) * Database Specific Implementations * [PostgresStORM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-PostgreSQL.md) * [SQLiteStORM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-SQLite.md) * [MySQLStORM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-MySQL.md) * [Apache CouchDB](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-CouchDB.md) * [MongoDBStoRM](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/StORM-MongoDB.md) ## Perfect Turnstile โ€“ an authentication layer for Perfect [Turnstile](https://github.com/stormpath/Turnstile) is an Open Source project from [Stormpath](https://github.com/stormpath) focussing on standardizing authentication across platforms and frameworks. Thanks to work done by [Edward Jiang](https://github.com/edjiang) on Turnstile and a foundation linking Turnstile with Perfect, an authentication layer is available for Perfect. **โš ๏ธNOTEโš ๏ธ** Turnstile is out of service as declared by its author, please check [Storm API Migration FAQ](https://stormpath.com/oktaplusstormpath?utm_source=github&utm_medium=readme&utm-campaign=okta-announcement) for more information. * [Perfect-Turnstile](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Turnstile.md) * [Perfect Turnstile with SQLite Integration](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Turnstile.md) * [Perfect Turnstile with PostgreSQL Integration](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Turnstile.md) * [Perfect Turnstile with MySQL Integration](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Turnstile.md) * [Perfect Turnstile with CouchDB Integration](https://github.com/PerfectlySoft/PerfectDocs/blob/master/guide/Turnstile.md)
156
A repository of different Algorithms and Data Structures implemented in many programming languages.
# Data Structures and Algorithms Clean example implementations of data structures and algorithms written in different languages. <br><br> [![Gitter chat](https://badges.gitter.im/VAR-solutions/Algorithms.png)](https://gitter.im/VAR-solutions/Algorithms "Gitter chat") [![MIT license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) [![Issues](http://img.shields.io/github/issues/VAR-solutions/Algorithms.svg)](https://github.com/VAR-solutions/Algorithms/issues) #### List of implementations [Algorithms list(not updated)](#) ## Contribution! * Contributions are always welcome. Language doesn't matter. Just make sure you're implementing an algorithm. * PRs are welcome. To begin developing, follow the structure: > Algorithm-Type/algorithm-name/language-name/file-name.extension e.g > Sorting/bubble-sort/python/bubble-sort.py * If there is an implementation of the same algorithm in your language, do not give a PR for that. * Please include a description for the algorithm that you are implementing. It doesn't matter if it's copied from somewhere as long as it helps people that are learning new algorithm. * Graphical examples would be very helpful too. * You can include tests as well. * Don't remove previous implementations of algorithms. Just add a new file with your own implementation. * Beautify and clean up your code for easier reading ### Note: * If your PR is closed without any comment, it means that your PR does not meet the above criteria. Make sure your PR is **not Duplicate** and it should be **well-documented**. ## Resources The curated list of resources dealing with algorithms. * **Sites** * [Algorithms - Tutorials point](https://www.tutorialspoint.com/data_structures_algorithms/index.htm) * [Algorithms - Princetone edu](http://algs4.cs.princeton.edu/home/) * [Data structures and algorithms - Hackr](https://hackr.io/tutorials/learn-data-structures-algorithms) * [Data science - Topcoder](https://www.topcoder.com/community/data-science/data-science-tutorials/) * [Fundamentals Of Algorithms- Geeks For Geeks](http://www.geeksforgeeks.org/fundamentals-of-algorithms/) * [Visual Algorithm - visualising data structures and algorithms through animation](https://visualgo.net/en) * [Rosetta Code](http://rosettacode.org/wiki/Rosetta_Code) * [GeeksforGeeks](https://www.geeksforgeeks.org) * **Online classes (Free)** * Coursera * [Introduction to algorithms Part 1](https://www.coursera.org/learn/algorithms-part1) * [Algorithms specialization 4 courses](https://www.coursera.org/specializations/algorithms) * Khan Academy * [Algorithms](https://www.khanacademy.org/computing/computer-science/algorithms) * Udacity * [Computability, Complexity & Algorithms](https://www.udacity.com/course/computability-complexity-algorithms--ud061) * [Intro to algorithms](https://www.udacity.com/course/intro-to-algorithms--cs215) * EdX * [Algorithms](https://www.edx.org/course/algorithms-iitbombayx-cs213-3x-0) * [Algorithms and data structures](https://www.edx.org/course/algorithms-data-structures-microsoft-dev285x) * [Algorithm Design and Analysis](https://courses.edx.org/courses/course-v1:PennX+SD3x+2T2017/course/) * [Graph Algorithms](https://www.edx.org/course/graph-algorithms-uc-san-diegox-algs202x) * [Data Structures](https://www.edx.org/course/data-structures-uc-san-diegox-algs201x) * [Algorithmic Design and Techniques](https://www.edx.org/course/algorithmic-design-techniques-uc-san-diegox-algs200x) * [String Processing and Pattern Matching Algorithms](https://www.edx.org/course/string-processing-pattern-matching-uc-san-diegox-algs204x) * [Graph Algorithms in Genome Sequencing](https://www.edx.org/course/graph-algorithms-genome-sequencing-uc-san-diegox-algs206x) * [Algorithms and Data Structures Capstone](https://www.edx.org/course/algorithms-data-structures-capstone-uc-san-diegox-algs207x) * [Data Structures](https://www.youtube.com/user/mycodeschool) * [Algorithms and Data Structures Capstone](https://www.edx.org/course/algorithms-data-structures-capstone-uc-san-diegox-algs207x) * [Data Structures and Algorithms](https://www.programiz.com/dsa) * GeeksForGeeks * [Algorithms](https://www.geeksforgeeks.org/fundamentals-of-algorithms/) * **Coding Practice Sites** * [HackerRank](https://www.hackerrank.com/) * [HackerEarth](https://www.hackerearth.com/) * [SPOJ](http://www.spoj.com/) * [TopCoder](https://www.topcoder.com/) * [CodeChef](https://www.codechef.com/) * [Codeforces](http://codeforces.com/) * [Project Euler](https://projecteuler.net/) * [LeetCode](https://leetcode.com/) * [CodinGame](https://www.codingame.com/) * [CodeWars](https://codewars.com/) * [Coderbyte](https://www.coderbyte.com/) * [HireVue](https://www.hirevue.com/) * [FreeCodeCamp](https://www.freecodecamp.org/) * [CodeSignal](https://codesignal.com/) * [AtCoder](https://atcoder.jp/) # Project Maintainers. * [Vishal Gaur](https://github.com/i-vishi) :tada:<br> * [Ravi Varshney](https://github.com/ravivarshney01) :tada:<br> * [Ananya Tewari](https://github.com/antew7) :tada:<br>
157
A simple way to create a UITableView for settings in Swift.
# QuickTableViewController [![GitHub Actions](https://github.com/bcylin/QuickTableViewController/workflows/CI/badge.svg)](https://github.com/bcylin/QuickTableViewController/actions) [![Codecov](https://img.shields.io/codecov/c/github/bcylin/QuickTableViewController)](https://codecov.io/gh/bcylin/QuickTableViewController) [![Carthage compatible](https://img.shields.io/badge/carthage-compatible-green.svg)](https://github.com/Carthage/Carthage) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/QuickTableViewController.svg)](https://cocoapods.org/pods/QuickTableViewController) [![Platform](https://img.shields.io/cocoapods/p/QuickTableViewController?label=docs)](https://bcylin.github.io/QuickTableViewController) ![Swift 5](https://img.shields.io/badge/Swift-5-orange.svg) A simple way to create a table view for settings, including: * Table view cells with `UISwitch` * Table view cells with center aligned text for tap actions * A section that provides mutually exclusive options * Actions performed when the row reacts to the user interaction * Easy to specify table view cell image, cell style and accessory type <img src="https://raw.githubusercontent.com/bcylin/QuickTableViewController/gh-pages/img/screenshots.png" width="80%"></img> ## Usage Set up `tableContents` in `viewDidLoad`: ```swift import QuickTableViewController final class ViewController: QuickTableViewController { override func viewDidLoad() { super.viewDidLoad() tableContents = [ Section(title: "Switch", rows: [ SwitchRow(text: "Setting 1", switchValue: true, action: { _ in }), SwitchRow(text: "Setting 2", switchValue: false, action: { _ in }) ]), Section(title: "Tap Action", rows: [ TapActionRow(text: "Tap action", action: { [weak self] in self?.showAlert($0) }) ]), Section(title: "Navigation", rows: [ NavigationRow(text: "CellStyle.default", detailText: .none, icon: .named("gear")), NavigationRow(text: "CellStyle", detailText: .subtitle(".subtitle"), icon: .named("globe")), NavigationRow(text: "CellStyle", detailText: .value1(".value1"), icon: .named("time"), action: { _ in }), NavigationRow(text: "CellStyle", detailText: .value2(".value2")) ], footer: "UITableViewCellStyle.Value2 hides the image view."), RadioSection(title: "Radio Buttons", options: [ OptionRow(text: "Option 1", isSelected: true, action: didToggleSelection()), OptionRow(text: "Option 2", isSelected: false, action: didToggleSelection()), OptionRow(text: "Option 3", isSelected: false, action: didToggleSelection()) ], footer: "See RadioSection for more details.") ] } // MARK: - Actions private func showAlert(_ sender: Row) { // ... } private func didToggleSelection() -> (Row) -> Void { return { [weak self] row in // ... } } } ``` ### NavigationRow #### Detail Text Styles ```swift NavigationRow(text: "UITableViewCellStyle.default", detailText: .none) NavigationRow(text: "UITableViewCellStyle", detailText: .subtitle(".subtitle") NavigationRow(text: "UITableViewCellStyle", detailText: .value1(".value1") NavigationRow(text: "UITableViewCellStyle", detailText: .value2(".value2")) ``` [`Subtitle`](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/Model/Subtitle.swift) and the [initializers with title/subtitle](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/Model/Deprecated.swift) are deprecated and will be removed in **v2.0.0**. #### Accessory Type * The `NavigationRow` shows with different accessory types based on the `action` and `accessoryButtonAction` closures: ```swift var accessoryType: UITableViewCell.AccessoryType { switch (action, accessoryButtonAction) { case (nil, nil): return .none case (.some, nil): return .disclosureIndicator case (nil, .some): return .detailButton case (.some, .some): return .detailDisclosureButton } } ``` * The `action` will be invoked when the table view cell is selected. * The `accessoryButtonAction` will be invoked when the accessory button is selected. #### Images ```swift enum Icon { case named(String) case image(UIImage) case images(normal: UIImage, highlighted: UIImage) } ``` * Images in table view cells can be set by specifying the `icon` of each row. * Table view cells in `UITableViewCellStyle.value2` will not show the image view. ### SwitchRow * A `SwitchRow` is representing a table view cell with a `UISwitch` as its `accessoryView`. * The `action` will be invoked when the switch value changes. ### TapActionRow * A `TapActionRow` is representing a button-like table view cell. * The `action` will be invoked when the table view cell is selected. * The icon, detail text, and accessory type are disabled in `TapActionRow`. ### OptionRow * An `OptionRow` is representing a table view cell with `.checkmark`. * The `action` will be invoked when the selected state is toggled. ```swift let didToggleSelection: (Row) -> Void = { [weak self] in if let option = $0 as? OptionRowCompatible, option.isSelected { // to exclude the event where the option is toggled off } } ``` ### RadioSection * `RadioSection` allows only one selected option at a time. * Setting `alwaysSelectsOneOption` to true will keep one of the options selected. * `OptionRow` can also be used with `Section` for multiple selections. ## Customization ### Rows All rows must conform to [`Row`](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/Protocol/Row.swift) and [`RowStyle`](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/Protocol/RowStyle.swift). Additional interface to work with specific types of rows are represented as different [protocols](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/Protocol/RowCompatible.swift): * `NavigationRowCompatible` * `OptionRowCompatible` * `SwitchRowCompatible` * `TapActionRowCompatible` ### Cell Classes A customized table view cell type can be specified to rows during initialization. ```swift // Default is UITableViewCell. NavigationRow<CustomCell>(text: "Navigation", detailText: .none) // Default is SwitchCell. SwitchRow<CustomSwitchCell>(text: "Switch", switchValue: true, action: { _ in }) // Default is TapActionCell. TapActionRow<CustomTapActionCell>(text: "Tap", action: { _ in }) // Default is UITableViewCell. OptionRow<CustomOptionCell>(text: "Option", isSelected: true, action: { _ in }) ``` Since the rows carry different cell types, they can be matched using either the concrete types or the related protocol: ```swift let action: (Row) -> Void = { switch $0 { case let option as OptionRow<CustomOptionCell>: // only matches the option rows with a specific cell type case let option as OptionRowCompatible: // matches all option rows default: break } } ``` ### Overwrite Default Configuration You can use `register(_:forCellReuseIdentifier:)` to specify custom cell types for the [table view](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/QuickTableViewController.swift#L100-L102) to use. See [CustomizationViewController](https://github.com/bcylin/QuickTableViewController/blob/develop/Example-iOS/ViewControllers/CustomizationViewController.swift) for the cell reuse identifiers of different rows. Table view cell classes that conform to `Configurable` can take the customization during `tableView(_:cellForRowAt:)`: ```swift protocol Configurable { func configure(with row: Row & RowStyle) } ``` Additional setups can also be added to each row using the `customize` closure: ```swift protocol RowStyle { var customize: ((UITableViewCell, Row & RowStyle) -> Void)? { get } } ``` The `customize` closure [overwrites](https://github.com/bcylin/QuickTableViewController/blob/develop/Source/QuickTableViewController.swift#L104-L109) the `Configurable` setup. ### UIAppearance As discussed in issue [#12](https://github.com/bcylin/QuickTableViewController/issues/12), UIAppearance customization works when the cell is dequeued from the storyboard. One way to work around this is to register nib objects to the table view. Check out [AppearanceViewController](https://github.com/bcylin/QuickTableViewController/blob/develop/Example-iOS/ViewControllers/AppearanceViewController.swift) for the setup. ## tvOS Differences * `UISwitch` is replaced by a checkmark in `SwitchCell`. * `TapActionCell` does not use center aligned text. * `NavigationRow.accessoryButtonAction` is not available. * Cell image view's left margin is 0. ## Limitation > When to use **QuickTableViewController**? QuickTableViewController is good for presenting static table contents, where the sections and rows don't change dynamically after `viewDidLoad`. It's possible to update the table contents by replacing a specific section or row. Using different styles on each row requires additional configuration as described in the [Customization](#customization) section. > When **not** to use it? QuickTableViewController is not designed for inserting and deleting rows. It doesn't handle table view reload animation either. If your table view needs to update dynamically, you might want to consider other solutions such as [IGListKit](https://github.com/Instagram/IGListKit). ## Documentation * [QuickTableViewController Reference](https://bcylin.github.io/QuickTableViewController) ## Requirements <details><summary><b>Pre 1.0 versions</b></summary> QuickTableViewController | iOS | tvOS | Xcode | Swift ------------------------ | :--: | :--: | :---: | :---: `~> 0.1.0` | 8.0+ | - | 6.4 | 1.2 `~> 0.2.0` | 8.0+ | - | 7.0 | 2.0 `~> 0.3.0` | 8.0+ | - | 7.3 | 2.2 `~> 0.4.0` | 8.0+ | - | 8.0 | 2.3 `~> 0.5.0` | 8.0+ | - | 8.0 | 3.0 `~> 0.6.0` | 8.0+ | - | 8.3 | 3.1 `~> 0.7.0` | 8.0+ | - | 9.0 | 3.2 `~> 0.8.0` | 8.0+ | - | 9.1 | 4.0 `~> 0.9.0` | 8.0+ | - | 9.3 | 4.1 </details><br> QuickTableViewController | iOS | tvOS | Xcode | Swift ------------------------ | :--: | :--: | :---: | :---: `~> 1.0.0` | 8.0+ | 9.0+ | 9.4 | 4.1 `~> 1.1.0` | 8.0+ | 9.0+ | 10.1 | 4.2 `~> 1.2.0` | 8.0+ | 9.0+ | 10.2 | 5.0 `~> 1.3.0` | 9.0+ | 9.0+ | 11.7 | 5.2 ## Installation ### Use Swift Package Manager Follow the instructions at [Adding Package Dependencies to Your App](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app) and use version `v1.2.1` or later. (requires Xcode 11) ### Use [CocoaPods](https://guides.cocoapods.org) Create a `Podfile` with the following specification and run `pod install`. ```rb platform :ios, '9.0' use_frameworks! pod 'QuickTableViewController' ``` ### Use [Carthage](https://github.com/Carthage/Carthage) Create a `Cartfile` with the following specification and run `carthage update QuickTableViewController`. Follow the [instructions](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application) to add the framework to your project. ``` github "bcylin/QuickTableViewController" ``` Xcode 12 workaround Guide: https://github.com/Carthage/Carthage/blob/master/Documentation/Xcode12Workaround.mdx ### Use Git Submodule ``` git submodule add -b master [email protected]:bcylin/QuickTableViewController.git Dependencies/QuickTableViewController ``` * Drag **QuickTableViewController.xcodeproj** to your app project as a subproject. * On your application target's **Build Phases** settings tab, add **QuickTableViewController-iOS** to **Target Dependencies**. ## License QuickTableViewController is released under the MIT license. See [LICENSE](https://github.com/bcylin/QuickTableViewController/blob/master/LICENSE) for more details. Image source: [iconmonstr](https://iconmonstr.com/license).
158
Smallest AppDelegate ever by using a decoupled-services based architecture. ๐Ÿ› 
# PluggableApplicationDelegate [![CI Status](http://img.shields.io/travis/fmo91/PluggableApplicationDelegate.svg?style=flat)](https://travis-ci.org/fmo91/PluggableApplicationDelegate) [![Version](https://img.shields.io/cocoapods/v/PluggableApplicationDelegate.svg?style=flat)](http://cocoapods.org/pods/PluggableApplicationDelegate) [![License](https://img.shields.io/cocoapods/l/PluggableApplicationDelegate.svg?style=flat)](http://cocoapods.org/pods/PluggableApplicationDelegate) [![Platform](https://img.shields.io/cocoapods/p/PluggableApplicationDelegate.svg?style=flat)](http://cocoapods.org/pods/PluggableApplicationDelegate) ## Introduction `AppDelegate` is a traditional example of bad code. Lots of line of code that makes so much different things are put together in methods that are called within the application life cycle. But all of those concerns are over. Using `PluggableApplicationDelegate` you decouple AppDelegate from the services that you plug to it. Each `ApplicationService` has its own life cycle that is shared with `AppDelegate`. ## At a glance Let see some code. Here is how a `ApplicationService` is like: ```swift import Foundation import PluggableApplicationDelegate final class LoggerApplicationService: NSObject, ApplicationService { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { print("It has started!") return true } func applicationDidEnterBackground(_ application: UIApplication) { print("It has entered background") } } ``` That's all. **It is exactly the same as a AppDelegate**. Think of `ApplicationService` as sub-AppDelegates. In `AppDelegate` you just have to inherit from PluggableApplicationDelegate to register the services. ```swift import UIKit import PluggableApplicationDelegate @UIApplicationMain class AppDelegate: PluggableApplicationDelegate { override var services: [ApplicationService] { return [ LoggerApplicationService() ] } } ``` Yes. That's all. Simple. ## How does this work? You may want to read my [Medium post about Pluggable App Delegate](https://medium.com/ios-os-x-development/pluggableapplicationdelegate-e50b2c5d97dd#.sz50l4d0l). Basically, you do an inversion of control. Instead of let AppDelegate instantiate your dependencies, perform actions at every step of its life cycle, you create objects that share the AppDelegate life cycle and plug them into your AppDelegate. Those objects are observers of the AppDelegate. Your AppDelegate has the only responsibility of notify them about its life cycle events. ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements PluggableApplicationDelegate requires Swift 3.0 or above. ## Installation PluggableApplicationDelegate is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod 'PluggableApplicationDelegate' ``` ## Author fmo91, [email protected] ## License PluggableApplicationDelegate is available under the MIT license. See the LICENSE file for more info.
159
Easily craft fast Neural Networks on iOS! Use TensorFlow models. Metal under the hood.
# Bender <p align="left"> <a href="https://travis-ci.org/xmartlabs/Bender"><img src="https://travis-ci.org/xmartlabs/Bender.svg?branch=master" alt="Build status" /></a> <img src="https://img.shields.io/badge/platform-iOS-blue.svg?style=flat" alt="Platform iOS" /> <a href="https://developer.apple.com/swift"><img src="https://img.shields.io/badge/swift4-compatible-4BC51D.svg?style=flat" alt="Swift 4 compatible" /></a> <a href="https://cocoapods.org/pods/MetalBender"><img src="https://img.shields.io/cocoapods/v/MetalBender.svg" alt="CocoaPods compatible" /></a> <a href="https://github.com/Carthage/Carthage"><img src="https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat" alt="Carthage compatible" /></a> <a href="https://raw.githubusercontent.com/xmartlabs/Bender/master/LICENSE"><img src="http://img.shields.io/badge/license-MIT-blue.svg?style=flat" alt="License: MIT" /></a> <a href="https://app.fossa.io/projects/git%2Bgithub.com%2Fxmartlabs%2FBender?ref=badge_shield" alt="FOSSA Status"><img src="https://app.fossa.io/api/projects/git%2Bgithub.com%2Fxmartlabs%2FBender.svg?type=shield"/></a> </p> ![Bender](Documentation/Media/Artboard.png) Bender is an abstraction layer over MetalPerformanceShaders useful for working with neural networks. ## Contents * [Introduction](#introduction) * [Why did we need Bender](#why) * [Basic usage](#usage) * [Requirements](#requirements) * [Getting involved](#getting-involved) * [Examples](#examples) * [Installation](#installation) * [Changelog](#change-log) The documentation can be found under the `Documentation` folder: * [API](Documentation/API.md) contains the most important information to get started. * [Supported Layers] explains which layers are supported and how they map to TensorFlow ops. * [Importing] explains how to import models from other frameworks such as TensorFlow. You can also find information on how to enhance this functionality for custom implementations. ## Introduction Bender is an abstraction layer over MetalPerformanceShaders which is used to work with neural networks. It is of growing interest in the AI environment to execute neural networks on mobile devices even if the training process has been done previously. We want to make it easier for everyone to execute pretrained networks on iOS. Bender allows you to easily define and run neural networks using the most common layers like Convolution, Pooling, FullyConnected and some normalizations among others. It is also flexible in the way it receives the parameters for these layers. We also want to support loading models trained on other frameworks such as TensorFlow or Caffe2. Currently Bender includes an adapter for TensorFlow that loads a graph with variables and "translates" it to Bender layers. This feature supports a subset of TensorFlow's operations but we plan to enhance it to cover more cases. ## Why did we need Bender? <a name="why"></a> At [Xmartlabs] we were about to start a Machine Learning project and investigated frameworks to use in iOS. We found MetalPerformanceShaders useful but not very user friendly and we saw ourselves repeating a lot of code and information. That is why we starting building a framework to handle that kind of stuff. We also found ourselves creating scripts to translate the models we had from training with TensorFlow to iOS. This means transposing the weights to the MPSCNN format and also mapping the parameters of the different kinds of layers in TensorFlow to the parameters used by the MPSCNN kernels. TensorFlow can be compiled for iOS but currently it does not support running on GPU which we wanted to do. We also did not want to include TensorFlow's static library into our project. This is why we also started to work on an adapter that would parse a TF graph and translate it to our Bender layers. ## Usage You can define your own network in Bender using our custom operator or you can load a model exported from TensorFlow. Defining a network and loading a model can be done like this: ```swift import MetalBender let url = Bundle.main.url(forResource: "myModel", withExtension: "pb")! // A TensorFlow model. let network = Network.load(url: url, inputSize: LayerSize(h: 256, w: 256, f: 3)) network.run(input: /* ... */) { output in // ... } ``` You can read more information about this in [Importing](Documentation/Importing.md). If you want to define your network yourself you can do it like this: ```swift let network = Network(inputSize: LayerSize(h: 256, w: 256, f: 3)) network.start ->> Convolution(convSize: ConvSize(outputChannels: 16, kernelSize: 3, stride: 2)) ->> InstanceNorm() ->> Convolution(convSize: ConvSize(outputChannels: 32, kernelSize: 3, stride: 2), neuronType: .relu) ->> InstanceNorm() ->> FullyConnected(neurons: 128) ->> Neuron(type: .tanh) ->> FullyConnected(neurons: 10) ->> Softmax() // ... ``` and once you're done with all your layers: ```swift network.initialize() ``` To know more about this have a look at [API](Documentation/API.md). ## Requirements * Xcode 9 * iOS 11.0+ (but deployment target is iOS 10.0, so iOS 10 is supported) ## Getting involved * If you **want to contribute** please feel free to **submit pull requests**. * If you **have a feature request** please **open an issue**. * If you **found a bug** or **need help** please **check older issues, [FAQ](#faq) and threads on [StackOverflow](https://stackoverflow.com) before submitting an issue**. Before contribute check the [CONTRIBUTING] file for more info. If you use **Bender** in your app We would love to hear about it! Drop us a line on [Twitter](https://twitter.com/xmartlabs). ## Examples Follow these steps to run the examples: * Clone Bender repository (or download it). * Run `carthage update --platform iOS` in the downloaded folder. * Open Bender workspace and run the *Example* project. > There is an Image recognition example which includes a MobileNet model in Bender and one in CoreML. It is also set up to run an Inception model but you will have to download it separately as it is almost 100 MB in size. You can download it from http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz but then you have to freeze it and add it to the 'Example' Xcode project as 'inception_v3.pb'. ## Installation #### CocoaPods To install Bender, simply add the following line to your Podfile: ```ruby pod 'MetalBender', '~> 0.5' ``` > Remember that Bender compiles for iOS 10. So you must add `platform :ios, '10.0'` to your Podfile #### Carthage [Carthage](https://github.com/Carthage/Carthage) is a simple, decentralized dependency manager for Cocoa. To install Bender, add the following line to your Cartfile: ```ogdl github "xmartlabs/Bender" ~> 0.5 ``` Then run: ```bash carthage update --platform iOS ``` Finally, drag the built `.framework` binaries for `MetalBender`, `MetalPerformanceShadersProxy` and `SwiftProtobuf` to your application's Xcode project. ## Author * [Xmartlabs SRL](https://github.com/xmartlabs) ([@xmartlabs](https://twitter.com/xmartlabs)) # Change Log This can be found in the [CHANGELOG.md](CHANGELOG.md) file. <!-- Links --> [Xmartlabs]: http://xmartlabs.com [Importing]: Documentation/Importing.md [CONTRIBUTING]: .github/CONTRIBUTING.md [API]: Documentation/API.md [Supported Layers]: Documentation/Supported_Layers.md ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fxmartlabs%2FBender.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fxmartlabs%2FBender?ref=badge_large)
160
๐Ÿ’พ A collection of classic-style UI components for iOS
# ![ClassicKit](Images/logo.png) A collection of classic-style UI components for UIKit, influenced by Windows 95 ![about](Images/about.png) ![portrait](Images/portrait.png) ![landscape](Images/landscape.png) ## Introduction This is a little exploration into applying '90s-era design & principles into a modern platform with some primitive components. The assets and design metrics were (for the most part) taken from an actual installation of Windows 95. These are pixel-accurate renditions of the original design: ![](Images/pixel.png) **Update:** - (3/17) Added a simple Blue Screen of Death! Simply shake the device vigorously. ## Usage - The `Browser` example can be run out-of-the-box. - You _should_ be able to include some or all of the files under `/Components` in your project. - Each component is intended to be used like their UIKit counterparts. For example, `CKButton` should respond to gesture events just as `UIButton` would. - These are `@IBDesignable` components! That means you can lay out your entire app with these components in Interface Builder and Xcode will render them for you: ![xcode](Images/xcode.png) ## Notes & FAQ - This project is very much a work-in-progress. Although it was designed with modularity and robustness in mind, there are no guarantees on reliability. - **Q: Why did you do this?** - This project was born out of some wholesome sarcasm and Millennial jokes with [Ben Galassi.](http://bengalassi.com) Check out his work! - **Q: If this project is made for Apple devices, why based it on Microsoft's design?** - Most people were using Windows during this age and far more people recognize the Windows Standard design pattern than Platinum. If you need any proof, [PCs sold close to 100 million units in 1998, compared to just 2.7 million for Macintosh.](https://arstechnica.com/features/2005/12/total-share/8/) - I may revisit this point in the future. - **Q: Why isn't the UI rendering in my Storyboard?** - Interface Builder is very finicky. Rendering typically fails because the underlying code has an error or a constraint cannot be satisfied. Even if you fix these issues, you may have to clear the cache and restart Xcode. - **Q: Why do I need YYImage?** - You don't. `YYImage` is used in `CKImageView` to animate the throbber animation in the `Browser` example, but you can remove the reference in `CKImageView.swift`. Eventually this dependency will be removed. - Please let me know if you have any questions or comments! I'd also love to chat about design or tech nostalgia ๐Ÿ™‚ ## Disclaimer I do not claim ownership of the assets or logos used in this project. Windows and Internet Explorer are registered trademarks of Microsoft Inc. ## License MIT
161
Run compilers interactively from your web browser and interact with the assembly
[![Build Status](https://github.com/compiler-explorer/compiler-explorer/workflows/Compiler%20Explorer/badge.svg)](https://github.com/compiler-explorer/compiler-explorer/actions?query=workflow%3A%22Compiler+Explorer%22) [![codecov](https://codecov.io/gh/compiler-explorer/compiler-explorer/branch/main/graph/badge.svg)](https://codecov.io/gh/compiler-explorer/compiler-explorer) ![Compiler Explorer](views/resources/site-logo.svg) # Compiler Explorer **Compiler Explorer** is an interactive compiler exploration website. Edit code in C, C++, C#, F#, Rust, Go, D, Haskell, Swift, Pascal, [ispc](https://ispc.github.io/), Python, Java or in any of the other [30+ supported languages](https://godbolt.org/api/languages), and see how that code looks after being compiled in real time. Multiple compilers are supported for each language, many different tools and visualisations are available, and the UI layout is configurable (thanks to [GoldenLayout](https://www.golden-layout.com/)). Try out at [godbolt.org](https://godbolt.org), or [run your own local instance](#running-a-local-instance). **Compiler Explorer** follows a [Code of Conduct](CODE_OF_CONDUCT.md) which aims to foster an open and welcoming environment. **Compiler Explorer** was started in 2012 to show how C++ constructs translated to assembly code. It started out as a `tmux` session with `vi` running in one pane and `watch gcc -S foo.cc -o -` running in the other. Since then, it has become a public website serving around [3,000,000 compilations per week](https://www.stathat.com/cards/Tk5csAWI0O7x). You can financially support [this project on Patreon](https://patreon.com/mattgodbolt), [GitHub](https://github.com/sponsors/mattgodbolt/), [Paypal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=KQWQZ7GPY2GZ6&item_name=Compiler+Explorer+development&currency_code=USD&source=url), or by buying cool gear on the [Compiler Explorer store](https://shop.spreadshirt.com/compiler-explorer/). ## Using Compiler Explorer ### FAQ There is now a FAQ section [in the repository wiki](https://github.com/compiler-explorer/compiler-explorer/wiki/FAQ). If your question is not present, please contact us as described below, so we can help you. If you find that the FAQ is lacking some important point, please free to contribute to it and/or ask us to clarify it. ### Videos There are a number of videos that showcase some features of Compiler Explorer: - [Presentation for CppCon 2019 about the project](https://www.youtube.com/watch?v=kIoZDUd5DKw) - [Older 2 part series of videos](https://www.youtube.com/watch?v=4_HL3PH4wDg) which go into a bit more detail into the more obscure features. - [Just Enough Assembly for Compiler Explorer](https://youtu.be/QLolzolunJ4): Practical introduction to Assembly with a focus on usage on Compiler Explorer, from CppCon 2021. - [Playlist: Compiler Explorer](https://www.youtube.com/playlist?list=PL2HVqYf7If8dNYVN6ayjB06FPyhHCcnhG): A collection of videos discussing Compiler Explorer; using it, installing it, what it's for, etc. A [Road map](docs/Roadmap.md) is available which gives a little insight into the future plans for **Compiler Explorer**. ## Developing **Compiler Explorer** is written in [Node.js](https://nodejs.org/). Assuming you have a compatible version of `node` installed, on Linux simply running `make` ought to get you up and running with an Explorer running on port 10240 on your local machine: [http://localhost:10240/](http://localhost:10240/). If this doesn't work for you, please contact us, as we consider it important you can quickly and easily get running. Currently, **Compiler Explorer** requires [`node` 16 _(LTS version)_](CONTRIBUTING.md#node-version) installed, either on the path or at `NODE_DIR` (an environment variable or `make` parameter). Running with `make EXTRA_ARGS='--language LANG'` will allow you to load `LANG` exclusively, where `LANG` is one for the language ids/aliases defined in `lib/languages.ts`. For example, to only run **Compiler Explorer** with C++ support, you'd run `make EXTRA_ARGS='--language c++'`. The `Makefile` will automatically install all the third party libraries needed to run; using `npm` to install server-side and client side components. For development, we suggest using `make dev` to enable some useful features, such as automatic reloading on file changes and shorter startup times. You can also use `npm run dev` to run if `make dev` doesn't work on your machine. Some languages need extra tools to demangle them, e.g. `rust`, `d`, or `haskell`. Such tools are kept separately in the [tools repo](https://github.com/compiler-explorer/compiler-explorer-tools). Configuring compiler explorer is achieved via configuration files in the `etc/config` directory. Values are `key=value`. Options in a `{type}.local.properties` file (where `{type}` is `c++` or similar) override anything in the `{type}.defaults.properties` file. There is a `.gitignore` file to ignore `*.local.*` files, so these won't be checked into git, and you won't find yourself fighting with updated versions when you `git pull`. For more information see [Adding a Compiler](docs/AddingACompiler.md). Check [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed information about how you can contribute to **Compiler Explorer**, and the [docs](./docs) folder for specific details regarding various things you might want to do, such as how to add new compilers or languages to the site. ### Running a local instance If you want to point it at your own GCC or similar binaries, either edit the `etc/config/LANG.defaults.properties` or else make a new one with the name `LANG.local.properties`, substituting `LANG` as needed. `*.local.properties` files have the highest priority when loading properties. When running in a corporate setting the URL shortening service can be replaced by an internal one if the default storage driver isn't appropriate for your environment. To do this, add a new module in `lib/shortener/myservice.js` and set the `urlShortenService` variable in configuration. This module should export a single function, see the [tinyurl module](lib/shortener/tinyurl.js) for an example. ### RESTful API There's a simple restful API that can be used to do compiles to asm and to list compilers. You can find the API documentation [here](docs/API.md). ## Contact us We run a [Compiler Explorer Discord](https://discord.gg/B5WacA7), which is a place to discuss using or developing Compiler Explorer. We also have a presence on the [cpplang](https://cppalliance.org/slack/) Slack channel `#compiler_explorer` and we have [a public mailing list](https://groups.google.com/forum/#!forum/compiler-explorer-discussion). There's a development channel on the discord, and also a [development mailing list](https://groups.google.com/forum/#!forum/compiler-explorer-development). Feel free to raise an issue on [github](https://github.com/compiler-explorer/compiler-explorer/issues) or [email Matt directly](mailto:[email protected]) for more help. ## Credits **Compiler Explorer** is maintained by the awesome people listed in the [AUTHORS](AUTHORS.md) file. We would like to thank the contributors listed in the [CONTRIBUTORS](CONTRIBUTORS.md) file, who have helped shape **Compiler Explorer**. We would also like to specially thank these people for their contributions to **Compiler Explorer**: - [Gabriel Devillers](https://github.com/voxelf) (_while working for [Kalray](http://www.kalrayinc.com/)_) - [Johan Engelen](https://github.com/JohanEngelen) - [Joshua Sheard](https://github.com/jsheard) - [Andrew Pardoe](https://github.com/AndrewPardoe) A number of [amazing sponsors](https://godbolt.org/#sponsors), both individuals and companies, have helped fund and promote Compiler Explorer.
162
Spreadsheet CollectionViewLayout in Swift. Fully customizable. ๐Ÿ”ถ
# SwiftSpreadsheet [![Version](https://img.shields.io/cocoapods/v/SwiftSpreadsheet.svg?style=flat)](http://cocoapods.org/pods/SwiftSpreadsheet) [![License](https://img.shields.io/cocoapods/l/SwiftSpreadsheet.svg?style=flat)](http://cocoapods.org/pods/SwiftSpreadsheet) [![Platform](https://img.shields.io/cocoapods/p/SwiftSpreadsheet.svg?style=flat)](http://cocoapods.org/pods/SwiftSpreadsheet) <a href="https://github.com/apple/swift-package-manager"><img alt="Swift Package Manager compatible" src="https://img.shields.io/badge/SPM-%E2%9C%93-brightgreen.svg?style=flat"/></a> ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements Swift 5.0 ## Installation SwiftSpreadsheet is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "SwiftSpreadsheet" ``` ## Demo ![Output sample](https://thumbs.gfycat.com/SilentLightheartedAmmonite-size_restricted.gif) ## Quick start A short introduction on how to get started: The rows of the spreadsheet represent a section in the collection view, with columns being the respective items. The leftmost and the rightmost elements of the spreadsheet (`leftRowHeadline` and `rightRowHeadline`), as well as the topmost and the bottommost elements (`topColumnHeader` and `bottomColumnFooter`) are represented as `UISupplementaryView`, which โ€” if needed โ€” have to be registered with the respective identifiers of the provided enum `ViewKindType` (refer to the example code). The corners of the resulting spreadsheet are represented as `UIDecorationView` which can be passed as `UINib` or as `AnyClass` upon initialization of the layout. To allow more flexibilty you have to pass the given nib or class via the `DecorationViewType` enum. Its cases hold one of the respective types as associative value: `asNib(myNib)` or `asClass(myClass)`. A short example: ```swift //Register SupplementaryViews first, then initialize the layout with optional Nibs/Classes for the DecorationViews let layout = SpreadsheetLayout(delegate: self, topLeftDecorationViewType: .asNib(topLeftDecorationViewNib), topRightDecorationViewType: .asNib(topRightDecorationViewNib), bottomLeftDecorationViewType: .asClass(bottomLeftDecorationViewClass), bottomRightDecorationViewType: .asClass(bottomRightDecorationViewClass)) //Default is true, set false here if you do not want some of these sides to remain sticky layout.stickyLeftRowHeader = true layout.stickyRightRowHeader = true layout.stickyTopColumnHeader = true layout.stickyBottomColumnFooter = true self.collectionView.collectionViewLayout = layout ``` Implement the provided `SpreadsheetLayoutDelegate`. The methods are straightforward. Simply pass `nil` wherever you do not want supplementary views to be displayed (leftmost, rightmost, topmost and bottommost). Reload Layout: ```swift //On Layout: layout.resetLayoutCache() //Helper Method for collection view collectionView.reloadDataAndSpreadsheetLayout() ``` So in short: 1) Register the respective objects of type `UISupplementaryView` you want to use with the provided identifiers of the enum `ViewKindType`. 2) Create a `UINib` object for each `UIDecrationView` (corner of the Spreadsheet) and pass it upon initialization of the layout. 3) Initialize the layout with the provided convenience initializer and pass the delegate as well as the required decoration views. 4) Implement the `SpreadsheetLayoutDelegate`. 5) Set the content of your cells and the supplementary views in the data source methods of your collection view. 6) Enjoy ;) ## Questions Please refer to the demo application or contact me directly. ## Author Wojtek Kordylewski. indiControl GmbH owns the Copyright of the respective SwiftSpreadsheet.swift file. ## License SwiftSpreadsheet is available under the MIT license. See the LICENSE file for more info.
163
Elegant HTTP Networking in Swift
![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/AlamofireLogo.png) [![Swift](https://img.shields.io/badge/Swift-5.3_5.4_5.5_5.6-orange?style=flat-square)](https://img.shields.io/badge/Swift-5.3_5.4_5.5_5.6-Orange?style=flat-square) [![Platforms](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-yellowgreen?style=flat-square)](https://img.shields.io/badge/Platforms-macOS_iOS_tvOS_watchOS_Linux_Windows-Green?style=flat-square) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg?style=flat-square)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat-square)](https://github.com/Carthage/Carthage) [![Swift Package Manager](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square)](https://img.shields.io/badge/Swift_Package_Manager-compatible-orange?style=flat-square) [![Twitter](https://img.shields.io/badge/[email protected]?style=flat-square)](https://twitter.com/AlamofireSF) [![Swift Forums](https://img.shields.io/badge/Swift_Forums-Alamofire-orange?style=flat-square)](https://forums.swift.org/c/related-projects/alamofire/37) Alamofire is an HTTP networking library written in Swift. - [Features](#features) - [Component Libraries](#component-libraries) - [Requirements](#requirements) - [Migration Guides](#migration-guides) - [Communication](#communication) - [Installation](#installation) - [Contributing](#contributing) - [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire) - [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) - [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor) - **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers) - **Advanced Concurrency -** [Swift Concurrency](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-swift-concurrency) and [Combine](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#using-alamofire-with-combine) - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) - [Open Radars](#open-radars) - [FAQ](#faq) - [Credits](#credits) - [Donations](#donations) - [License](#license) ## Features - [x] Chainable Request / Response Methods - [x] Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6. - [x] Combine Support - [x] URL / JSON Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData - [x] Download File using Request or Resume Data - [x] Authentication with `URLCredential` - [x] HTTP Response Validation - [x] Upload and Download Progress Closures with Progress - [x] cURL Command Output - [x] Dynamically Adapt and Retry Requests - [x] TLS Certificate and Public Key Pinning - [x] Network Reachability - [x] Comprehensive Unit and Integration Test Coverage - [x] [Complete Documentation](https://alamofire.github.io/Alamofire) ## Component Libraries In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system. - [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. ## Requirements | Platform | Minimum Swift Version | Installation | Status | | --- | --- | --- | --- | | iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ | 5.3 | [CocoaPods](#cocoapods), [Carthage](#carthage), [Swift Package Manager](#swift-package-manager), [Manual](#manually) | Fully Tested | | Linux | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | | Windows | Latest Only | [Swift Package Manager](#swift-package-manager) | Building But Unsupported | #### Known Issues on Linux and Windows Alamofire builds on Linux and Windows but there are missing features and many issues in the underlying `swift-corelibs-foundation` that prevent full functionality and may cause crashes. These include: - `ServerTrustManager` and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support. - Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges. - Cache control through `CachedResponseHandler` and associated APIs is unavailable, as the underlying delegate methods aren't called. - `URLSessionTaskMetrics` are never gathered. Due to these issues, Alamofire is unsupported on Linux and Windows. Please report any crashes to the [Swift bug reporter](https://bugs.swift.org). ## Migration Guides - [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md) - [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) - [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) - [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) ## Communication - If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. - If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. - If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). - If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). - If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). - If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better! ## Installation ### CocoaPods [CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby pod 'Alamofire' ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "Alamofire/Alamofire" ``` ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. ```swift dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.6.1")) ] ``` ### Manually If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. #### Embedded Framework - Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: ```bash $ git init ``` - Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git ``` - Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - Select the top `Alamofire.framework` for iOS and the bottom one for macOS. > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`. - And that's it! > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. ## Contributing Before contributing to Alamofire, please read the instructions detailed in our [contribution guide](https://github.com/Alamofire/Alamofire/blob/master/CONTRIBUTING.md). ## Open Radars The following radars have some effect on the current implementation of Alamofire. - [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case - `rdar://26870455` - Background URL Session Configurations do not work in the simulator - `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` ## Resolved Radars The following radars have been resolved over time after being filed against the Alamofire project. - [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage. - (Resolved): 9/1/17 in Xcode 9 beta 6. - [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ - (Resolved): Just add `CFNetwork` to your linked frameworks. - `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS - (Resolved): Metrics now collected on watchOS 7+. ## FAQ ### What's the origin of the name Alamofire? Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. ## Credits Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. ### Security Disclosure If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to [email protected]. Please do not post it to a public issue tracker. ## Sponsorship The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. Sponsoring the ASF will enable us to: - Pay our yearly legal fees to keep the non-profit in good status - Pay for our mail servers to help us stay on top of all questions and security issues - Potentially fund test servers to make it easier for us to test the edge cases - Potentially fund developers to work on one of our projects full-time The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated. [Sponsor Alamofire](https://github.com/sponsors/Alamofire) ## Supporters [MacStadium](https://macstadium.com) provides Alamofire with a free, hosted Mac mini. ![Powered by MacStadium](https://raw.githubusercontent.com/Alamofire/Alamofire/master/Resources/MacStadiumLogo.png) ## License Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details.
164
Call hidden/private API in style! The Swift way.
![image](https://user-images.githubusercontent.com/121827/79637117-4961c880-8185-11ea-9014-5eb7fc9dc211.png) ![Swift](https://img.shields.io/badge/Swift-5.2-orange?logo=Swift&logoColor=white) [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://swift.org/package-manager/) ![Build](https://github.com/mhdhejazi/Dynamic/workflows/Build/badge.svg) ![Tests](https://github.com/mhdhejazi/Dynamic/workflows/Tests/badge.svg) A library that uses `@dynamicMemberLookup` and `@dynamicCallable` to access Objective-C API the Swifty way. ## Table of contents * [Introduction](#introduction) * [Examples](#examples) * [Installation](#installation) * [How to use](#how-to-use) * [Requirements](#requirements) * [Contribution](#contribution) * [Author](#author) ## Introduction Assume we have the following private Objective-C class that we want to access in Swift: ```objectivec @interface Toolbar : NSObject - (NSString *)titleForItem:(NSString *)item withTag:(NSString *)tag; @end ``` There are three ways to dynamically call the method in this class: **1. Using `performSelector()`** ```swift let selector = NSSelectorFromString("titleForItem:withTag:") let unmanaged = toolbar.perform(selector, with: "foo", with: "bar") let result = unmanaged?.takeRetainedValue() as? String ``` **2. Using `methodForSelector()` with `@convention(c)`** ```swift typealias titleForItemMethod = @convention(c) (NSObject, Selector, NSString, NSString) -> NSString let selector = NSSelectorFromString("titleForItem:withTag:") let methodIMP = toolbar.method(for: selector) let method = unsafeBitCast(methodIMP, to: titleForItemMethod.self) let result = method(toolbar, selector, "foo", "bar") ``` **3. Using `NSInvocation`** <details> <summary>It's only available in Objective-C.</summary> ```objectivec SEL selector = @selector(titleForItem:withTag:); NSMethodSignature *signature = [toolbar methodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; invocation.target = toolbar; invocation.selector = selector; NSString *argument1 = @"foo"; NSString *argument2 = @"bar"; [invocation setArgument:&argument1 atIndex:2]; [invocation setArgument:&argument2 atIndex:3]; [invocation invoke]; NSString *result; [invocation getReturnValue:&result]; ``` </details> **Or, we can use Dynamic** ๐ŸŽ‰ ```swift let result = Dynamic(toolbar) // Wrap the object with Dynamic .titleForItem("foo", withTag: "bar") // Call the method directly! ``` > More details on how the library is designed and how it works [here](https://medium.com/swlh/calling-ios-and-macos-hidden-api-in-style-1a924f244ad1). ## Examples The main use cases for `Dynamic` is accessing private/hidden iOS and macOS API in Swift. And with the introduction of Mac Catalyst, the need to access hidden API arose as Apple only made a very small portion of the macOS AppKit API visible to Catalyst apps. What follows are examples of how easy it is to access AppKit API in a Mac Catalyst with the help of Dynamic. #### 1. Get the `NSWindow` from a `UIWindow` in a MacCatalyst app ```swift extension UIWindow { var nsWindow: NSObject? { var nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(self) if #available(macOS 11, *) { nsWindow = nsWindow.attachedWindow } return nsWindow.asObject } } ``` #### 2. Enter fullscreen in a MacCatalyst app ```swift // macOS App window.toggleFullScreen(nil) // Mac Catalyst (with Dynamic) window.nsWindow.toggleFullScreen(nil) ``` #### 3. Using `NSOpenPanel` in a MacCatalyst app ```swift // macOS App let panel = NSOpenPanel() panel.beginSheetModal(for: view.window!, completionHandler: { response in if let url: URL = panel.urls.first { print("url: ", url) } }) // Mac Catalyst (with Dynamic) let panel = Dynamic.NSOpenPanel() panel.beginSheetModalForWindow(self.view.window!.nsWindow, completionHandler: { response in if let url: URL = panel.URLs.firstObject { print("url: ", url) } } as ResponseBlock) typealias ResponseBlock = @convention(block) (_ response: Int) -> Void ``` #### 4. Change the window scale factor in MacCatalyst apps iOS views in Mac Catalyst apps are automatically scaled down to 77%. To change the scale factor we need to access a hidden property: ```swift override func viewDidAppear(_ animated: Bool) { view.window?.scaleFactor = 1.0 // Default value is 0.77 } extension UIWindow { var scaleFactor: CGFloat { get { Dynamic(view.window?.nsWindow).contentView .subviews.firstObject.scaleFactor ?? 1.0 } set { Dynamic(view.window?.nsWindow).contentView .subviews.firstObject.scaleFactor = newValue } } } ``` ## Installation You can use [Swift Package Manager](https://swift.org/package-manager) to install `Dynamic` by adding it in your `Package.swift` : ```swift let package = Package( dependencies: [ .package(url: "https://github.com/mhdhejazi/Dynamic.git", branch: "master") ] ) ``` ## How to use The following diagram shows how we use Dynamic to access private properties and methods from the Objective-C object `obj`: ![Diagram](https://user-images.githubusercontent.com/121827/83970645-7312b280-a8df-11ea-87bf-d69682f8627d.png) ### 1. Wrap Objective-C objects To work with Objective-C classes and instances, we need to wrap them with Dynamic first #### Wrapping an existing object If we have a reference for an existing Objective-C object, we can simply wrap it with `Dynamic`: ```swift let dynamicObject = Dynamic(objcObject) ``` #### Creating new instances To create a new instance from a hidden class, we prepend its name with `Dynamic` (or `ObjC`): ```swift // Objective-C: [[NSDateFormatter alloc] init]; // Swift: let formatter = Dynamic.NSDateFormatter() // Or maybe: let formatter = ObjC.NSDateFormatter() // Or the longer form: let formatter = ObjC.NSDateFormatter.`init`() ``` > **Note 1**: The `formatter` is an instance of `Dynamic` that wraps the new instance of `NSDateFormatter` > **Note 2**: `ObjC` is just a typealias for `Dynamic`. Whatever you choose to use, stay consistent. If the initializer takes parameters, we can pass them directly: ```swift // Objective-C: [[NSProgress alloc] initWithParent:foo userInfo:bar]; // Swift: let progress = Dynamic.NSProgress(parent: foo, userInfo: bar) // Or the longer form: let progress = Dynamic.NSProgress.initWithParent(foo, userInfo: bar) ``` > Both forms are equivalent because the library adds the prefix `initWith` to the method selector in the first case. > If you choose to use the shorter form, remember that you can only drop the prefix `initWith` from the original initializer name. Whatever comes after `initWith` should be the label of the first parameter. #### Singletons Accessing singletons is also straightforward: ```swift // Objective-C: [NSApplication sharedApplication]; // Swift: let app = Dynamic.NSApplication.sharedApplication() // Or we can drop the parenthesizes, as if `sharedApplication` was a static property: let app = Dynamic.NSApplication.sharedApplication ``` > **Important Note**: Although the syntax looks very similar to the Swift API, it's not always identical to the Swift version of the used API. For instance, the name of the above singleton in Swift is [`shared`](https://developer.apple.com/documentation/appkit/nsapplication/1428360-shared) not `sharedApplication`, but we can only use [`sharedApplicaton`](https://developer.apple.com/documentation/appkit/nsapplication/1428360-sharedapplication) here as we're internally taking with the Objective-C classes. > Always refer to the Objective-C documentation of the method you're trying to call to make sure you're using the right name. ### 2. Call the private API After wrapping the Objective-C object, we can now access its properties and methods directly from the Dynamic object. #### Accessing properties ```swift // Objective-C: @interface NSDateFormatter { @property(copy) NSString *dateFormat; } // Swift: let formatter = Dynamic.NSDateFormatter() // Getting the property value: let format = formatter.dateFormat // `format` is now a Dynamic object // Setting the property value: formatter.dateFormat = "yyyy-MM-dd" // Or the longer version: formatter.dateFormat = NSString("yyyy-MM-dd") ``` > **Note 1**: The variable `format` above is now a `Dynamic` object that wraps the actual property value. The reason for returning a `Dynamic` object and not the actual value is to allow call chaining. We'll see later how we can unwrap the actual value from a `Dynamic` object. > **Note 2**: Although the property `NSDateFormatter.dataFormat` is of the type `NSString`, we can set it to a Swift `String` and the library will convert it to `NSString` automatically. #### Calling methods ```swift let formatter = Dynamic.NSDateFormatter() let date = formatter.dateFromString("2020 Mar 30") // `date` is now a Dynamic object ``` ```swift // Objective-C: [view resizeSubviewsWithOldSize:size]; [view beginPageInRect:rect atPlacement:point]; // Swift: view.resizeSubviewsWithOldSize(size) // OR โคธ view.resizeSubviews(withOldSize: size) view.beginPageInRect(rect, atPlacement: point) // OR โคธ view.beginPage(inRect: rect, atPlacement: point) ``` > Calling the same method in different forms is possible because the library combines the method name (e.g. `resizeSubviews`) with the first parameter label (e.g. `withOldSize`) to form the method selector (e.g. `resizeSubviewsWithOldSize:`). This means you can also call: `view.re(sizeSubviewsWithOldSize: size)`, but please don't. #### Objective-C block arguments To pass a Swift closure for a block argument, we need to add `@convention(block)` to the closure type, and then cast the passed closure to this type. ```swift // Objective-C: - (void)beginSheetModalForWindow:(NSWindow *)sheetWindow completionHandler:(void (^)(NSModalResponse returnCode))handler; // Swift: let panel = Dynamic.NSOpenPanel.openPanel() panel.beginSheetModal(forWindow: window, completionHandler: { result in print("result: ", result) } as ResultBlock) typealias ResultBlock = @convention(block) (_ result: Int) -> Void ``` ### 3. Unwrap the result Methods and properties return `Dynamic` objects by default to make it possible to chain calls. When the actual value is needed it can be unwrapped in multiple ways: #### Implicit unwrapping A value can be implicitly unwrapped by simply specifying the type of the variable we're assigning the result to. ```swift let formatter = Dynamic.NSDateFormatter() let date: Date? = formatter.dateFromString("2020 Mar 30") // Implicitly unwrapped as Date? let format: String? = formatter.dateFormat // Implicitly unwrapped as String? let progress = Dynamic.NSProgress() let total: Int? = progress.totalUnitCount // Implicitly unwrapped as Int? ``` Note that we should always use a nullable type (`Optional`) for the variable type or we may see a compiler error: ```swift let total = progress.totalUnitCount // No unwrapping. `total` is a Dynamic object let total: Int? = progress.totalUnitCount // Implicit unwrapping as Int? let total: Int = progress.totalUnitCount // Compiler error let total: Int = progress.totalUnitCount! // Okay, but dangerous ``` > Assigning to a variable of an optional type isn't the only way for implicitly unwrapping a value. Other ways include returning the result of a method call or comparing it with a variable of an optional type. Note that the implicit unwrapping only works with properties and method calls since the compiler can choose the proper overloading method based on the expected type. This isn't the case when we simply return a Dynamic variable or assign it to another variable: ```swift // This is okay: let format: Date? = formatter.dateFromString("2020 Mar 30") // But this is not: let dynamicObj = formatter.dateFromString("2020 Mar 30") let format: Date? = dynamicObj // Compiler error ``` #### Explicit unwrapping We can also explicitly unwrap values by calling one of the `as<Type>` properties: ```swift Dynamic.NSDateFormatter().asObject // Returns the wrapped value as NSObject? formatter.dateFormat.asString // Returns the wrapped value as String? progress.totalUnitCount.asInt // Returns the wrapped value as Int? ``` And there are many properties for different kinds of values: ```swift var asAnyObject: AnyObject? { get } var asValue: NSValue? { get } var asObject: NSObject? { get } var asArray: NSArray? { get } var asDictionary: NSDictionary? { get } var asString: String? { get } var asFloat: Float? { get } var asDouble: Double? { get } var asBool: Bool? { get } var asInt: Int? { get } var asSelector: Selector? { get } var asCGPoint: CGPoint? { get } var asCGVector: CGVector? { get } var asCGSize: CGSize? { get } var asCGRect: CGRect? { get } var asCGAffineTransform: CGAffineTransform? { get } var asUIEdgeInsets: UIEdgeInsets? { get } var asUIOffset: UIOffset? { get } var asCATransform3D: CATransform3D? { get } ``` ### Edge cases #### Unrecognized methods and properties If you try to access undefined properties or methods the app won't crash, but you'll get `InvocationError.unrecognizedSelector` wrapped with a `Dynamic` object. You can use `Dynamic.isError` to check for such an error. ```swift let result = Dynamic.NSDateFormatter().undefinedMethod() result.isError // -> true ``` And you'll also see a warning in the console: ```nasm WARNING: Trying to access an unrecognized member: NSDateFormatter.undefinedMethod ``` > Note that a crash may expectedly happen if you pass random parameters of unexpected types to a method that doesn't expect them. #### Setting a property to `nil` You can use one the following ways to set a property to `nil`: ```swift formatter.dateFormat = .nil // The custom Dynamic.nil constant formatter.dateFormat = nil as String? // A "typed" nil formatter.dateFormat = String?.none // The Optional.none case ``` ### Logging It's always good to understand what's happening under the hood - be it to debug a problem or just out of curiosity. To enable extensive logging, simply change the `loggingEnabled` property to `true`: ```swift Dynamic.loggingEnabled = true ``` ## Requirements #### Swift: 5.0 `Dynamic` uses the `@dynamicCallable` attribute which was introduced in Swift 5. ## Contribution Please feel free to contribute pull requests, or create issues for bugs and feature requests. ## Author Mhd Hejazi <a href="https://twitter.com/intent/follow?screen_name=Hejazi"><img src="https://img.shields.io/badge/@hejazi-x?color=08a0e9&logo=twitter&logoColor=white" valign="middle" /></a>
165
iOSๆททๆท†ๅŠ ๅ›บๅทฎๅผ‚ๅŒ–็ฟปๆ–ฐๅŠ ๅฏ†ๅทฅๅ…ท๏ผŒๆจกๆ‹Ÿไบบๅทฅๆ‰‹ๅŠจๆททๆท†๏ผŒ่ฏ†ๅˆซไธŠไธ‹ๆ–‡ ๏ผŒๆ”ฏๆŒ็ปงๆ‰ฟ้“พใ€็ฑปๅž‹่ฏ†ๅˆซใ€ๆ–นๆณ•ๅคšๅ‚็ญ‰ๅคๆ‚้ซ˜็บงๆททๆท†ใ€‚source-to-source obfuscation of iOS projects๏ผŒXcode's refactor->rename. ๅ‘Šๅˆซๆ’ๅ…ฅๆฏซๆ— ๅ…ณ่”็š„ๅžƒๅœพไปฃ็ ใ€ๅผƒ็”จๆ— ่„‘ๅ•่ฏ้šๆœบๆ‹ผๆŽฅๆ›ฟๆข๏ผŒๆจกๆ‹Ÿๆญฃๅธธๅผ€ๅ‘๏ผŒไธ€ๆฌพๆœ€ๅฅฝ็š„ๆททๆท†ๆœ€ๅฝปๅบ•็š„Mac App Toolsใ€‚ๆ”ฏๆŒOC(Objcใ€Objective-C)ใ€Cใ€C++(Cocos2d-xใ€Cocos2dxๅ’ŒLuaๆธธๆˆๅผ€ๅ‘)ใ€Swiftใ€C#(Unity)ๆททๆท†๏ผŒๅฏ็”จไบŽios้ฉฌ็”ฒๅŒ…ๆธธๆˆSDKๆททๆท†๏ผŒๅ‡ๅฐ‘่ดฆๅท่ฐƒๆŸฅ่ฟ‡ๆœบๅฎกไธŠๆžถ่ฟ‡ๅŒ…่ฟ‡ๅฎก4.3ใ€2.3.1ใ€2.1
<a name="tMJSz"></a> # ![](https://cdn.nlark.com/yuque/0/2020/png/213807/1606304234500-46a10b02-f83d-4996-99fc-ce092241ea7c.png#averageHue=%23e9c2bf&from=paste&height=200&id=v0ghq&originHeight=200&originWidth=200&originalType=url&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=&width=200) <a name="beqYw"></a> ### English | [ไธญๆ–‡](/README_ZH.md) <a name="wNymF"></a> # Preface By chance, I ran into the iOS [vest bag business](https://www.yuque.com/docs/share/7e70244c-5dea-4035-b634-65cc082097da?translate=en) . I also used other tools on the market in the early stage, but the actual effect was not ideal. After a lot of practice, a full-featured [obfuscation tool has been developed](https://github.com/520coding/confuse) . The tool have been packaged into a Mac application which support multiple programming languages, such as OC, C++, Swift. More functions are still being packaged, so stay tuned. <a name="ixxhF"></a> # Prompt In order to let everyone get started quickly and compare the effects of confusion, a new test project [**confuse_test**](https://github.com/520coding/confuse/tree/master/confuse_test) was created. If you encounter problems during actual use, welcome to extend the test project. Please indicate the bug details in the project, and there will be rewards. <a name="sbrhD"></a> #### Test engineering description: > [confuse_test](https://github.com/520coding/confuse/tree/master/confuse_test): Contains oc, c++, swift and some third-party use cases to quickly verify the overall effect > [confuse_test_oc](https://github.com/520coding/confuse/tree/master/confuse_test_oc): only contains oc, which is convenient to verify the effect of each function > [confuse_test_swift](https://github.com/520coding/confuse/tree/master/confuse_test_swift): only contains swift, the code comes from[ Apple's official example code](https://docs.swift.org/swift-book/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0), which is convenient to verify the effect of each function The source code can be modified arbitrarily to verify the actual effect. It is recommended to use different tools to confuse the above test projects or third-party open source library projects to compare the effects. > Instructions for the old version before 1.2.0: ย  > Introduction: No grammar and compilation requirements are involved, but partial omissions or corrections may occur after confusion, please add to the blacklist filter by yourself. ย  > Applicable projects: RN and other mixed projects that have not yet been adapted. ย  > Conditions of use: temporarily unavailable, reopen later <a name="Yng3v"></a> # Readme <a name="6e674183b5d2f1af15baaa27bb7c93b2"></a> ### The essence of vest bag: 1. The first stage reduces the repetition rate. The initial version of my development is basically similar to other tools currently on the market, mainly the basic function of global substitution of class name, method name, and variable name. 2. The second stage reduces the similarity (normal distribution of the same elements). At present, the tool has been greatly improved after optimization and continuous reconstruction, and it basically meets the requirements in this respect. For details, see the following function introduction. There are two sides to everything. The more powerful the function, the longer it will take to confuse. If your project is large, it is possible to confuse for a few hours. Please do not take offense, and continue to optimize. <a name="fc8a03eacc987f4c5e94e6dc0086ea50"></a> ### Distinguish the pros and cons of tools In fact, to identify the pros and cons of a tool, just look at the following points: 1. Can modify all attributes, methods, and all parameter names of methods 2. Modify the name of the member (attribute, method), can it be distinguished by class, or a simple global replacement 3. Can modify the method with block parameters, a typical network request > For example๏ผš+ (BOOL)post:(NSString *)url parameters:(NSDictionary *)parameters success:(HttpRequestResponse)success error:(HttpRequestResponse)error; 3. The length of the changed name of the method name and attribute name (this tool can guarantee that 60~80% of the changed name is a common word, such as name, title, etc., and ensure that it does not conflict with the system.~~Completely abandon the simple practice of relying on a large number of word libraries to ensure the uniqueness of naming~~, The real simulation of manual development) 4. Modify the layout (Frame, Masonry, SDAutoLayout) 5. Is the code inserted or "garbage" (this tool creates custom controls, encapsulates network requests, and uses MVC pattern association between files to completely bid farewell to "garbage" and mix the spurious with the genuine). 6. Not to mention "Who else..." can identify macros, distinguish contextual content such as inheritance chains, and intelligently identify unmodifiable parts > For example: + (void)init ;-(void)reloadData; basically can be changed, who else can do it? " 7. Normal projects (or third-party libraries) basically do not report errors after obfuscation (except for some individual [improper grammars](https://www.yuque.com/docs/share/4a87ec96-80fe-4d25-873d-93cb428b3e15#iz0Zi) that cause confusion and report errors) <a name="426215c094f184f34acdb12593ddb1fc"></a> # Features confuse is a [confusion tool](https://github.com/520coding/confuse) that simulates manual development as much as possible, imitates some functions of Xcode, and avoids machine core 4.3, 2.1, 2.3.1, account surveys, etc.<br />Goal: **Simulate manually modify everything that can be changed** , which is why this tool only has a blacklist and no whitelist<br />The detailed functions are as follows (the basic functions are not described, see other tools for details): <a name="82f2e3582d1466241460f1564b36b2a6"></a> ## Completed The following functions are supported: 1. Blacklist (secondary) filtering, freely control the obfuscated content of each function, and adapt to almost all projects. 2. Confusion percentage control, you can freely adjust according to the actual needs of your own project 3. Smart noun substitution: 1. When renaming, use the combination of related type existing information + similar semantics + type + some old vocabulary, and filter sensitive words. At the same time, users can also customize sensitive words.~~Deprecate'random word brainless combination'~~ 2. Different types of members with the same name -> different types of members with different names, and different types of different name members -> different types of members with the same name, simulating normal development. Members refer to methods, attributes, and functions 4. Intelligent identification of unmodifiable parts: Identifying systems, third parties, and Pod methods through types and inheritance chains is not a'simple' equality judgment, for example: 1. Class method: + (void)init; in principle, it can be changed anywhere 2. Object method:-(void)reloadData; can be changed if it is not a subclass of UITableView 3. Property: @property (readonly) NSUInteger length; it can be changed if it is not a subclass of NSString <a name="7e02145ffab0f7184b0a6b92e79d9acd"></a> ### General part 1. [Project Configuration], as long as you select the project path, other default configurations will be automatically completed 1. Global setting "Ignore path", support regular, better use with blacklist 2. ' xcodeproj' setting, for multiple xcodeproj projects and xx.xcodeproj is not in the project root directory 3. 'Scheme' is confused and consistent with Xcode 4. 'Debug mode', It is convenient to view the comparison before and after the modification in the source file, and insert some special annotations to facilitate the location of the bug. 5. 'Hybrid mode', this mode is used to process the swift call oc part of the mixed project, to ensure that the call relationship is maintained after confusion 6. 'Reference project root path' setting, read the word and UUID of the reference project 7. 'Sensitive words' filtering 8. ' **Version iteration confusion** ', iteratively update after review, continue to use the last time (you can also choose the version arbitrarily) to obfuscate the record incremental confusion, maintain version continuity, and simulate normal development. Advantages: Development and obfuscation are synchronized and independent . The main functions currently support update confusion 2. [Antivirus], [Xcode poisoning, XCSSET Malware](https://juejin.cn/post/6936535178118430733) 1. 'UUID suffix', the virus will randomly insert UUID with a fixed suffix, regular scanning 2. 'Script path feature', a suspicious script will be executed before virus compilation, support regular scanning 3. 'Run script code flag', a suspicious script code will be executed before virus compilation, support regular scanning 3. [Resource replacement], specify the resource folder that needs to be replaced before obfuscation , and automatically replace the file with the same name, which is convenient and quick 4. [Remove comment], identify single-line, multi-line comments 5. [Edit picture], quality modification, size shift, local pixel fine-tuning๏ผŒRGBA offset๏ผŒmode modification (support hot update) 6. [Modify Lottie], simulate the real Lottie file structure, modify and expand the source file, basically does not affect the actual effect 7. [Modify file attributes], such as creation time, access time, modification time 8. [Modify item], no need to delete Cocoapods 1. Can be set to'modify uuid', completely refurbished 2. Customize the name of the'modify target', and the associated information will be updated synchronously 9. Automatic source code backup <a name="279a46203c9fe475b30ffab43dad6dba"></a> ### Objective-C 1. [Rename picture], intelligent noun replacement , automatically correct the situation that the picture name and the xcassets folder name do not correspond 1. You can set the 'Run splicing name', which is used for the image name generated by splicing strings at runtime 2. You can set the 'rename associated string' to modify the situation where the string is equal to the picture name 3. You can set the 'specified ignore length', the length of the picture name is less than the specified length is a dangerous name, it will be ignored 4. You can set 'ignore danger', which has the same name as the dictionary key, and it will be ignored 5. You can set 'associated files', other files containing picture names 2. [Insert picture], automatically insert pictures, and simulate manual calls according to context and type, and the number of inserts can be specified 3. [Rename property], support all types of @property , advantages: 1. Identify grammar, identify type, inheritance relationship, **attribute name confusion and class name (including inheritance chain) association** , automatically identify system attributes 2. You can set the 'Model suffix' to filter by the suffix of the class name, which is convenient for filtering Model 3. You can set 'Model Mapping' to automatically insert the mapping relationship (customized, and automatically complete other attributes) to ensure that the background data is matched 4. [Insert property], creation, assignment, and modification are all associated with existing types, smart noun replacement 1. 'Percentage control' 2. You can set the 'Model suffix' to filter by the suffix of the class name, the purpose: to avoid Model archiving or data transfer model failure 3. Can be executed multiple times, the index x2 increases 5. [Rename method], similar to Xcode's Rename function , advantages: 1. Syntax-related, identification of types, inheritance relationships, support for **multi-parameter modification, confusion of method names, class names (including inheritance chains) and type associations** , automatic identification of system methods 6. [Insert method], insert and call context-related methods, bid farewell to "garbage code", advantages: 1. According to the return value type of the method, create the corresponding method in the category. At the same time , the return value of the original method is encapsulated and use (local variables, attributes, formal parameters) called. 2. Can be executed multiple times, the index x2 increases 7. [Modification method], simulating manual package call, advantages: 1. **Split the call** to the original method **and adjust** it **locally according to the parameter type (support inheritance)** . For details, see the [summary table of supported parameter types.](https://www.yuque.com/docs/share/315b72d9-28f9-4fa6-bf20-c40d94f2253a?translate=en) 2. Can be executed multiple times, the index x2 increases 8. [Rename global variables], smart noun substitution 9. [Modify global variables], replace global variable names, **convert global variables into global functions** , and confuse string variable values 10. [Insert local variable], single-line compound call becomes simple multi-line call, change the execution order 11. [Modify local variable], simulate manual encapsulation call, variable name association type, advantages: 1. Local variable values remain unchanged during operation, see the [summary table of supported types for](https://www.yuque.com/docs/share/90444065-4f4e-49c8-9e1a-5bd3d3b4f84d?translate=en) details 2. Can be executed multiple times, the index x2 increases 12. [Rename multilingual], using a system of direct or indirect methods **NSLocalizedString** , **NSLocalizedStringFromTable** multilingual modified๏ผŒ[The custom packaging methods require manual processing](https://520coding.yuque.com/docs/share/de45751a-c629-4737-84ad-251fb2502123?translate=en) 13. [Modify string], support arbitrary string, encryption processing (hard code -> memory), the original string is kept in the comment for easy inspection 1. Set the'minimum length' filter 2. You can also set the " effective number" to use together 14. [Modify xib, storyboard], automatically insert the view, and modify the internal structure properties 15. [Modify font] , randomly fine-tune the font used in the project, and identify macros 16. [Modify color], randomly shift the color of the UI controls in the project, and identify the macro 17. [UI layout offset], support Frame, Masonry, SDAutoLayout common layout fine-tuning 18. [Insert file], generate other files (Combined with network, storage, and MVC to ensure that the code has high relevance and practical significance), automatic high-related calls in the project ; **Note:** (Under the project root path, a folder of " **other_xxx_file** " will be generated , and the sub-option **Target** controls Import method, if it is empty, you need to manually import, just drag the generated folder into the project; otherwise, automatically import) 19. [Insert text], Generate json, txt, plist and other common text files, automatic high-related calls in the project ; **note:** (under the project root path, a folder of " **other_xxx_text** " will be generated , and the generated files will be **automatically imported** ) 20. [Rename class], the class name is not limited (for example: my, My), you can specify to add a prefix, support class|struct|protocol๏ผŒadvantages: 1. Smart noun substitution 2. Can be set to'rename files with the same name' 3. You can set'rename similar strings', (ignore | equal | include) three modes 4. Added 'correct non-standard dot grammar', calling for non-standard dot grammar (methods are called as attributes) <a name="015937695b202fc108bd5bc9b3283082"></a> ### C++ 1. [Rename attribute], support all type attributes, recognize syntax, recognize type, inherit 2. [Insert attributes], insert attributes (member variables) and call each other to modify, automatic initialization, destruction, and assignment modification in other methods and other similar manual operations, support'percentage control' 3. [Rename method], similar to Xcode's Rename function, identifying types, templates, overloading, rewriting, inheritance, etc. 4. [Modification method], use overloading technology to modify the function prototype and call the modified parameter 5. [Modify string], support arbitrary string, encryption processing (hard code -> memory), the original string is kept in the comment for easy inspection 1. Set the'minimum length' filter 2. You can also set the " effective number" to use together 6. [Rename class], support template and other types 1. Can switch the old mode 2. Prefix setting 3. Can be set to'rename files with the same name' <a name="ea78561d0c1d5c21d3e2c93d960472e5"></a> ### Cocos2d-x This part of the function is integrated into C++ and supports cocos2dx automatic filtering <a name="47038e8338f9e18ef9eaba0ea5effb80"></a> ### Swift Adapt to Swift5.3, the SPM package management project has not yet been tested 1. [Rename global method] to automatically identify system methods 1. Can set 'parameter label', support hidden parameter label and trailing closure usage 2. [Rename picture], smart noun replacement, and automatically correct the situation where the picture name and the xcassets folder name do not correspond to each other 1. You can set the 'Run splicing name', which is used for the image name generated by splicing strings at runtime 2. You can set the 'specified ignore length', the length of the picture name is less than the specified length is a dangerous name, it will be ignored 3. You can set 'ignore danger', which has the same name as the dictionary key, and it will be ignored 4. You can set 'associated files', other files containing picture names 3. [Rename lottie] to adapt to various scenarios 1. You can set the 'run splicing name', which is used for the lottie name generated by string splicing at runtime 2. You can set the 'specified Ignore Length', if the length of the lottie name is less than the specified length, it is a dangerous name and will be ignored 3. You can set 'ignore danger', which has the same name as the dictionary key, and it will be ignored 4. [Insert picture], which automatically inserts pictures, and simulates manual calls according to the context and type, and the number of insertions can be specified 5. [rename enum], identify associated and primitive values 1. 'Original value' can be set to refine the control range 6. [Rename attribute], basic function, without too much description, advantages: 1. Similar to OC [Rename attribute], identify inheritance chain and nested type, support storage and calculation of attributes, observers, wrappers, class attributes 2. You can set the 'Model suffix' to filter by the suffix of the class name, which is convenient for filtering Model 3. You can set the 'Model mapping', automatically insert the mapping relationship, and match the background data 7. [Insert property], use calculated properties to wrap and call and replace the original properties 1. Support storage and calculation of attributes, observers, wrappers, class attributes 2. You can set the 'Model suffix' to filter by the suffix of the class name, the purpose: to avoid Model archiving or data transfer model failure 8. [Rename method], the basic functions are renamed similar to other tools, without too much description, advantages: 1. Can set 'parameter label', support hidden parameter label and trailing closure usage 2. Identification of inheritance chain nested types, support for (class, struct, enum) static methods and instance methods, and optional chains, etc. 9. [Insert method], encapsulate the return value of the original method and use the context to call additional associated methods, saying goodbye to "garbage code" 10. [Modification method], use overloading technology to modify the function prototype and call the modified parameter 11. [Rename global variables], smart noun substitution 12. [Modify font] , randomly fine-tune the font used in the project, and identify macros 13. [Modify color], randomly shift the color of UI controls in the project 14. [UI layout offset], support Frame, SnapKit, common layout fine-tuning 15. [Insert local variable], split single-line compound calls, change the execution order 16. [Modify local variable], simulate manual encapsulation call, variable name association type (support nesting), advantages: 1. The value of the local variable remains unchanged during operation. For details, see the summary table of supported types. 2. Can be executed multiple times, the index x2 increases 17. [Modify string], recognize single-line, multi-line, string interpolation, and extended string. After the modification, it can be freely combined by a variety of methods such as encryption and split character groups, and the comments of the original characters are reserved for easy inspection 1. Set the'minimum length' filter 2. You can also set the "effective number" to use together 18. [Modify xib, storyboard], automatically insert the view, and modify the internal structure properties 19. [Insert file], close to actual development (combined with network, storage, MVC, xib, etc., to ensure that the code has high relevance and practical significance), and strengthen contextual relevance. Can set 'file name prefix', set 'Target import' in the same way as OC 20. [Insert text], generate common text files such as json, txt, plist, etc., and automatically high-related calls in the project (introduction of attributes, initialization, automatic destruction, etc.). Note: (under the project root path, the folder "other_xxx_text" will be generated, and the generated files will be automatically imported) 21. [Rename class], the class name is not limited (for example: my, My), identify nested types and typealias, support class|struct|enum|protocol 1. Can be set to'rename files with the same name' 2. 'Prefix' can be set > Note: At present, the Swift and OC mixed project, the OC calling Swift part will not be processed for the time being, and will be optimized in the future. <a name="6554a51551d5572e2cd7d848844e9660"></a> ## Planning Update iterations will be carried out in the following order 1. Objective-C (95%), mainly to improve the versatility and stability of the tool, and strengthen the function 1. Audio and video files are used less and will be added later 2. Swift (95%), under development... 1. Enhanced performance 3. C++ (60%), under development... 1. Method: Insert 2. Property: modify 3. Global variables: modify 4. Lua (0%) is too specific, and it is temporarily closed. If users have this demand, we will refactor this part 5. C# (0%), I donโ€™t use much in actual projects, so I ranked last, depending on user needs before deciding 6. Other functions: 1. Fast obfuscation mode <a name="af444a353c9380bc9aa8aec067937316"></a> # Graphic introduction Run the APP rendering, please read the [tool usage tutorial](https://www.yuque.com/docs/share/cd0968ac-9c7e-415f-9e7c-1460b85e80e8) in detail before use<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/213807/1623167266244-4978d5ed-0b2c-42b5-80c4-1b44e4ff7f96.png#averageHue=%233a9b1d&clientId=u4ef53c93-4376-4&errorMessage=unknown%20error&from=paste&height=877&id=ufbdd65fd&name=image.png&originHeight=1754&originWidth=2532&originalType=binary&ratio=2&rotation=0&showTitle=false&size=443560&status=error&style=none&taskId=ue83d9a90-392f-4558-9b46-f06320d2c45&title=&width=1266) <a name="c318fa67bf88d5d842cee03115743b4b"></a> # Update log <a name="ckOtE"></a> ### v6.6.4 (2023.02.01) 1. Optimize OC [modify all variables], allow the blacklist to be set to the name of the global variable before renaming 2. Optimize OC [modify local variables], the runtime problem of assigning NSArray to NSMutableArray 3. Optimize OC [modify string], if the string is a class name, change it to cancel the modification 4. Optimize the environment check and add hints for [@class ](/class ) and [@protocol ](/protocol ) [View more historical update records](https://www.yuque.com/docs/share/39f2f60e-b6a8-443b-b005-b9364fb79b95?translate=en) <a name="41b9f638a3e62c9449ec872644258c8d"></a> # Thanks for the feedback [shizu2014](https://github.com/shizu2014)ใ€[myhonior](https://github.com/myhonior)ใ€[imbahong](https://github.com/imbahong)ใ€[tabier008](https://github.com/tabier008) <a name="0ae29cb26e944f357b114cccc4c1211b"></a> # Link navigation 1. [Tool usage tutorial](https://www.yuque.com/docs/share/cd0968ac-9c7e-415f-9e7c-1460b85e80e8) 2. [Software Questions and Answers (Q&A)](https://www.yuque.com/docs/share/4a87ec96-80fe-4d25-873d-93cb428b3e15?translate=en) 3. [OC[Modification method] Parameter type summary table](https://www.yuque.com/docs/share/315b72d9-28f9-4fa6-bf20-c40d94f2253a?translate=en) 4. [OC[Modify local variables] Modify local variables-summary table of supported types](https://www.yuque.com/docs/share/90444065-4f4e-49c8-9e1a-5bd3d3b4f84d?translate=en) 5. [OC[Rename multilingual] processing custom packaging method](https://520coding.yuque.com/docs/share/de45751a-c629-4737-84ad-251fb2502123?translate=en) 6. [Swift[Modification method] Parameter type summary table](https://520coding.yuque.com/docs/share/cd70e83b-4ab4-40e5-b719-70f214e869c8)
166
QuickCheck for Swift
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Build Status](https://travis-ci.org/typelift/SwiftCheck.svg?branch=master)](https://travis-ci.org/typelift/SwiftCheck) [![Gitter chat](https://badges.gitter.im/DPVN/chat.png)](https://gitter.im/typelift/general?utm_source=share-link&utm_medium=link&utm_campaign=share-link) SwiftCheck ========== QuickCheck for Swift. For those already familiar with the Haskell library, check out the source. For everybody else, see the [Tutorial Playground](Tutorial.playground) for a beginner-level introduction to the major concepts and use-cases of this library. Introduction ============ SwiftCheck is a testing library that automatically generates random data for testing of program properties. A property is a particular facet of an algorithm or data structure that must be invariant under a given set of input data, basically an `XCTAssert` on steroids. Where before all we could do was define methods prefixed by `test` and assert, SwiftCheck allows program properties and tests to be treated like *data*. To define a program property the `forAll` quantifier is used with a type signature like `(A, B, C, ... Z) -> Testable where A : Arbitrary, B : Arbitrary ... Z : Arbitrary`. SwiftCheck implements the `Arbitrary` protocol for most Swift Standard Library types and implements the `Testable` protocol for `Bool` and several other related types. For example, if we wanted to test the property that every Integer is equal to itself, we would express it as such: ```swift func testAll() { // 'property' notation allows us to name our tests. This becomes important // when they fail and SwiftCheck reports it in the console. property("Integer Equality is Reflexive") <- forAll { (i : Int) in return i == i } } ``` For a less contrived example, here is a program property that tests whether Array identity holds under double reversal: ```swift property("The reverse of the reverse of an array is that array") <- forAll { (xs : [Int]) in // This property is using a number of SwiftCheck's more interesting // features. `^&&^` is the conjunction operator for properties that turns // both properties into a larger property that only holds when both sub-properties // hold. `<?>` is the labelling operator allowing us to name each sub-part // in output generated by SwiftCheck. For example, this property reports: // // *** Passed 100 tests // (100% , Right identity, Left identity) return (xs.reversed().reversed() == xs) <?> "Left identity" ^&&^ (xs == xs.reversed().reversed()) <?> "Right identity" } ``` Because SwiftCheck doesn't require tests to return `Bool`, just `Testable`, we can produce tests for complex properties with ease: ```swift property("Shrunken lists of integers always contain [] or [0]") <- forAll { (l : [Int]) in // Here we use the Implication Operator `==>` to define a precondition for // this test. If the precondition fails the test is discarded. If it holds // the test proceeds. return (!l.isEmpty && l != [0]) ==> { let ls = self.shrinkArbitrary(l) return (ls.filter({ $0 == [] || $0 == [0] }).count >= 1) } } ``` Properties can even depend on other properties: ```swift property("Gen.one(of:) multiple generators picks only given generators") <- forAll { (n1 : Int, n2 : Int) in let g1 = Gen.pure(n1) let g2 = Gen.pure(n2) // Here we give `forAll` an explicit generator. Before SwiftCheck was using // the types of variables involved in the property to create an implicit // Generator behind the scenes. return forAll(Gen.one(of: [g1, g2])) { $0 == n1 || $0 == n2 } } ``` All you have to figure out is what to test. SwiftCheck will handle the rest. Shrinking ========= What makes QuickCheck unique is the notion of *shrinking* test cases. When fuzz testing with arbitrary data, rather than simply halt on a failing test, SwiftCheck will begin whittling the data that causes the test to fail down to a minimal counterexample. For example, the following function uses the Sieve of Eratosthenes to generate a list of primes less than some n: ```swift /// The Sieve of Eratosthenes: /// /// To find all the prime numbers less than or equal to a given integer n: /// - let l = [2...n] /// - let p = 2 /// - for i in [(2 * p) through n by p] { /// mark l[i] /// } /// - Remaining indices of unmarked numbers are primes func sieve(_ n : Int) -> [Int] { if n <= 1 { return [] } var marked : [Bool] = (0...n).map { _ in false } marked[0] = true marked[1] = true for p in 2..<n { for i in stride(from: 2 * p, to: n, by: p) { marked[i] = true } } var primes : [Int] = [] for (t, i) in zip(marked, 0...n) { if !t { primes.append(i) } } return primes } /// Short and sweet check if a number is prime by enumerating from 2...โŒˆโˆš(x)โŒ‰ and checking /// for a nonzero modulus. func isPrime(n : Int) -> Bool { if n == 0 || n == 1 { return false } else if n == 2 { return true } let max = Int(ceil(sqrt(Double(n)))) for i in 2...max { if n % i == 0 { return false } } return true } ``` We would like to test whether our sieve works properly, so we run it through SwiftCheck with the following property: ```swift import SwiftCheck property("All Prime") <- forAll { (n : Int) in return sieve(n).filter(isPrime) == sieve(n) } ``` Which produces the following in our testing log: ``` Test Case '-[SwiftCheckTests.PrimeSpec testAll]' started. *** Failed! Falsifiable (after 10 tests): 4 ``` Indicating that our sieve has failed on the input number 4. A quick look back at the comments describing the sieve reveals the mistake immediately: ```diff - for i in stride(from: 2 * p, to: n, by: p) { + for i in stride(from: 2 * p, through: n, by: p) { ``` Running SwiftCheck again reports a successful sieve of all 100 random cases: ``` *** Passed 100 tests ``` Custom Types ============ SwiftCheck implements random generation for most of the types in the Swift Standard Library. Any custom types that wish to take part in testing must conform to the included `Arbitrary` protocol. For the majority of types, this means providing a custom means of generating random data and shrinking down to an empty array. For example: ```swift import SwiftCheck public struct ArbitraryFoo { let x : Int let y : Int public var description : String { return "Arbitrary Foo!" } } extension ArbitraryFoo : Arbitrary { public static var arbitrary : Gen<ArbitraryFoo> { return Gen<(Int, Int)>.zip(Int.arbitrary, Int.arbitrary).map(ArbitraryFoo.init) } } class SimpleSpec : XCTestCase { func testAll() { property("ArbitraryFoo Properties are Reflexive") <- forAll { (i : ArbitraryFoo) in return i.x == i.x && i.y == i.y } } } ``` There's also a `Gen.compose` method which allows you to procedurally compose values from multiple generators to construct instances of a type: ``` swift public static var arbitrary : Gen<MyClass> { return Gen<MyClass>.compose { c in return MyClass( // Use the nullary method to get an `arbitrary` value. a: c.generate(), // or pass a custom generator b: c.generate(Bool.suchThat { $0 == false }), // .. and so on, for as many values and types as you need. c: c.generate(), ... ) } } ``` `Gen.compose` can also be used with types that can only be customized with setters: ``` swift public struct ArbitraryMutableFoo : Arbitrary { var a: Int8 var b: Int16 public init() { a = 0 b = 0 } public static var arbitrary: Gen<ArbitraryMutableFoo> { return Gen.compose { c in var foo = ArbitraryMutableFoo() foo.a = c.generate() foo.b = c.generate() return foo } } } ``` For everything else, SwiftCheck defines a number of combinators to make working with custom generators as simple as possible: ```swift let onlyEven = Int.arbitrary.suchThat { $0 % 2 == 0 } let vowels = Gen.fromElements(of: [ "A", "E", "I", "O", "U" ]) let randomHexValue = Gen<UInt>.choose((0, 15)) let uppers = Gen<Character>.fromElements(in: "A"..."Z") let lowers = Gen<Character>.fromElements(in: "a"..."z") let numbers = Gen<Character>.fromElements(in: "0"..."9") /// This generator will generate `.none` 1/4 of the time and an arbitrary /// `.some` 3/4 of the time let weightedOptionals = Gen<Int?>.frequency([ (1, Gen<Int?>.pure(nil)), (3, Int.arbitrary.map(Optional.some)) ]) ``` For instances of many complex or "real world" generators, see [`ComplexSpec.swift`](Tests/SwiftCheckTests/ComplexSpec.swift). System Requirements =================== SwiftCheck supports OS X 10.9+ and iOS 7.0+. Setup ===== SwiftCheck can be included one of two ways: **Using The Swift Package Manager** - Add SwiftCheck to your `Package.swift` file's dependencies section: ```swift .package(url: "https://github.com/typelift/SwiftCheck.git", from: "0.8.1") ``` **Using Carthage** - Add SwiftCheck to your Cartfile - Run `carthage update` - Drag the relevant copy of SwiftCheck into your project. - Expand the Link Binary With Libraries phase - Click the + and add SwiftCheck - Click the + at the top left corner to add a Copy Files build phase - Set the directory to `Frameworks` - Click the + and add SwiftCheck **Using CocoaPods** - Add [our Pod](https://cocoapods.org/pods/SwiftCheck) to your podfile. - Run `$ pod install` in your project directory. **Framework** - Drag SwiftCheck.xcodeproj into your project tree as a subproject - Under your project's Build Phases, expand Target Dependencies - Click the + and add SwiftCheck - Expand the Link Binary With Libraries phase - Click the + and add SwiftCheck - Click the + at the top left corner to add a Copy Files build phase - Set the directory to Frameworks - Click the + and add SwiftCheck License ======= SwiftCheck is released under the MIT license.
167
Folding Tab Bar and Tab Bar Controller
# FoldingTabBar.iOS [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/FoldingTabBar.svg)](https://img.shields.io/cocoapods/v/FoldingTabBar.svg) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) Folding Tab Bar and Tab Bar Controller Inspired by [this project on Dribbble](https://dribbble.com/shots/2003376-Tab-Bar-Animation) Also, read how it was done in our [blog](https://yalantis.com/blog/how_we_created_tab_bar_animation_for_ios/?utm_source=github) ![Preview](https://d13yacurqjgara.cloudfront.net/users/495792/screenshots/2003376/tab_bar_animation_fin-02.gif) ## Requirements iOS 7.0 ## Installation #### [CocoaPods](http://cocoapods.org) ```ruby pod 'FoldingTabBar', '~> 1.2.1' ``` #### [Carthage](https://github.com/Carthage/Carthage) ``` github "Yalantis/FoldingTabBar.iOS" ~> 1.2.1 ``` #### Manual Installation Alternatively you can directly add all the source files from FoldingTabBar folder to your project. 1. Download the [latest code version](https://github.com/Yalantis/FoldingTabBar.iOS/archive/master.zip) or add the repository as a git submodule to your git-tracked project. 2. Open your project in Xcode, then drag and drop all the folder directories in FoldingTabBar folder onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project. ## Introduction #### YALFoldingTabBarController `YALFoldingTabBarController` is a subclass of `UITabBarController` with custom animating `YALFoldingTabBar`. #### YALFoldingTabBar YALFoldingTabBar is a subclass of a standard UIView. We wanted to make this component expand and contract in response to a user tapping. When the component is closed you can only see a central button (โ€œ+โ€). When tapping on it, our custom Tab Bar expands letting other tabBarItems appear, so that the user can switch the controllers. Each separate tabBarItem can have two additional buttons on the left and right. These buttons can be used to let a user interact with a selected screen on the YALFoldingTabBarController without even having to leave it. #### YALTabBarItem `YALTabBarItem` is a model to configure your tab bar items with images. ## Usage Option 1: The simplest way is to use `YALFoldingTabBarController` as it is. You can also subclass it if you indend to change the default behaviour. Option 2: You can write your own implementation of `UITabBarController `and use `YALFoldingTabBar` or its subclass. Here is an instruction of how to use `YALFoldingTabBarController` in the Storyboard. 1. Add native `UITabBarController` to the storyboard, establish relationships with its view controllers. 2. Choose `YALFoldingTabBarController` as custom class for `UITabBarController`. 3. Choose `YALCustomHeightTabBar` as custom class for `UITabBar` inside `YALFoldingTabBarController` 3. In AppDelegate method take out an instance of `YALFoldingTabBarController` from the window.rootViewController and supply it with images for the left and right tabBarItems respectively. Also you can add your own image for the center button of `YALFoldingTabBar`. ## Objective-C ```objective-c YALFoldingTabBarController *tabBarController = (YALFoldingTabBarController *) self.window.rootViewController; //prepare leftBarItems YALTabBarItem *item1 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"nearby_icon"] leftItemImage:nil rightItemImage:nil]; YALTabBarItem *item2 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"profile_icon"] leftItemImage:[UIImage imageNamed:@"edit_icon"] rightItemImage:nil]; tabBarController.leftBarItems = @[item1, item2]; //prepare rightBarItems YALTabBarItem *item3 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"chats_icon"] leftItemImage:[UIImage imageNamed:@"search_icon"] rightItemImage:[UIImage imageNamed:@"new_chat_icon"]]; YALTabBarItem *item4 = [[YALTabBarItem alloc] initWithItemImage:[UIImage imageNamed:@"settings_icon"] leftItemImage:nil rightItemImage:nil]; tabBarController.rightBarItems = @[item3, item4]; ``` ## Swift ```swift if let tabBarController = window?.rootViewController as? YALFoldingTabBarController { //leftBarItems let firstItem = YALTabBarItem( itemImage: UIImage(named: "nearby_icon")!, leftItemImage: nil, rightItemImage: nil ) let secondItem = YALTabBarItem( itemImage: UIImage(named: "profile_icon")!, leftItemImage: UIImage(named: "edit_icon")!, rightItemImage: nil ) tabBarController.leftBarItems = [firstItem, secondItem] //rightBarItems let thirdItem = YALTabBarItem( itemImage: UIImage(named: "chats_icon")!, leftItemImage: UIImage(named: "search_icon")!, rightItemImage: UIImage(named: "new_chat_icon")! ) let forthItem = YALTabBarItem( itemImage: UIImage(named: "settings_icon")!, leftItemImage: nil, rightItemImage: nil ) tabBarController.rightBarItems = [thirdItem, forthItem] } ``` If you want to handle touches on extra tabBarItems import `YALTabBarDelegate` protocol to the subclass of the proper `UIVIewController` and implement these methods: ##Objective-C ```objective-c - (void)tabBarDidSelectExtraLeftItem:(YALFoldingTabBar *)tabBar; - (void)tabBarDidSelectExtraRightItem:(YALFoldingTabBar *)tabBar; ``` ## Swift ```swift func tabBarDidSelectExtraLeftItem(tabBar: YALFoldingTabBar!) func tabBarDidSelectExtraRightItem(tabBar: YALFoldingTabBar!) ``` If you want to handle touches on tabBarItems by indexes import `YALTabBarDelegate` protocol to the subclass of the proper `UIVIewController` and implement these methods: ## Objective-C ```objective-c - (void)tabBar:(YALFoldingTabBar *)tabBar didSelectItemAtIndex:(NSUInteger)index; - (BOOL)tabBar:(YALFoldingTabBar *)tabBar shouldSelectItemAtIndex:(NSUInteger)index; ``` ## Swift ```swift func tabBar(tabBar: YALFoldingTabBar!, didSelectItemAtIndex index: UInt) func tabBar(tabBar: YALFoldingTabBar!, shouldSelectItemAtIndex index: UInt) -> Bool ``` If you want to observe contracting and expanding animation states in `YALFoldingTabBar` the following methods of `YALTabBarDelegate` protocol can be implemented: ## Objective-C ```objective-c - (void)tabBarWillCollapse:(YALFoldingTabBar *)tabBar; - (void)tabBarWillExpand:(YALFoldingTabBar *)tabBar; - (void)tabBarDidCollapse:(YALFoldingTabBar *)tabBar; - (void)tabBarDidExpand:(YALFoldingTabBar *)tabBar; ``` ## Swift ```swift func tabBarWillCollapse(tabBar: YALFoldingTabBar!) func tabBarWillExpand(tabBar: YALFoldingTabBar!) func tabBarDidCollapse(tabBar: YALFoldingTabBar!) func tabBarDidExpand(tabBar: YALFoldingTabBar!) ``` ## Important notes Because we changed the height of the default `UITabBar` you should adjust your content to the bottom of viewcontroller's superview, and ignore Bottom Layout Guide. You should also uncheck 'Under bottom bars' !['](http://i.stack.imgur.com/Owlcz.png) You can see how we did it on the example project. ## Tips for customization You can make the following configurations for custom tabBar: 1) Specify height ## Objective-C ```objective-c tabBarController.tabBarViewHeight = YALTabBarViewDefaultHeight; ``` ## Swift ```swift tabBarController.tabBarViewHeight = YALTabBarViewDefaultHeight ``` 2) Specify insets and offsets ## Objective-C ```objective-c tabBarController.tabBarView.tabBarViewEdgeInsets = YALTabBarViewHDefaultEdgeInsets; tabBarController.tabBarView.tabBarItemsEdgeInsets = YALTabBarViewItemsDefaultEdgeInsets; tabBarController.tabBarView.offsetForExtraTabBarItems = YALForExtraTabBarItemsDefaultOffset; ``` ## Swift ```swift tabBarController.tabBarView.tabBarViewEdgeInsets = YALTabBarViewHDefaultEdgeInsets tabBarController.tabBarView.tabBarItemsEdgeInsets = YALTabBarViewItemsDefaultEdgeInsets tabBarController.tabBarView.offsetForExtraTabBarItems = YALForExtraTabBarItemsDefaultOffset ``` 3) Specify colors ## Objective-C ```objective-c tabBarController.tabBarView.backgroundColor = [UIColor colorWithRed:94.0/255.0 green:91.0/255.0 blue:149.0/255.0 alpha:1]; tabBarController.tabBarView.tabBarColor = [UIColor colorWithRed:72.0/255.0 green:211.0/255.0 blue:178.0/255.0 alpha:1]; tabBarController.tabBarView.dotColor = [UIColor colorWithRed:94.0/255.0 green:91.0/255.0 blue:149.0/255.0 alpha:1]; ``` ## Swift ```swift tabBarController.tabBarView.backgroundColor = UIColor( red: 94.0/255.0, green: 91.0/255.0, blue: 149.0/255.0, alpha: 1 ) tabBarController.tabBarView.tabBarColor = UIColor( red: 72.0/255.0, green: 211.0/255.0, blue: 178.0/255.0, alpha: 1 ) tabBarController.tabBarView.dotColor = UIColor( red: 94.0/255.0, green: 91.0/255.0, blue: 149.0/255.0, alpha: 1 ) ``` 4) Specify height for additional left and right buttons ## Objective-C ```objective-c tabBarController.tabBarView.extraTabBarItemHeight = YALExtraTabBarItemsDefaultHeight; ``` ## Swift ```swift tabBarController.tabBarView.extraTabBarItemHeight = YALExtraTabBarItemsDefaultHeight ``` ## Let us know! Weโ€™d be really happy if you sent us links to your projects where you use our component. Just send an email to [email protected] And do let us know if you have any questions or suggestion regarding the animation. P.S. Weโ€™re going to publish more awesomeness wrapped in code and a tutorial on how to make UI for iOS (Android) better than better. Stay tuned! ## License The MIT License (MIT) Copyright ยฉ 2017 Yalantis 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.
168
Generate types and converters from JSON, Schema, and GraphQL
![](https://raw.githubusercontent.com/quicktype/quicktype/master/media/quicktype-logo.svg?sanitize=true) [![npm version](https://badge.fury.io/js/quicktype.svg)](https://badge.fury.io/js/quicktype) ![Build status](https://github.com/quicktype/quicktype/actions/workflows/master.yaml/badge.svg) `quicktype` generates strongly-typed models and serializers from JSON, JSON Schema, TypeScript, and [GraphQL queries](https://blog.quicktype.io/graphql-with-quicktype/), making it a breeze to work with JSON type-safely in many programming languages. - [Try `quicktype` in your browser](https://app.quicktype.io). - Read ['A first look at quicktype'](http://blog.quicktype.io/first-look/) for more introduction. - If you have any questions, check out the [FAQ](FAQ.md) first. ### Supported Inputs | JSON | JSON API URLs | [JSON Schema](https://app.quicktype.io/#s=coordinate) | | ---- | ------------- | ----------------------------------------------------- | | TypeScript | GraphQL queries | | ---------- | --------------- | ### Target Languages | [Ruby](https://app.quicktype.io/#l=ruby) | [JavaScript](https://app.quicktype.io/#l=js) | [Flow](https://app.quicktype.io/#l=flow) | [Rust](https://app.quicktype.io/#l=rust) | [Kotlin](https://app.quicktype.io/#l=kotlin) | | ---------------------------------------- | -------------------------------------------- | ---------------------------------------- | ---------------------------------------- | -------------------------------------------- | | [Dart](https://app.quicktype.io/#l=dart) | [Python](https://app.quicktype.io/#l=python) | [C#](https://app.quicktype.io/#l=cs) | [Go](https://app.quicktype.io/#l=go) | [C++](https://app.quicktype.io/#l=cpp) | | ---------------------------------------- | -------------------------------------------- | ------------------------------------ | ------------------------------------ | -------------------------------------- | | [Java](https://app.quicktype.io/#l=java) | [TypeScript](https://app.quicktype.io/#l=ts) | [Swift](https://app.quicktype.io/#l=swift) | [Objective-C](https://app.quicktype.io/#l=objc) | [Elm](https://app.quicktype.io/#l=elm) | | ---------------------------------------- | -------------------------------------------- | ------------------------------------------ | ----------------------------------------------- | -------------------------------------- | | [JSON Schema](https://app.quicktype.io/#l=schema) | [Pike](https://app.quicktype.io/#l=pike) | [Prop-Types](https://app.quicktype.io/#l=javascript-prop-types) | [Haskell](https://app.quicktype.io/#l=haskell) | | | ------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------- | --- | _Missing your favorite language? Please implement it!_ ## Installation There are many ways to use `quicktype`. [app.quicktype.io](https://app.quicktype.io) is the most powerful and complete UI. The web app also works offline and doesn't send your sample data over the Internet, so paste away! For the best CLI, we recommend installing `quicktype` globally via `npm`: ```bash npm install -g quicktype ``` Other options: - [Homebrew](http://formulae.brew.sh/formula/quicktype) _(infrequently updated)_ - [Xcode extension](https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220?mt=12)\* - [VSCode extension](https://marketplace.visualstudio.com/items/quicktype.quicktype)\* - [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=typeguard.quicktype-vs)\* <small>\* limited functionality</small> ## Using `quicktype` ```bash # Run quicktype without arguments for help and options quicktype # quicktype a simple JSON object in C# echo '{ "name": "David" }' | quicktype -l csharp # quicktype a top-level array and save as Go source echo '[1, 2, 3]' | quicktype -o ints.go # quicktype a sample JSON file in Swift quicktype person.json -o Person.swift # A verbose way to do the same thing quicktype \ --src person.json \ --src-lang json \ --lang swift \ --top-level Person \ --out Person.swift # quicktype a directory of samples as a C++ program # Suppose ./blockchain is a directory with files: # latest-block.json transactions.json marketcap.json quicktype ./blockchain -o blockchain-api.cpp # quicktype a live JSON API as a Java program quicktype https://api.somewhere.com/data -o Data.java ``` ### Generating code from JSON schema The recommended way to use `quicktype` is to generate a JSON schema from sample data, review and edit the schema, commit the schema to your project repo, then generate code from the schema as part of your build process: ```bash # First, infer a JSON schema from a sample. quicktype pokedex.json -l schema -o schema.json # Review the schema, make changes, # and commit it to your project repo. # Finally, generate model code from schema in your # build process for whatever languages you need: quicktype -s schema schema.json -o src/ios/models.swift quicktype -s schema schema.json -o src/android/Models.java quicktype -s schema schema.json -o src/nodejs/Models.ts # All of these models will serialize to and from the same # JSON, so different programs in your stack can communicate # seamlessly. ``` ### Generating code from TypeScript (Experimental) You can achieve a similar result by writing or generating a [TypeScript](http://www.typescriptlang.org/) file, then quicktyping it. TypeScript is a typed superset of JavaScript with simple, succinct syntax for defining types: ```typescript interface Person { name: string; nickname?: string; // an optional property luckyNumber: number; } ``` You can use TypeScript just like JSON schema was used in the last example: ```bash # First, infer a TypeScript file from a sample (or just write one!) quicktype pokedex.json -o pokedex.ts --just-types # Review the TypeScript, make changes, etc. quicktype pokedex.ts -o src/ios/models.swift ``` ### Calling `quicktype` from JavaScript You can use `quicktype` as a JavaScript function within `node` or browsers. First add the `quicktype-core` package: ```bash $ npm install quicktype-core ``` In general, first you create an `InputData` value with one or more JSON samples, JSON schemas, TypeScript sources, or other supported input types. Then you call `quicktype`, passing that `InputData` value and any options you want. ```javascript import { quicktype, InputData, jsonInputForTargetLanguage, JSONSchemaInput, FetchingJSONSchemaStore } from "quicktype-core"; async function quicktypeJSON(targetLanguage, typeName, jsonString) { const jsonInput = jsonInputForTargetLanguage(targetLanguage); // We could add multiple samples for the same desired // type, or many sources for other types. Here we're // just making one type from one piece of sample JSON. await jsonInput.addSource({ name: typeName, samples: [jsonString] }); const inputData = new InputData(); inputData.addInput(jsonInput); return await quicktype({ inputData, lang: targetLanguage }); } async function quicktypeJSONSchema(targetLanguage, typeName, jsonSchemaString) { const schemaInput = new JSONSchemaInput(new FetchingJSONSchemaStore()); // We could add multiple schemas for multiple types, // but here we're just making one type from JSON schema. await schemaInput.addSource({ name: typeName, schema: jsonSchemaString }); const inputData = new InputData(); inputData.addInput(schemaInput); return await quicktype({ inputData, lang: targetLanguage }); } async function main() { const { lines: swiftPerson } = await quicktypeJSON("swift", "Person", jsonString); console.log(swiftPerson.join("\n")); const { lines: pythonPerson } = await quicktypeJSONSchema("python", "Person", jsonSchemaString); console.log(pythonPerson.join("\n")); } main(); ``` The argument to `quicktype` is a complex object with many optional properties. [Explore its definition](https://github.com/quicktype/quicktype/blob/master/src/quicktype-core/Run.ts#L119) to understand what options are allowed. ## Contributing `quicktype` is [Open Source](LICENSE) and we love contributors! In fact, we have a [list of issues](https://github.com/quicktype/quicktype/issues?utf8=โœ“&q=is%3Aissue+is%3Aopen+label%3Ahelp-wanted) that are low-priority for us, but for which we'd happily accept contributions. Support for new target languages is also strongly desired. If you'd like to contribute, need help with anything at all, or would just like to talk things over, come [join us on Slack](http://slack.quicktype.io/). ### Setup, Build, Run `quicktype` is implemented in TypeScript and requires `nodejs` and `npm` to build and run. First, install `typescript` globally via `npm`: Clone this repo and do: #### macOS / Linux ```bash nvm use npm install script/quicktype # rebuild (slow) and run (fast) ``` #### Windows ```bash npm install --ignore-scripts # Install dependencies npm install -g typescript # Install typescript globally tsc --project src/cli # Rebuild node dist\cli\index.js # Run ``` ### Edit Install [Visual Studio Code](https://code.visualstudio.com/), open this workspace, and install the recommended extensions: ```bash code . # opens in VS Code ``` ### Live-reloading for quick feedback When working on an output language, you'll want to view generated output as you edit. Use `npm start` to watch for changes and recompile and rerun `quicktype` for live feedback. For example, if you're developing a new renderer for `fortran`, you could use the following command to rebuild and reinvoke `quicktype` as you implement your renderer: ```bash npm start -- "--lang fortran pokedex.json" ``` The command in quotes is passed to `quicktype`, so you can render local `.json` files, URLs, or add other options. ### Test ```bash # Run full test suite npm run test # Test a specific language (see test/languages.ts) FIXTURE=golang npm test # Test a single sample or directory FIXTURE=swift npm test -- pokedex.json FIXTURE=swift npm test -- test/inputs/json/samples ```
169
Collection of models for Core ML
<img src="core-ml.png" align="left" width="64"> # Awesome Core ML models [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) This repository has a collection of Open Source machine learning models which work with Apples **Core ML** standard. Apple has published some of their own models. They can be downloaded [here](https://developer.apple.com/machine-learning/). Those published models are: **SqueezeNet, Places205-GoogLeNet, ResNet50, Inception v3, VGG16** and will not be republished in this repository. ## Contributing If you want your model added simply create a pull request with your repository and model added. In order to keep the quality of this repository you have to conform to this project structure (taken from **@hollance**). ``` โ”œโ”€โ”€ Convert ย ย  โ”œโ”€โ”€ coreml.py ย ย  โ”œโ”€โ”€ mobilenet_deploy.prototxt ย ย  โ””โ”€โ”€ synset_words.txt ``` There has to be a **Convert** directory with a Python script and additional data to reproduce this model on your own. If your model requires a huge amount of space please include a script which downloads those files. ``` โ”œโ”€โ”€ MobileNetCoreML โ”‚ย ย  โ”œโ”€โ”€ *.swift โ”œโ”€โ”€ MobileNetCoreML.xcodeproj โ”‚ย ย  โ”œโ”€โ”€ project.pbxproj โ”‚ย ย  โ””โ”€โ”€ project.xcworkspace โ”‚ย ย  โ””โ”€โ”€ contents.xcworkspacedata โ”œโ”€โ”€ README.markdown ``` You also have to have an Xcode project where the user can test the model (sample data included would be nice). This is a template for the README to copy: ``` ### Name of your model **Model:** [Model.mlmodel](link for downloading) <br /> **Description:** Short description <br /> **Author:** [Author](https://github.com/author) <br /> **Reference:** [Name of reference](URL to reference) <br /> **Example:** [Your example project](URL to example project) <br /> ``` ## Models ### MobileNet **Model:** [MobileNet.mlmodel](https://github.com/hollance/MobileNet-CoreML/raw/master/MobileNet.mlmodel) <br /> **Description:** Object detection, finegrain classification, face attributes and large scale geo-localization <br /> **Author:** [Matthijs Hollemans](https://github.com/hollance) <br /> **Reference:** [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861v1) <br /> **Example:** [MobileNet-CoreML](https://github.com/hollance/MobileNet-CoreML) <br /> ### MNIST **Model:** [MNIST.mlmodel](https://github.com/ph1ps/MNIST-CoreML/raw/master/MNISTPrediction/MNIST.mlmodel) <br /> **Description:** Handwritten digit classification <br /> **Author:** [Philipp Gabriel](https://github.com/ph1ps) <br /> **Reference:** [MNIST handwritten digit database](http://yann.lecun.com/exdb/mnist/) <br /> **Example:** [MNIST-CoreML](https://github.com/ph1ps/MNIST-CoreML) <br /> ### Food101 **Model:** [Food101.mlmodel](https://drive.google.com/open?id=0B5TjkH3njRqnVjBPZGRZbkNITjA) <br /> **Description:** Food classification <br /> **Author:** [Philipp Gabriel](https://github.com/ph1ps) <br /> **Reference:** [UPMC Food-101](http://visiir.lip6.fr/explore) <br /> **Example:** [Food101-CoreML](https://github.com/ph1ps/Food101-CoreML) <br /> ### SentimentPolarity **Model:** [SentimentPolarity](https://github.com/cocoa-ai/SentimentCoreMLDemo/raw/master/SentimentPolarity/Resources/SentimentPolarity.mlmodel) <br /> **Description:** Sentiment Polarity Analysis <br /> **Author:** [Vadym Markov](https://github.com/vadymmarkov) <br /> **Reference:** [Epinions.com reviews dataset](http://boston.lti.cs.cmu.edu/classes/95-865-K/HW/HW3/) <br /> **Example:** [SentimentCoreMLDemo](https://github.com/cocoa-ai/SentimentCoreMLDemo) <br /> ### VisualSentimentCNN **Model:** [VisualSentimentCNN](https://drive.google.com/open?id=0B1ghKa_MYL6mZ0dITW5uZlgyNTg) <br /> **Description:** Visual Sentiment Prediction <br /> **Author:** [Image Processing Group - BarcelonaTECH - UPC](https://github.com/imatge-upc) <br /> **Reference:** [From Pixels to Sentiment: Fine-tuning CNNs for Visual Sentiment Prediction](https://github.com/imatge-upc/sentiment-2017-imavis) <br /> **Example:** [SentimentVisionDemo](https://github.com/cocoa-ai/SentimentVisionDemo) <br /> ### AgeNet **Model:** [AgeNet](https://drive.google.com/file/d/0B1ghKa_MYL6mT1J3T1BEeWx4TWc/view?usp=sharing) <br /> **Description:** Age Classification <br /> **Author:** [Gil Levi and Tal Hassner](http://www.openu.ac.il/home/hassner/projects/cnn_agegender/) <br /> **Reference:** [Age and Gender Classification using Convolutional Neural Networks](http://www.openu.ac.il/home/hassner/projects/cnn_agegender/CNN_AgeGenderEstimation.pdf) <br /> **Example:** [FacesVisionDemo](https://github.com/cocoa-ai/FacesVisionDemo) <br /> ### GenderNet **Model:** [GenderNet](https://drive.google.com/file/d/0B1ghKa_MYL6mYkNsZHlyc2ZuaFk/view?usp=sharing) <br /> **Description:** Gender Classification <br /> **Author:** [Gil Levi and Tal Hassner](http://www.openu.ac.il/home/hassner/projects/cnn_agegender/) <br /> **Reference:** [Age and Gender Classification using Convolutional Neural Networks](http://www.openu.ac.il/home/hassner/projects/cnn_agegender/CNN_AgeGenderEstimation.pdf) <br /> **Example:** [FacesVisionDemo](https://github.com/cocoa-ai/FacesVisionDemo) <br /> ### CNNEmotions **Model:** [CNNEmotions](https://drive.google.com/file/d/0B1ghKa_MYL6mTlYtRGdXNFlpWDQ/view?usp=sharing) <br /> **Description:** Emotion Recognition <br /> **Author:** [Gil Levi and Tal Hassner](http://www.openu.ac.il/home/hassner/projects/cnn_emotions/) <br /> **Reference:** [Emotion Recognition in the Wild via Convolutional Neural Networks and Mapped Binary Patterns](http://www.openu.ac.il/home/hassner/projects/cnn_emotions/LeviHassnerICMI15.pdf) <br /> **Example:** [FacesVisionDemo](https://github.com/cocoa-ai/FacesVisionDemo) <br /> ### NamesDT **Model:** [NamesDT](https://github.com/cocoa-ai/NamesCoreMLDemo/raw/master/Names/Resources/NamesDT.mlmodel) <br /> **Description:** Gender Classification from first names <br /> **Author:** [http://nlpforhackers.io](http://nlpforhackers.io) <br /> **Reference:** [Is it a boy or a girl? An introduction to Machine Learning](http://nlpforhackers.io/introduction-machine-learning/) <br /> **Example:** [NamesCoreMLDemo](https://github.com/cocoa-ai/NamesCoreMLDemo) <br /> ### Oxford102 **Model:** [Oxford102](https://drive.google.com/file/d/0B1ghKa_MYL6meDBHT2NaZGxkNzQ/view?usp=sharing) <br /> **Description:** Flower Classification <br /> **Author:** [Jimmie Goode](https://github.com/jimgoo) <br /> **Reference:** [Classifying images in the Oxford 102 flower dataset with CNNs](http://jimgoo.com/flower-power/) <br /> **Example:** [FlowersVisionDemo](https://github.com/cocoa-ai/FlowersVisionDemo) <br /> ### FlickrStyle **Model:** [FlickrStyle](https://drive.google.com/file/d/0B1ghKa_MYL6maFFWR3drLUFNQ1E/view?usp=sharing) <br /> **Description:** Image Style Classification <br /> **Author:** [Sergey Karayev](https://gist.github.com/sergeyk) <br /> **Reference:** [Recognizing Image Style](http://sergeykarayev.com/files/1311.3715v3.pdf) <br /> **Example:** [StylesVisionDemo](https://github.com/cocoa-ai/StylesVisionDemo) <br /> ## Model Demonstration App <p align="left"> <img src="https://github.com/eugenebokhan/Awesome-ML/raw/master/Media/header.png", width="640"> </p> <p align="left"> <img src="https://github.com/eugenebokhan/Awesome-ML/raw/master/Media/Cards_Scroll_Demonstration_640.gif", width="640"> </p> **Description:** Discover, download, on-device-compile & launch different image processing CoreML models on iOS. <br /> **Author:** [Eugene Bokhan](https://github.com/eugenebokhan) <br /> **Source:** [Awesome ML](https://github.com/eugenebokhan/Awesome-ML) <br /> **Lincese:** [BSD 3-Clause](https://github.com/eugenebokhan/Awesome-ML/blob/master/LICENSE.md) <br />
170
leetcode.com , algoexpert.io solutions in python and swift
<h1 align="center"> <br> <a href="https://github.com/partho-maple/coding-interview-gym/archive/master.zip"><img src="leetcode.png"></a> <a href="https://github.com/partho-maple/coding-interview-gym/archive/master.zip"><img src="algoexpert.png"></a> </h1> [![GitHub last commit][last-commit-shield]][last-commit-url] [![GitHub repo size in bytes][repo-size-shield]][repo-size-url] [![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![Issues][issues-shield]][issues-url] [![MIT License][license-shield]][license-url] [![LinkedIn][linkedin-shield]][linkedin-url] [![Travis](https://img.shields.io/badge/language-Swift-green.svg)]() [![Travis](https://img.shields.io/badge/language-Python-red.svg)]() <h4 align="center">This repo contains around 700 (600 Leetcode.com and 100 Algoexpert.io) problems in total, with solutions using Swift and Python</h4> <p align="center"> This repo contains my solutions to algorithmic problems in <a href="https://leetcode.com/parthobiswas007/">leetcode.com</a> and <a href="https://www.algoexpert.io/questions">algoexpert.io</a> written in <b>Swift</b> and <b>Python</b>. </p> <h4 align="center">Show your support by giving it a STAR</h4> <p align="center"> <a href="#About">About</a> โ€ข <a href="#Topics">Topics</a> โ€ข <a href="#Tips">Tips</a> โ€ข <a href="#LeetCode">LeetCode.com</a> โ€ข <a href="#AlgoExpert">AlgoExpert.io</a> โ€ข <a href="#References">References</a> </p> --- --- ## About I have solved quite a number of problems from several topics. See the below table for further details. ## Topics - Binary Search - Binary Search Tree - Binary Tree(Segment Tree) - N-aray Tree(Trie, Binary Indexed Tree) - Graph(Dijkstra, Union Find, Kruskal, Prim's, Minimum Spanning Tree, Topological Ordering...etc) - Stack - Queue - Array - Sorting - Hash Table - Heap - Linked list - Bit Operation - Dynamic programming - Backtracking(Permutations & Combinations & Subsets...etc) - Math - and more... ## Questions from - [Leetcode](https://leetcode.com) - [Algoexpert.io](Algoexpert.io) ## My other related repos - [Coding Interview Patterns](https://tinyurl.com/wluap5j) - [Coding Interview Gym](https://tinyurl.com/wt2dbym) - [iOS Interview Gym](https://tinyurl.com/wt5vyzq) - [Behavioural Interview Gym](https://tinyurl.com/v65wlwf) - [System Design Interview Gym](https://tinyurl.com/tr2xkze) - [Object Oriented Design Interview Gym](https://tinyurl.com/uhlp9sc) ## My leetcode account - [ParthoBiswas007](https://leetcode.com/ParthoBiswas007/) ## Tips - Check this **[Golden](https://tinyurl.com/uboo399)** post first. - Whenever you solve a new question with some new techniques/algorithms, try to solve atleast 2 similar problem in a row. This way, your understanding to the new techniques/algorithms will be better. - Solve all [leetcode cards](https://leetcode.com/explore/learn/) --- --- ## LeetCode [![leetcode badge](https://leetcode-badge.chyroc.cn/?name=ParthoBiswas007&leetcode_badge_style=leetcode%20|%20solved/total-{{.solved_question}}/{{.all_question}}-{{if%20le%20.solved_question_rate_float%200.3}}red.svg{{else%20if%20le%20.solved_question_rate_float%200.5}}yellow.svg{{else}}green.svg{{end}}&refresh=true)](https://leetcode.com/ParthoBiswas007/) ### 1. [Arrays](https://leetcode.com/explore/learn/card/array-and-string/) , [HashMap](https://leetcode.com/explore/learn/card/hash-table/), Set <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [1. Two Sum](https://leetcode.com/problems/two-sum/)| [Python](https://tinyurl.com/wu6rdaw/1_Two_Sum.py), [Swift](https://tinyurl.com/to2yjbw/leetcode.com/swift/1_Two_Sum.swift) | --- | --- | โœ… ๐Ÿ“Œ โญ ๐Ÿ˜ญ ๐Ÿง ๐Ÿ˜Ž | |02| [485. Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)| [Swift](https://tinyurl.com/to2yjbw/leetcode.com/swift/485_Max_Consecutive_Ones.swift)| |03| [476. Number Complement](https://leetcode.com/problems/number-complement/)| [Swift](https://tinyurl.com/to2yjbw/leetcode.com/swift/476_Number_Complement.swift)| |04| [461. Hamming Distance](https://leetcode.com/problems/hamming-distance/)| [Swift](https://tinyurl.com/to2yjbw/leetcode.com/swift/461_Hamming_Distance.swift)| |05| [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/)| [Python](https://tinyurl.com/wu6rdaw/9_Palindrome_Number.py)| |06| [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/)| [Python](https://tinyurl.com/wu6rdaw/88_Merge_Sorted_Array.py)| |07| [811. Subdomain Visit Count](https://leetcode.com/problems/subdomain-visit-#/)| [Python](https://tinyurl.com/wu6rdaw/811_Subdomain_Visit_Count.py)| |08| [771. Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/)| [Python](https://tinyurl.com/wu6rdaw/771_Jewels_and_Stones.py)| |09| [414. Third Maximum Number](https://leetcode.com/problems/third-maximum-number/)| [Python](https://tinyurl.com/wu6rdaw/414_Third_Maximum_Number.py)| |10| [259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)| [Python](https://tinyurl.com/wu6rdaw/259_3Sum_Smaller.py)| |11| [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)| [Python](https://tinyurl.com/wu6rdaw/16_3Sum_Closest.py)| |12| [15. 3Sum](https://leetcode.com/problems/3sum/)| [Python](https://tinyurl.com/wu6rdaw/15_3Sum.py)| |13| [118. Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)| [Python](https://tinyurl.com/wu6rdaw/118_Pascal's_Triangle.py)| |14| [119. Pascal's Triangle II](https://leetcode.com/problems/pascals-triangle-ii/)| [Python](https://tinyurl.com/wu6rdaw/119_Pascal's_Triangle_II.py)| |15| [238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/solution/)| [Python](https://tinyurl.com/wu6rdaw/238_Product_of_Array_Except_Self.py), [Swift](https://tinyurl.com/wuja3c4/238_Product_of_Array_Except_Self.swift) | |16| [724. Find Pivot Index](https://leetcode.com/problems/find-pivot-index/)| [Python](https://tinyurl.com/wu6rdaw/724_Find_Pivot_Index.py)| | |17| [747. Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/)| [Python](https://tinyurl.com/wu6rdaw/747_Largest_Number_At_Least_Twice_of_Others.py)| | |18| [581. Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/)| [Python](https://tinyurl.com/wu6rdaw/581_Shortest_Unsorted_Continuous_Subarray.py)| | |19| [904. Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/solution/)| [Python](https://tinyurl.com/wu6rdaw/904_Fruit_Into_Baskets.py)| [Article](https://www.educative.io/courses/grokking-the-coding-interview/Bn2KLlOR0lQ), [Video 1](https://www.youtube.com/watch?v=s_zu2dOkq80), [Video 2](https://www.youtube.com/watch?v=za2YuucS0tw)| Medium | [Sliding Window, Two Pointer](https://github.com/partho-maple/coding-interview-patterns) | |20| [56. Merge Intervals](https://leetcode.com/problems/merge-intervals/)| [Python](https://tinyurl.com/wu6rdaw/56_Merge_Intervals.py)| [Article](https://leetcode.com/problems/merge-intervals/discuss/21227/7-lines-easy-Python), [Swift](https://tinyurl.com/wuja3c4/56_Merge_Intervals.swift) | |21| [334. Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)| [Python](https://tinyurl.com/wu6rdaw/334_Increasing_Triplet_Subsequence.py)| --- | Medium | --- | |22| [792. Number of Matching Subsequences](https://leetcode.com/problems/number-of-matching-subsequences/)| [Python](https://tinyurl.com/wu6rdaw/792_Number_of_Matching_Subsequences.py)| **[Official](https://leetcode.com/problems/number-of-matching-subsequences/discuss/117634/Efficient-and-simple-go-through-words-in-parallel-with-explanation/)** | Medium | **Very tricky. Check again** | |23| [912. Sort an Array (Merge Sort)](https://leetcode.com/problems/sort-an-array/)| [Python](https://tinyurl.com/wu6rdaw/912_Sort_an_Array_(Merge__Sort).py)|--- | Medium | --- | |24| [1118. Number of Days in a Month](https://leetcode.com/problems/number-of-days-in-a-month/)| [Python](https://tinyurl.com/wu6rdaw/1118_-Number_of_Days_in_a_Month.py)|--- | Easy | --- | |25| [349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/)| [Python](https://tinyurl.com/wu6rdaw/349_Intersection_of_Two_Arrays.py)| [Art 1](https://tinyurl.com/rh3s2gp), [Art 2](https://tinyurl.com/ts27qxq) | Easy | **Very tricky and versatile** | |26| [350. Intersection of Two Arrays II](https://leetcode.com/problems/intersection-of-two-arrays-ii/)| [Python](https://tinyurl.com/wu6rdaw/350_Intersection_of_Two_Arrays_II.py)| [](), [](), []() | Easy | **Very tricky and versatile** | |27| [303. Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/)| [Python](https://tinyurl.com/wu6rdaw/303_Range_Sum_Query-Immutable.py)| [Vid 1](https://tinyurl.com/qkaq2oa) | Easy | --- | |28| [560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)| [Python](https://tinyurl.com/wu6rdaw/560_Subarray_Sum_Equals_K.py), [Swift](https://tinyurl.com/wuja3c4/560_Subarray_Sum_Equals_K.swift) | [Art 1](https://tinyurl.com/rd8d7b7), [Art 2](https://tinyurl.com/uhkjk84), [Art 3](https://tinyurl.com/v62x843), [Art 4](https://tinyurl.com/tonp2ye), [Art 5](https://tinyurl.com/uhkjk84), [Art 6](https://tinyurl.com/upuh6ax) | Medium | **Very tricky and persuasive with Sliding Window but it's not. This is a classic running sum problem** | |29| [325. Maximum Size Subarray Sum Equals k](https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/)| [Python](https://tinyurl.com/wu6rdaw/325_Maximum_Size_Subarray_Sum_Equals_k.py)| [Art 1](https://tinyurl.com/sksjlzg) | Medium | **Very tricky and persuasive with Sliding Window but it's not. This is a classic running sum problem** | |30| [1074. Number of Submatrices That Sum to Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)| [Python](https://tinyurl.com/wu6rdaw/1074_Number_of_Submatrices_That_Sum_to_Target.py)| [Art 1](https://tinyurl.com/yydt3tpy), [Art 2](https://tinyurl.com/vhwht5j), [Art 3](https://tinyurl.com/rrelm6y), [Art 4](https://tinyurl.com/s9mwbfy) | Extremely Hard | **Very tricky and hard, check again. Also DP** | |31| [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)| [Python](https://tinyurl.com/wu6rdaw/167_Two_Sum_II_-_Input_array_is_sorted.py)| --- | Easy | Two pointer basics | |32| [1099. Two Sum Less Than K](https://leetcode.com/problems/two-sum-less-than-k/)| [Python](https://tinyurl.com/wu6rdaw/1099_Two_Sum_Less_Than_K.py)| --- | Easy | Two pointer basics | |33| [26. Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)| [Python](https://tinyurl.com/wu6rdaw/26_Remove_Duplicates_from_Sorted_Array.py)| --- | Easy | Two pointer basics | |34| [977. Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/)| [Python](https://tinyurl.com/wu6rdaw/977_Squares_of_a_Sorted_Array.py)| --- | Easy | Two pointer basics | |35| [713. Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/)| [Python](https://tinyurl.com/wu6rdaw/713_Subarray_Product_Less_Than_K.py)| --- | Medium | Two pointer ad Sliding Window | |36| [75. Sort Colors](https://leetcode.com/problems/sort-colors/)| [Python](https://tinyurl.com/wu6rdaw/75_Sort_Colors.py)| [Vid 1](https://tinyurl.com/svdmwg8) | Medium | Two pointer | |37| [18. 4Sum](https://leetcode.com/problems/4sum/)| [Python](https://tinyurl.com/wu6rdaw/18_4Sum.py)| --- | Medium | Two pointer | |38| [11. Container With Most Water](https://tinyurl.com/r4jdatg)| [Python](https://tinyurl.com/wu6rdaw/11_Container_With_Most_Water.py)| --- | Medium | Two pointer | |39| [202. Happy Number](https://tinyurl.com/ujm63nf)| [Python](https://tinyurl.com/wu6rdaw/202_Happy_Number.py)| [Art 1](https://tinyurl.com/roegfpt) | Easy | Fast pointer Slow pointer | |40| [457. Circular Array Loop](http://bit.ly/2skNL8X)| [Python](https://tinyurl.com/wu6rdaw/457_Circular_Array_Loop.py)| --- | Medium | Fast pointer Slow pointer. Check again | |41| [448. Find All Numbers Disappeared in an Array](https://tinyurl.com/vd3u4ne)| [Python](https://tinyurl.com/wu6rdaw/448_Find_All_Numbers_Disappeared_in_an_Array.py)| --- | Easy | Cyclic Sort | |42| [287. Find the Duplicate Number](https://tinyurl.com/ua342v6)| [Python](https://tinyurl.com/wu6rdaw/287_Find_the_Duplicate_Number.py)| --- | Medium | Cyclic Sort. TODO: Check all other approaches | |43| [442. Find All Duplicates in an Array](https://tinyurl.com/yxxs4vvn)| [Python](https://tinyurl.com/wu6rdaw/442_Find_All_Duplicates_in_an_Array.py)| --- | Medium | Cyclic Sort TODO: Check all other approaches | |44| [41. First Missing Positive](https://tinyurl.com/tfewwtv)| [Python](https://tinyurl.com/wu6rdaw/41_First_Missing_Positive.py)| --- | Hard | Cyclic Sort, Very important | |45| **[939. Minimum Area Rectangle](https://tinyurl.com/tcr34w3)** | [Python](https://tinyurl.com/wu6rdaw/939_Minimum_Area_Rectangle.py)| [Art 1](https://tinyurl.com/wfgjaf3) | Medium | Hash and Set, Very important | |46| **[359. Logger Rate Limiter](https://tinyurl.com/tcr34w3)** | [Python](https://tinyurl.com/wu6rdaw/359_Logger_Rate_Limiter.py)| --- | Easy | Hash and Set, Very important | |47| **[48. Rotate Image](https://tinyurl.com/yy3z9hab)** | [Python](https://tinyurl.com/wu6rdaw/48_Rotate_Image.py)| [Must](https://tinyurl.com/tr62top), [Vid 1](https://tinyurl.com/uhnruzt) | Medium | Very important | |48| **[362. Design Hit Counter](https://tinyurl.com/sswrcc3)** | [Python](https://tinyurl.com/wu6rdaw/362_Design_Hit_Counter.py), [Swift](https://tinyurl.com/wuja3c4/362_Design_Hit_Counter.swift)| --- | Medium | --- | |49| **[289. Game of Life](https://tinyurl.com/y5ujyvu5)** | [Python](https://tinyurl.com/wu6rdaw/289_Game_of_Life.py), [Swift](https://tinyurl.com/wuja3c4/289_Game_of_Life.swift)| --- | Medium | --- | |50| **[54. Spiral Matrix](https://tinyurl.com/yy5rnvce)** | [Python](https://tinyurl.com/wu6rdaw/54_Spiral_Matrix.py), [Swift](https://tinyurl.com/wuja3c4/54_Spiral_Matrix.swift)| [Official](https://tinyurl.com/s6np53k), [Algoexpert.io](https://www.algoexpert.io/questions/Spiral%20Traverse) | Medium | --- | |51| **[380. Insert Delete GetRandom O(1)](https://tinyurl.com/y3urnkfj)** | [Python](https://tinyurl.com/wu6rdaw/380_Insert_Delete_GetRandom_O(1).py), [Swift](https://tinyurl.com/wuja3c4/380_Insert_Delete_GetRandom_O(1).swift)| [Official](https://tinyurl.com/t4t38od) | Medium | --- | |52| **[835. Image Overlap](https://tinyurl.com/r9x9nkm)** | [Python](https://tinyurl.com/wu6rdaw/835_Image_Overlap.py), [Swift](https://tinyurl.com/wuja3c4/835_Image_Overlap.swift)| [Art 1](https://tinyurl.com/tx3gd98), [Art 2](https://tinyurl.com/tnmj6du) | Medium | --- | |53| **[1051. Height Checker](https://tinyurl.com/scupmnz)** | [Python](https://tinyurl.com/wu6rdaw/1051_Height_Checker.py), [Swift](https://tinyurl.com/wuja3c4/1051_Height_Checker.swift) | --- | Easy | | |55| **[683. K Empty Slots](https://tinyurl.com/rbyxknc)** | [Python](https://tinyurl.com/wu6rdaw/683_K_Empty_Slots.py), [Swift](https://tinyurl.com/wuja3c4/683_K_Empty_Slots.swift) | [Art 1](https://tinyurl.com/qsenvnd), [Art 2](https://tinyurl.com/u7g6hhy), [Art 3](https://tinyurl.com/vw42pp7) | Hard | TODO: Check monotonic queue approach. Solved it with sliding widow | |56| **[849. Maximize Distance to Closest Person](https://tinyurl.com/v44bs88)** | [Python](https://tinyurl.com/wu6rdaw/849_Maximize_Distance_to_Closest_Person.py), [Swift](https://tinyurl.com/wuja3c4/849_Maximize_Distance_to_Closest_Person.swift) | [Art 1](https://tinyurl.com/qsenvnd) | Easy | Not so easy and intuitive. Can be solve is a variety of way. I have used Binary search(A bit over engineered solution). Can be simplifies | |57| **[283. Move Zeroes](https://tinyurl.com/y5kxjuvc)** | [Python](https://tinyurl.com/wu6rdaw/283_Move_Zeroes.py), [Swift](https://tinyurl.com/wuja3c4/283_Move_Zeroes.swift) | --- | Easy | Not so easy and intuitive. Uses fast and slow pointer | |58| **[163. Missing Ranges](https://tinyurl.com/s297jm7)** | [Python](https://tinyurl.com/wu6rdaw/163_Missing_Ranges.py), [Swift](https://tinyurl.com/wuja3c4/163_Missing_Ranges.swift) | --- | Medium | Man, it's a very trick problem | |59| **[1089. Duplicate Zeros](https://tinyurl.com/vdlwjwa)** | [Python](https://tinyurl.com/wu6rdaw/1089_Duplicate_Zeros.py), [Swift](https://tinyurl.com/wuja3c4/1089_Duplicate_Zeros.swift) | [Art 1](https://tinyurl.com/y3b2ynd4) | Easy | Not so easy and intuitive. Check again | |60| [941. Valid Mountain Array](https://tinyurl.com/tgdqrrk) | [Python](https://tinyurl.com/wu6rdaw/941_Valid_Mountain_Array.py), [Swift](https://tinyurl.com/wuja3c4/941_Valid_Mountain_Array.swift) | | Easy | | |61| [731. My Calendar II](https://tinyurl.com/sde6smv) | [Python](https://tinyurl.com/wu6rdaw/731_My_Calendar_II.py), [Swift](https://tinyurl.com/wuja3c4/731_My_Calendar_II.swift) | | Medium | Merge interval | |62| [59. Spiral Matrix II](https://tinyurl.com/pqfjvm7) | [Python](https://tinyurl.com/wu6rdaw/59_Spiral_Matrix_II.py), [Swift](https://tinyurl.com/wuja3c4/59_Spiral_Matrix_II.swift) | | Medium | loved it | |63| **[525. Contiguous Array](https://tinyurl.com/txbs9wh)** | [Python](https://tinyurl.com/wu6rdaw/525_Contiguous_Array.py), [Swift](https://tinyurl.com/wuja3c4/525_Contiguous_Array.swift) | [Art 1](https://tinyurl.com/qmbd2vl) | Medium | loved it. Check again | |64| **[379. Design Phone Directory](https://tinyurl.com/ybs3848v)** | [Python](https://tinyurl.com/wu6rdaw/379_Design_Phone_Directory.py), [Swift](https://tinyurl.com/wuja3c4/379_Design_Phone_Directory.swift) | | Medium | | |65| **[280. Wiggle Sort](https://tinyurl.com/ybnjn6fs)** | [Python](https://tinyurl.com/wu6rdaw/280_Wiggle_Sort.py), [Swift](https://tinyurl.com/wuja3c4/280_Wiggle_Sort.swift) | | Medium | | |66| [246. Strobogrammatic Number](https://tinyurl.com/ycqwsozh) | [Python](https://tinyurl.com/wu6rdaw/246_Strobogrammatic_Number.py), [Swift](https://tinyurl.com/wuja3c4/246_Strobogrammatic_Number.swift) | | Easy | | |67| **[845. Longest Mountain in Array](https://tinyurl.com/y9h5uah5)** | [Python](https://tinyurl.com/wu6rdaw/845_Longest_Mountain_in_Array.py), [Swift](https://tinyurl.com/wuja3c4/845_Longest_Mountain_in_Array.swift) | | Medium | | |68| **[66. Plus One](https://tinyurl.com/yd67rugq)** | [Python](https://tinyurl.com/wu6rdaw/66_Plus_One.py), [Swift](https://tinyurl.com/wuja3c4/66_Plus_One.swift) | | Easy | | |69| **[957. Prison Cells After N Days](https://tinyurl.com/yag46zkm)** | [Python](https://tinyurl.com/wu6rdaw/957_Prison_Cells_After_N_Days.py), [Swift](https://tinyurl.com/wuja3c4/957_Prison_Cells_After_N_Days.swift) | [Art 1](https://tinyurl.com/y7cbf32e), [Art 2](https://tinyurl.com/yd2y66dn), [Art 3](https://tinyurl.com/yczdwnwu), [Art 4](https://tinyurl.com/y8j9b593), [Art 5](https://tinyurl.com/y6u2u42m) | Medium | | |70| [1232. Check If It Is a Straight Line](https://tinyurl.com/y932lhyb) | [Python](https://tinyurl.com/wu6rdaw/1232_Check_If_It_Is_a_Straight_Line.py), [Swift](https://tinyurl.com/wuja3c4/1232_Check_If_It_Is_a_Straight_Line.swift) | | Easy | | |71| **[348. Design Tic-Tac-Toe](https://tinyurl.com/ybtrbuso)** | [Python](https://tinyurl.com/wu6rdaw/348_Design_Tic-Tac-Toe.py), [Swift](https://tinyurl.com/wuja3c4/348_Design_Tic-Tac-Toe.swift) | [Vid 1](https://tinyurl.com/y745qzme), [Art 1](https://tinyurl.com/ybvjnmuo) | Medium | A fucking tricky question | |72| **[1152. Analyze User Website Visit Pattern](https://tinyurl.com/y8q3nw6u)** | [Python](https://tinyurl.com/wu6rdaw/1152_Analyze_User_Website_Visit_Pattern.py), [Swift](https://tinyurl.com/wuja3c4/1152_Analyze_User_Website_Visit_Pattern.swift) | [Art 1](https://tinyurl.com/y9vqr6ja), [Art 2](https://tinyurl.com/y77nax4d), [Art 3](https://tinyurl.com/y8kbvk5y), [Art 4](https://tinyurl.com/ydyxd57p) | Medium | A fucking unclear question and problem. I Fucking disliked it. | |73| **[953. Verifying an Alien Dictionary](https://tinyurl.com/y8j8e4jo)** | [Python](https://tinyurl.com/wu6rdaw/953_Verifying_an_Alien_Dictionary.py), [Swift](https://tinyurl.com/wuja3c4/953_Verifying_an_Alien_Dictionary.swift) | | Easy(REALLY!!!) | Don't be fooled by the difficulty label | |74| **[463. Island Perimeter](https://tinyurl.com/yapqj2yd)** | [Python](https://tinyurl.com/wu6rdaw/463_Island_Perimeter.py), [Swift](https://tinyurl.com/wuja3c4/463_Island_Perimeter.swift) | | Easy | It's very deceiving, to think it as a grapy ad DFS problem, but it's not. Think simply | |75| **[166. Fraction to Recurring Decimal](https://tinyurl.com/ycweccew)** | [Python](https://tinyurl.com/wu6rdaw/166_Fraction_to_Recurring_Decimal.py), [Swift](https://tinyurl.com/wuja3c4/166_Fraction_to_Recurring_Decimal.swift) | [Art 1](https://tinyurl.com/ycuah9vj) | Medium | Hate this problem. Why do companies ask this shit!!! | |75| **[311. Sparse Matrix Multiplication](https://tinyurl.com/y9lapcjx)** | [Python](https://tinyurl.com/wu6rdaw/311_Sparse_Matrix_Multiplication.py), [Swift](https://tinyurl.com/wuja3c4/311_Sparse_Matrix_Multiplication.swift) | [Art 1](https://tinyurl.com/ycv24vc4), [Art 2](https://tinyurl.com/ycmqcfw9), [Art 3](https://tinyurl.com/y9az7nef), **[Art 4](https://tinyurl.com/y84lwkya)** | Medium | Very tricky | |76| **[896. Monotonic Array](https://tinyurl.com/y8a95fb6)** | [Python](https://tinyurl.com/wu6rdaw/896_Monotonic_Array.py), [Swift](https://tinyurl.com/wuja3c4/896_Monotonic_Array.swift) | --- | Eassy | | |77| **[670. Maximum Swap](https://tinyurl.com/y2zhdd33)** | [Python](https://tinyurl.com/wu6rdaw/670_Maximum_Swap.py), [Swift](https://tinyurl.com/wuja3c4/670_Maximum_Swap.swift) | [Art 1](https://tinyurl.com/y8vqklj3) | Medium | | |78| **[825. Friends Of Appropriate Ages](https://tinyurl.com/ycgnqxb8)** | [Python](https://tinyurl.com/wu6rdaw/825_Friends_Of_Appropriate_Ages.py), [Swift](https://tinyurl.com/wuja3c4/825_Friends_Of_Appropriate_Ages.swift) | [Art 1](https://tinyurl.com/yd4oal3l) | Medium | Think differently from a different angle. Loved this problem | |79| **[189. Rotate Array](https://tinyurl.com/yalocp9r)** | [Python](https://tinyurl.com/wu6rdaw/189_Rotate_Array.py), [Swift](https://tinyurl.com/wuja3c4/189_Rotate_Array.swift) | --- | Easy | Getting to inplace (O(n) time and O(1) space) solution is tricky. | |80| **[1004. Max Consecutive Ones III](https://tinyurl.com/ty23c3s)** | [Python](https://tinyurl.com/wu6rdaw/1004_Max_Consecutive_Ones_III.py), [Swift](https://tinyurl.com/wuja3c4/1004_Max_Consecutive_Ones_III.swift) | --- | Medium | Solution is tricky. | |81| **[498. Diagonal Traverse](https://tinyurl.com/yccvh3rq)** | [Python](https://tinyurl.com/wu6rdaw/498_Diagonal_Traverse.py), [Swift](https://tinyurl.com/wuja3c4/498_Diagonal_Traverse.swift) | --- | Medium | --- | |82| **[766. Toeplitz Matrix](https://tinyurl.com/s3z4lem)** | [Python](https://tinyurl.com/wu6rdaw/766_Toeplitz_Matrix.py), [Swift](https://tinyurl.com/wuja3c4/766_Toeplitz_Matrix.swift) | --- | Easy | --- | |83| **[1031. Maximum Sum of Two Non-Overlapping Subarrays](https://tinyurl.com/y3x46a5t)** | [Python](https://tinyurl.com/wu6rdaw/1031_Maximum_Sum_of_Two_Non_Overlapping_Subarrays.py), [Swift](https://tinyurl.com/wuja3c4/1031_Maximum_Sum_of_Two_Non_Overlapping_Subarrays.swift) | --- | Medium | PrefixSum | |84| **[1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit](https://tinyurl.com/yysmvobr)** | [Python](https://tinyurl.com/wu6rdaw/1438_Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.py), [Swift](https://tinyurl.com/wuja3c4/1438_Longest_Continuous_Subarray_With_Absolute_Diff_Less_Than_or_Equal_to_Limit.swift) | (Art 1)[https://tinyurl.com/y69hjhjp], (Art 2)[https://tinyurl.com/y3h2fj2m] | Medium | Sliding window | |85| **[1428. Leftmost Column with at Least a One](https://tinyurl.com/y3reu3y2)** | [Python](https://tinyurl.com/wu6rdaw/1428_Leftmost_Column_with_at_Least_a_One.py), [Swift](https://tinyurl.com/wuja3c4/1428_Leftmost_Column_with_at_Least_a_One.swift) | --- | Medium | Binary Search | |86| **[914. X of a Kind in a Deck of Cards](https://tinyurl.com/y39y2k32)** | [Python](https://tinyurl.com/wu6rdaw/914_X_of_a_Kind_in_a_Deck_of_Cards.py), [Swift](https://tinyurl.com/wuja3c4/914_X_of_a_Kind_in_a_Deck_of_Cards.swift) | --- | Easy (Not So) | | |87| **[1275. Find Winner on a Tic Tac Toe Game](https://tinyurl.com/y323arde)** | [Python](https://tinyurl.com/wu6rdaw/1275_Find_Winner_on_a_Tic_Tac_Toe_Game.py), [Swift](https://tinyurl.com/wuja3c4/1275_Find_Winner_on_a_Tic_Tac_Toe_Game.swift) | [Art 1](https://tinyurl.com/yyc54qj5) | Easy (Not So) | | |88| **[532. K-diff Pairs in an Array](https://tinyurl.com/yyrhmynd)** | [Python](https://tinyurl.com/wu6rdaw/532_K-diff_Pairs_in_an_Array.py), [Swift](https://tinyurl.com/wuja3c4/532_K-diff_Pairs_in_an_Array.swift) | [Art 1](https://tinyurl.com/y5tg5aqd) | Medium | | |89| **[128. Longest Consecutive Sequence](https://tinyurl.com/yxzab8pw)** | [Python](https://tinyurl.com/wu6rdaw/128_Longest_Consecutive_Sequence.py), [Swift](https://tinyurl.com/wuja3c4/128_Longest_Consecutive_Sequence.swift) | [Art 1](https://tinyurl.com/y5e34662) | Hard | | |90| **[1423. Maximum Points You Can Obtain from Cards](https://tinyurl.com/yxry5n5b)** | [Python](https://tinyurl.com/wu6rdaw/1423_Maximum_Points_You_Can_Obtain_from_Cards.py), [Swift](https://tinyurl.com/wuja3c4/1423_Maximum_Points_You_Can_Obtain_from_Cards.swift) | [Art 1](https://tinyurl.com/y5mohcl3), [Art 2](https://tinyurl.com/y4d7p6wh) | Medium | Very important. Learned new ways of sliding window | |91| [900. RLE Iterator](https://tinyurl.com/yxry5n5b) | [Python](https://tinyurl.com/wu6rdaw/900_RLE_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/900_RLE_Iterator.swift) | --- | Medium | - | |92| [954. Array of Doubled Pairs](https://tinyurl.com/yftjpl7m) | [Swift](https://tinyurl.com/wuja3c4/954_Array_of_Doubled_Pairs.swift) | --- | Medium | - | |93| [853. Car Fleet](https://tinyurl.com/y5h6ggg9) | [Swift](https://tinyurl.com/wuja3c4/853_Car_Fleet.swift) | [Vid 1](https://tinyurl.com/yh628kc9), [Art 1](https://tinyurl.com/ykyq2os5) ] | Medium | - | |94| [1877. Minimize Maximum Pair Sum in Array](https://tinyurl.com/yj2fbqu3) | [Swift](https://tinyurl.comz/wuja3c4/1877_Minimize_Maximum_Pair_Sum_in_Array.swift) | [Art 1](https://tinyurl.com/ygbnautj) ] | Medium | - | </p> </details> ### 2. [String](https://leetcode.com/explore/learn/card/array-and-string/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| | |02| [412. Fizz Buzz](https://leetcode.com/problems/fizz-buzz/)| [Swift](https://tinyurl.com/to2yjbw/leetcode.com/swift/412_Fizz_Buzz.swift)| |03| [937. Reorder Log Files](https://leetcode.com/problems/reorder-data-in-log-files/)| [Python](https://tinyurl.com/wu6rdaw/937_Reorder_Log_Files.py)| |03| [929. Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/)| [Python](https://tinyurl.com/wu6rdaw/929_Unique_Email_Addresses.py)| |04| [7. Reverse Integer](https://leetcode.com/problems/reverse-integer/)| [Python](https://tinyurl.com/wu6rdaw/7_Reverse_Integer.py)| |05| [13. Roman to Integer](https://leetcode.com/problems/roman-to-integer/)| [Python](https://tinyurl.com/wu6rdaw/13_Roman_to_Integer.py)| |06| [125. Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)| [Python](https://tinyurl.com/wu6rdaw/125_Valid_Palindrome.py), [Swift](https://tinyurl.com/wuja3c4/125_Valid_Palindrome.swift) | |07| [161. One Edit Distance](https://leetcode.com/problems/one-edit-distance/)| [Python](https://tinyurl.com/wu6rdaw/161_One_Edit_Distance.py)| |08| [1119. Remove Vowels from a String](https://leetcode.com/problems/remove-vowels-from-a-string/)| [Python](https://tinyurl.com/wu6rdaw/1119_Remove_Vowels_from_a_String.py)| |09| [344. Reverse String](https://leetcode.com/problems/reverse-string/)| [Python](https://tinyurl.com/wu6rdaw/344_Reverse_String.py)| |10| [482. License Key Formatting](https://leetcode.com/problems/license-key-formatting/)| [Python](https://tinyurl.com/wu6rdaw/482_License_Key_Formatting.py)| | |11| [3. Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| [Python](https://tinyurl.com/wu6rdaw/3_Longest_Substring_Without_Repeating_Characters.py)| [Vid 1](https://tinyurl.com/tbwjwcf), [Vid 2](https://www.youtube.com/watch?v=3IETreEybaA) | Medium | ๐Ÿ“Œ Sliding window, Two pointer | |12| [340. Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/)| [Python](https://tinyurl.com/wu6rdaw/340_Longest_Substring_with_At_Most_K_Distinct_Characters.py), [Swift](https://tinyurl.com/wuja3c4/340_Longest_Substring_with_At_Most_K_Distinct_Characters.swift) | [Vid 1](https://tinyurl.com/t55ef99), [Art 1](https://tinyurl.com/vxumhku), [Art 2](https://tinyurl.com/ukyev7f) | Hard | ๐Ÿ“Œ Sliding window, Two pointer | |13| [159. Longest Substring with At Most Two Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/)| [Python](https://tinyurl.com/wu6rdaw/159_Longest_Substring_with_At_Most_Two_Distinct_Characters.py)| [Vid 1](https://tinyurl.com/t55ef99) | Hard | ๐Ÿ“Œ Sliding window, Two pointer | |14| [424. Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)| [Python](https://tinyurl.com/wu6rdaw/424_Longest_Repeating_Character_Replacement.py)| **[Vid 1](https://tinyurl.com/svyns7x)**, [Vid 2](https://tinyurl.com/rj3yt25), [Art 1](https://tinyurl.com/yx34cd9c), [Art 2](https://tinyurl.com/suxeoj3), [Art 3](https://tinyurl.com/slpeqnd), [Art 4](https://tinyurl.com/sje2no8) | Medium | ๐Ÿ“Œ Sliding window, Very important | |15| **[76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)** | [Python](https://tinyurl.com/wu6rdaw/76_Minimum_Window_Substring.py)| **[Vid 1](https://tinyurl.com/tv8lqpa)**, **[Vid 2](https://tinyurl.com/v38h4j4)**, **[Vid 3](https://tinyurl.com/ss5ue49)** | Hard | ๐Ÿ“Œ Sliding window, Very important | |16| [727. Minimum Window Subsequence](https://leetcode.com/problems/minimum-window-subsequence/)| [Python](https://tinyurl.com/wu6rdaw/727_Minimum_Window_Subsequence.py)| [Vid 1](https://tinyurl.com/seyskk7), [Art 1](https://tinyurl.com/vs9qedt), [Art 2](https://tinyurl.com/v5tud73) | Hard | ๐Ÿ“Œ Sliding window and DP, check the DP approach | |17| [438. Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)| [Python](https://tinyurl.com/wu6rdaw/438_Find_All_Anagrams_in_a_String.py), [Swift](https://tinyurl.com/wuja3c4/438_Find_All_Anagrams_in_a_String.swift) | **[Must](https://tinyurl.com/y8jsku3f)**, [Art 1](https://tinyurl.com/wzdp4yp) | Medium | ๐Ÿ“Œ Sliding window | |18| [567. Permutation in String](https://leetcode.com/problems/permutation-in-string/)| [Python](https://tinyurl.com/wu6rdaw/567_Permutation_in_String.py)| **[Must](https://tinyurl.com/y8jsku3f)** | Medium | ๐Ÿ“Œ Sliding window | |19| [844. Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/)| [Python](https://tinyurl.com/wu6rdaw/844_Backspace_String_Compare.py)| --- | Easy | ๐Ÿ“Œ Two Pointer | |20| **[809. Expressive Words](https://tinyurl.com/vuv9uud)**| [Python](https://tinyurl.com/wu6rdaw/809_Expressive_Words.py)| [Art 1](https://tinyurl.com/rzlvfn7) | Medium | ๐Ÿ“Œ Logic ad analytical prolem | |21| **[271. Encode and Decode Strings](https://tinyurl.com/u7hce8m)**| [Python](https://tinyurl.com/wu6rdaw/271_Encode_and_Decode_Strings.py)| [Art 1](https://tinyurl.com/wurc9am) | Medium | ๐Ÿ“Œ TODO: Check the second approach. Very Important | |22| **[299. Bulls and Cows](https://tinyurl.com/hqcq2v3)**| [Python](https://tinyurl.com/wu6rdaw/299_Bulls_and_Cows.py)| --- | Easy | --- | |23| **[833. Find And Replace in String](https://tinyurl.com/yxsjcjym)**| [Python](https://tinyurl.com/wu6rdaw/833_Find_And_Replace_in_String.py)| [Art 1](https://tinyurl.com/y5hod6np) | Medium | --- | |24| **[49. Group Anagrams](https://tinyurl.com/rdcu89b)**| [Python](https://tinyurl.com/wu6rdaw/49_Group_Anagrams.py)| [Art 1](https://tinyurl.com/yxyb5pel), [Algoexpert.io](https://tinyurl.com/qwannee) | Medium | --- | |25| [551. Student Attendance Record I](https://tinyurl.com/qu89xt8)| [Python](https://tinyurl.com/wu6rdaw/551_Student_Attendance_Record_I.py)| | Easy | --- | |26| [242. Valid Anagram](https://tinyurl.com/yguqjw2g)| [Python](https://tinyurl.com/wu6rdaw/242_Valid_Anagram.py), [Swift](https://tinyurl.com/wuja3c4/242_Valid_Anagram.swift) | | Easy | --- | |27| [1358. Number of Substrings Containing All Three Characters](https://tinyurl.com/ufhkahy)| [Python](https://tinyurl.com/wu6rdaw/1358_Number_of_Substrings_Containing_All_Three_Characters.py), [Swift](https://tinyurl.com/wuja3c4/1358_Number_of_Substrings_Containing_All_Three_Characters.swift) | [Art 1](https://tinyurl.com/sespxql) | Medium | Sliding Window | |28| **[459. Repeated Substring Pattern](https://tinyurl.com/tg4sjty)** | [Python](https://tinyurl.com/wu6rdaw/459_Repeated_Substring_Pattern.py), [Swift](https://tinyurl.com/wuja3c4/459_Repeated_Substring_Pattern.swift) | [Art 1](https://tinyurl.com/rrqo8rj) | Easy | I fucking love this problem | |29| **[681. Next Closest Time](https://tinyurl.com/rdz29j6)** | [Python](https://tinyurl.com/wu6rdaw/681_Next_Closest_Time.py), [Swift](https://tinyurl.com/wuja3c4/681_Next_Closest_Time.swift) | [Art 1](https://tinyurl.com/vupwnhw) | Medium | I feel stupid after trying my first solution | |30| **[925. Long Pressed Name](https://tinyurl.com/s4jbmmk)** | [Python](https://tinyurl.com/wu6rdaw/925_Long_Pressed_Name.py), [Swift](https://tinyurl.com/wuja3c4/925_Long_Pressed_Name.swift) | --- | Easy | | |31| **[949. Largest Time for Given Digits](https://tinyurl.com/ux8dk9e)** | [Python](https://tinyurl.com/wu6rdaw/949_Largest_Time_for_Given_Digits.py), [Swift](https://tinyurl.com/wuja3c4/949_Largest_Time_for_Given_Digits.swift) | --- | Easy | Not so easy | |32| [788. Rotated Digits](https://tinyurl.com/t9gelfm) | [Python](https://tinyurl.com/wu6rdaw/788_Rotated_Digits.py), [Swift](https://tinyurl.com/wuja3c4/788_Rotated_Digits.swift) | --- | Easy | --- | |33| [388. Longest Absolute File Path](https://tinyurl.com/svfa3rc) | [Python](https://tinyurl.com/wu6rdaw/388_Longest_Absolute_File_Path.py), [Swift](https://tinyurl.com/wuja3c4/388_Longest_Absolute_File_Path.swift) | --- | Medium | --- | |34| [616. Add Bold Tag in String](https://tinyurl.com/taftav2) | [Python](https://tinyurl.com/wu6rdaw/616_Add_Bold_Tag_in_String.py), [Swift](https://tinyurl.com/wuja3c4/616_Add_Bold_Tag_in_String.swift) | --- | Medium | Merge intervals(hidden) | |35| **[678. Valid Parenthesis String](https://tinyurl.com/y9a3g9kq)** | [Python](https://tinyurl.com/wu6rdaw/678_Valid_Parenthesis_String.py), [Swift](https://tinyurl.com/wuja3c4/678_Valid_Parenthesis_String.swift) | [Art 1](https://tinyurl.com/yad2akx6), [Art 2](https://tinyurl.com/y4odwzll), [Art 3](https://tinyurl.com/y7lkgfom), [Art 4](https://tinyurl.com/ycxpeyzn) | Medium | Super tricky. Much check again | |36| **[273. Integer to English Words](https://tinyurl.com/y7pps4u9)** | [Python](https://tinyurl.com/wu6rdaw/273_Integer_to_English_Words.py), [Swift](https://tinyurl.com/wuja3c4/273_Integer_to_English_Words.swift) | | Hard | MUST check again | |37| **[763. Partition Labels](https://tinyurl.com/yapt4n6v)** | [Python](https://tinyurl.com/wu6rdaw/763_Partition_Labels.py), [Swift](https://tinyurl.com/wuja3c4/763_Partition_Labels.swift) | | Medium | | |38| [819. Most Common Word](https://tinyurl.com/ydhwgc33) | [Python](https://tinyurl.com/wu6rdaw/819_Most_Common_Word.py), [Swift](https://tinyurl.com/wuja3c4/819_Most_Common_Word.swift) | [Art 1](https://tinyurl.com/y7u4pzeu) | Easy | | |39| [350. Intersection of Two Arrays II](https://tinyurl.com/y9kdrubz) | [Python](https://tinyurl.com/wu6rdaw/350_Intersection_of_Two_Arrays_II.py), [Swift](https://tinyurl.com/wuja3c4/350_Intersection_of_Two_Arrays_II.swift) | --- | Easy | Check the follow-ups | |40| **[249. Group Shifted Strings](https://tinyurl.com/jsfd4l3)** | [Python](https://tinyurl.com/wu6rdaw/249_Group_Shifted_Strings.py), [Swift](https://tinyurl.com/wuja3c4/249_Group_Shifted_Strings.swift) | [Art 1](https://tinyurl.com/yd4ckev2) | Medium | Tricky one | |41| **[158. Read N Characters Given Read4 II - Call multiple times](https://tinyurl.com/y6snjozr)** | [Python](https://tinyurl.com/wu6rdaw/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.py), [Swift](https://tinyurl.com/wuja3c4/158_Read_N_Characters_Given_Read4_II_Call_multiple_times.swift) | [Art 1](https://tinyurl.com/y5qu5dgz) | Hard | Good one | |42| [415. Add Strings](https://tinyurl.com/y7cbq62x) | [Python](https://tinyurl.com/wu6rdaw/415_Add_Strings.py), [Swift](https://tinyurl.com/wuja3c4/415_Add_Strings.swift) | [Art 1](https://tinyurl.com/y6v9uj9o) | Easy | --- | |43| **[65. Valid Number](https://tinyurl.com/yb6zsj3b)** | [Python](https://tinyurl.com/wu6rdaw/65_Valid_Number.py), [Swift](https://tinyurl.com/wuja3c4/65_Valid_Number.swift) | [Art 1](https://tinyurl.com/ycotov9v) | HARD | A fucking difficult but important problem. Chack DFA approach | |44| **[791. Custom Sort String](https://tinyurl.com/yag8mcfd)** | [Python](https://tinyurl.com/wu6rdaw/791_Custom_Sort_String.py), [Swift](https://tinyurl.com/wuja3c4/791_Custom_Sort_String.swift) | --- | Medium | Loved this problem | |45| **[157. Read N Characters Given Read4](https://tinyurl.com/y5g49nqt)** | [Python](https://tinyurl.com/wu6rdaw/157_Read_N_Characte_Given_Read4.py), [Swift](https://tinyurl.com/wuja3c4/157_Read_N_Characte_Given_Read4.swift) | --- | Easy (Not So!) | Loved this problem | |46| **[722. Remove Comments](https://tinyurl.com/y288v3lv)** | [Python](https://tinyurl.com/wu6rdaw/722_Remove_Comments.py), [Swift](https://tinyurl.com/wuja3c4/722_Remove_Comments.swift) | [Art 1](https://tinyurl.com/y56j4p76) | Medium | | |47| **[443. String Compression](https://tinyurl.com/ybll48vn)** | [Python](https://tinyurl.com/wu6rdaw/443_String_Compression.py), [Swift](https://tinyurl.com/wuja3c4/443_String_Compression.swift) | [Art 1](https://tinyurl.com/y5knbkcd) | Medium | | |48| **[1525_Number_of_Good_Ways_to_Split_a_String](https://tinyurl.com/yzree7us)** | [Swift](https://tinyurl.com/wuja3c4/1525_Number_of_Good_Ways_to_Split_a_String.swift) | --- | Medium | | |48| **[2007_Find_Original_Array_From_Doubled_Array](https://tinyurl.com/yhnzl82h)** | [Swift](https://tinyurl.com/wuja3c4/2007_Find_Original_Array_From_Doubled_Array.swift) | --- | Medium | | </p> </details> ### 3. [Linked List](https://leetcode.com/explore/learn/card/linked-list/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [2. Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)| [Python](https://tinyurl.com/wu6rdaw/2_Add_Two_Numbers.py), [Swift](https://tinyurl.com/wuja3c4/2_Add_Two_Numbers.swift)| --- | Medium | Fundamental | |02| [707. Design Linked List](https://leetcode.com/problems/design-linked-list/)| [Python](https://tinyurl.com/wu6rdaw/707_Design_Linked_List.py)| |03| [21. Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)| [Python](https://tinyurl.com/wu6rdaw/21_Merge_Two_Sorted_Lists.py)| [Algoexpert.io](https://tinyurl.com/r9azs3n), [Vid 1](https://tinyurl.com/t55smdg) | Easy | Fundamental and very very important | |04| [234. Palindrome Linked List](http://bit.ly/2PuZQAx)| [Python](https://tinyurl.com/wu6rdaw/234_Palindrome_Linked_List.py)| --- | Easy | Fast pointer Slow pointer | |05| [24. Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/)| [Python](https://tinyurl.com/wu6rdaw/24_Swap_Nodes_in_Pairs.py)| |06| [141. Linked List Cycle](https://tinyurl.com/u3vl5za)| [Python](https://tinyurl.com/wu6rdaw/141_Linked_List_Cycle.py)| --- | Easy | Fast pointer Slow pointer | |07| [142. Linked List Cycle II](https://tinyurl.com/svsaqk7)| [Python](https://tinyurl.com/wu6rdaw/142_Linked_List_Cycle_II.py)| [Art 1](https://tinyurl.com/us8ssdf), [Art 2](https://tinyurl.com/r5ztjpr), [AlgoExpert.io](https://tinyurl.com/r3rskyc) | Medium | Fast pointer Slow pointer | |08| [876. Middle of the Linked List](http://bit.ly/2YBAgOr)| [Python](https://tinyurl.com/wu6rdaw/876_Middle_of_the_Linked_List.py)| --- | Easy | Fast pointer Slow pointer | |09| [143. Reorder List](http://bit.ly/35861AZ)| [Python](https://tinyurl.com/wu6rdaw/143_Reorder_List.py)| --- | Medium | Fast pointer Slow pointer | |10| [19. Remove Nth Node From End of List](http://bit.ly/36gU1xo)| [Python](https://tinyurl.com/wu6rdaw/19_Remove_Nth_Node_From_End_of_List.py)| --- | Medium | Fast pointer Slow pointer | |11| [817. Linked List Components](https://tinyurl.com/trgps7z)| [Python](https://tinyurl.com/wu6rdaw/817_Linked_List_Components.py)| [Art 1](https://tinyurl.com/ql493bc) | Medium | Uses set/dictionary | |12| [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)| [Python](https://tinyurl.com/wu6rdaw/206_Reverse_Linked_List.py)| [Vid 1](https://www.youtube.com/watch?v=sYcOK51hl-A), [Vid 2](https://tinyurl.com/y3w3tek4) | Easy | Fundamental | |13| [92. Reverse Linked List II](https://tinyurl.com/h2kbl8k)| [Python](https://tinyurl.com/wu6rdaw/92_Reverse_Linked_List_II.py)| [educative.io](https://tinyurl.com/ql823xq), [Art 2](https://tinyurl.com/vdwhhv9) | Medium | Fundamental and very important | |14| [25. Reverse Nodes in k-Group](https://tinyurl.com/syg593o)| [Python](https://tinyurl.com/wu6rdaw/25_Reverse_Nodes_in_k-Group.py)| [educative.io](https://tinyurl.com/s7pns43q), [Art 1](https://tinyurl.com/rfumpm9), [Art 2](https://tinyurl.com/sqd5jsv) | Hard | Fundamental. TODO: Check again | |15| [24. Swap Nodes in Pairs](https://tinyurl.com/skymfxw)| [Python](https://tinyurl.com/wu6rdaw/24_Swap_Nodes_in_Pairs.py)| [educative.io](https://tinyurl.com/s7pns43q) | Medium | Fundamental | |16| [61. Rotate List](https://tinyurl.com/vnwzmxo)| [Python](https://tinyurl.com/wu6rdaw/61_Rotate_List.py)| [educative.io](https://tinyurl.com/rojgtv4) | Medium | Fundamental | |17| [328. Odd Even Linked List](https://tinyurl.com/qnjnarm)| [Python](https://tinyurl.com/wu6rdaw/328_Odd_Even_Linked_List.py)| [Art 1](https://tinyurl.com/r4f9y2s) | Medium | Fundamental | |18| [148. Sort List](https://tinyurl.com/rdlsc5c)| [Python](https://tinyurl.com/wu6rdaw/148_Sort_List.py)| [Vid 1](https://tinyurl.com/tgrrdzk), [Vid 2](https://tinyurl.com/tuhlf33), [Vid 3](https://tinyurl.com/w3xh8n3), [Art 1](https://tinyurl.com/uvsj8v3) | Medium | Fundamental | |19| **[23. Merge k Sorted Lists](https://tinyurl.com/u4dpc7r)** | [Python](https://tinyurl.com/wu6rdaw/23_Merge_k_Sorted_Lists.py)| **[educative.io](https://tinyurl.com/vaetc9d), [Art 1](https://tinyurl.com/rybqon6)** | Hard | Very important. TODO: Check heap approach | |20| [160. Intersection of Two Linked Lists](https://tinyurl.com/rz6nrop)| [Python](https://tinyurl.com/wu6rdaw/160_Intersection_of_Tw_Linked_Lists.py)| [Art 1](https://tinyurl.com/urrs7uy), [Art 2](https://tinyurl.com/wkya7ks) | Easy | --- | |21| **[138. Copy List with Random Pointer](https://tinyurl.com/uhaw95f)** | [Python](https://tinyurl.com/wu6rdaw/138_Copy_List_with_Random_Pointer.py)| **[Vid 1](https://tinyurl.com/reaqam9), [Art 1](https://tinyurl.com/tnwofvs)** | Medium | **TODO: Check again. Very important. Learned a lot of things** | |22| **[430. Flatten a Multilevel Doubly Linked List](https://tinyurl.com/sgpamoh)** | [Python](https://tinyurl.com/wu6rdaw/430_Flatten_a_Multilevel_Doubly_Linked_List.py)| [backtobackswe.com](https://tinyurl.com/y9mptlro), **[Vid 1](https://tinyurl.com/tbp99p2), [Art 1](https://tinyurl.com/un8p7f2)** | Medium | **TODO: Check again. Very important. Learned a lot of things** | |23| **[146. LRU Cache](https://tinyurl.com/zu2qbfl)** | [Python](https://tinyurl.com/wu6rdaw/146_LRU_Cache.py)| **[Vid 1](https://tinyurl.com/rtnhhys), [backtobackswe.com](https://tinyurl.com/vbpvjdc), [algoexpert.io](https://tinyurl.com/t2uhpgn)** | Hard | **TODO: Check again. Very important. Learned a lot of things** | |24| **[460. LFU Cache](https://tinyurl.com/yannrugv)** | [Python](https://tinyurl.com/wu6rdaw/460_LFU_Cache.py)| **[Vid 1](https://tinyurl.com/rtnhhys), [backtobackswe.com](https://tinyurl.com/vbpvjdc), [algoexpert.io](https://tinyurl.com/t2uhpgn)** | Hard | **TODO: Check again. Very important. Learned a lot of things** | |25| **[460. LFU Cache](https://tinyurl.com/y7qokgr8)** | [Python](https://tinyurl.com/wu6rdaw/237_Delete_Node_in_a_Linked_List.py)| [Art 1](https://tinyurl.com/rtnhhys) | Easy | | |26| **[708. Insert into a Sorted Circular Linked List](https://tinyurl.com/yy5ga9gn)** | [Python](https://tinyurl.com/wu6rdaw/708_Insert_into_a_Sorted_Circular_Linked_List.py), [Swift](https://tinyurl.com/wuja3c4/708_Insert_into_a_Sorted_Circular_Linked_List.swift) | [Art 1](https://tinyurl.com/y4p9krj8) | Medium | | |27| **[203. Remove Linked List Elements](https://tinyurl.com/y6bmycyr)** | [Python](https://tinyurl.com/wu6rdaw/203_Remove_Linked_List_Elements.py), [Swift](https://tinyurl.com/wuja3c4/203_Remove_Linked_List_Elements.swift) | --- | Easy | | |28| **[432. All O`one Data Structure](https://tinyurl.com/zqkzen4)** | [Python](https://tinyurl.com/wu6rdaw/432_All_O_one_Data_Structure.py), [Swift](https://tinyurl.com/wuja3c4/432_All_O_one_Data_Structure.swift) | [Art 1](https://tinyurl.com/y2ame7dc) | Hard | Super hard and super important | |29| **[426. Convert Binary Search Tree to Sorted Doubly Linked List](https://tinyurl.com/y5urjasp)** | [Python](https://tinyurl.com/wu6rdaw/426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.py), [Swift](https://tinyurl.com/wuja3c4/426_Convert_Binary_Search_Tree_to_Sorted_Doubly_Linked_List.swift) | [Art 1](https://tinyurl.com/yyq67lc7) | Medium | Super important | |30| **[1265. Print Immutable Linked List in Reverse](https://tinyurl.com/y5ksjt65)** | [Python](https://tinyurl.com/wu6rdaw/1265_Print_Immutable_Linked_List_in_Reverse.py), [Swift](https://tinyurl.com/wuja3c4/1265_Print_Immutable_Linked_List_in_Reverse.swift) | [Art 1](https://tinyurl.com/yxtb5wv4) | Medium | Really?? Are we supposed to solve a puzzle in an interview? | </p> </details> ### 4. [Stack, Queue](https://leetcode.com/explore/learn/card/queue-stack/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)| [Python](https://tinyurl.com/wu6rdaw/20_Valid_Parentheses.py)| |02| [155. Min Stack](https://leetcode.com/problems/min-stack/)| [Python](https://tinyurl.com/wu6rdaw/155_Min_Stack.py)| |03| [84. Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)| [Python](https://tinyurl.com/wu6rdaw/84_Largest_Rectangle_in_Histogram.py)| [Video 01](https://www.youtube.com/watch?v=VNbkzsnllsU), [Video 02](https://www.youtube.com/watch?v=RVIh0snn4Qc), [Article 01](https://leetcode.com/problems/largest-rectangle-in-histogram/solution/), [Article 02](https://leetcode.com/problems/largest-rectangle-in-histogram/discuss/28917/AC-Python-clean-solution-using-stack-76ms) | Hard | ๐Ÿ“Œ Need to revise | |04| [394. Decode String](https://leetcode.com/problems/decode-string/)| [Python](https://tinyurl.com/wu6rdaw/394_Decode_String.py)| --- | Medium | ๐Ÿ“Œ Classic stack problem | |05| **[239. Sliding Window Maximum](https://tinyurl.com/rvhujl5)** | [Python](https://tinyurl.com/wu6rdaw/239_Sliding_Window_Maximum.py)| **[Video 1](https://tinyurl.com/v767bl3)**, [Official](https://tinyurl.com/www4np2), [Art 1](https://tinyurl.com/y8nbroux), [Art 2](https://tinyurl.com/s62fzls), **[Art 3](https://tinyurl.com/vd3dtch)**, **[Art 4](https://tinyurl.com/yx3sjp46)** | Hard | ๐Ÿ“Œ Can be solved using Heap, Deque and DP | |06| [739. Daily Temperatures](https://tinyurl.com/ybbezzmt)| [Python](https://tinyurl.com/wu6rdaw/739_Daily_Temperatures.py)| **[Video 1](https://tinyurl.com/sdbkh3z)**, **[Video 2](https://tinyurl.com/rbvaozl)**, [Art 1](https://tinyurl.com/ss3d9tx) | Medium | ๐Ÿ“Œ TODO: Check again. A tricky one | |07| **[150. Evaluate Reverse Polish Notation](https://tinyurl.com/y2xrje8v)** | [Python](https://tinyurl.com/wu6rdaw/150_Evaluate_Reverse_Polish_Notation.py), [Swift](https://tinyurl.com/wuja3c4/150_Evaluate_Reverse_Polish_Notation.swift)| [Vid 1](https://tinyurl.com/s92fp4r) | Medium | --- | |08| **[341. Flatten Nested List Iterator](https://tinyurl.com/y6saxwjz)** | [Python](https://tinyurl.com/wu6rdaw/341_Flatten_Nested_List_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/341_Flatten_Nested_List_Iterator.swift)| [Vid 1](https://tinyurl.com/vkj4qll), [Art 1](https://tinyurl.com/wnvvafx), [Art 2](https://tinyurl.com/wmrlxmz), [Art 3](https://tinyurl.com/uplntb3), **[Art 4](https://tinyurl.com/v3q9qfw)**, **[Art 5](https://tinyurl.com/rotxca8)** | Medium | TODO: Check again. Very Important. Learned new things | |09| **[173. Binary Search Tree Iterator](https://tinyurl.com/wp2o8h2)** | [Python](https://tinyurl.com/wu6rdaw/173_Binary_Search_Tree_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/173_Binary_Search_Tree_Iterator.swift), [Swift](https://tinyurl.com/wuja3c4/173_Binary_Search_Tree_Iterator.swift)| [Vid 1](https://tinyurl.com/vb62v3q), **[Art 1](https://tinyurl.com/smu9ku3)** | Medium | TODO: Check again. Very Important. Learned new things | |10| **[284. Peeking Iterator](https://tinyurl.com/wp2o8h2)** | [Python](https://tinyurl.com/wu6rdaw/284_Peeking_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/284_Peeking_Iterator.swift)| **[Art 1](https://tinyurl.com/wv4ufcz)** | Medium | --- | |11| **[281. Zigzag Iterator](https://tinyurl.com/rxgn345)** | [Python](https://tinyurl.com/wu6rdaw/281_Zigzag_Iterator.py), [Swift](https://tinyurl.com/wuja3c4/281_Zigzag_Iterator.swift)| **[Art 1](https://tinyurl.com/wv4ufcz)** | Medium | --- | |12| **[946. Validate Stack Sequences](https://tinyurl.com/u8wbaqp)** | [Python](https://tinyurl.com/wu6rdaw/946_Validate_Stack_Sequences.py), [Swift](https://tinyurl.com/wuja3c4/946_Validate_Stack_Sequences.swift)| **[Art 1](https://tinyurl.com/um2r3bf)**, **[Art 2](https://tinyurl.com/vc5wmlj)** | Medium | --- | |13| **[862. Shortest Subarray with Sum at Least K](https://tinyurl.com/wzdraag)** | [Python](https://tinyurl.com/wu6rdaw/862_Shortest_Subarray_with_Sum_at_Least_K.py), [Swift](https://tinyurl.com/wuja3c4/862_Shortest_Subarray_with_Sum_at_Least_K.swift)| **[Art 1](https://tinyurl.com/rn7rsnf)**, **[Art 2](https://tinyurl.com/ra3ttcg)**, **[Art 3](https://tinyurl.com/swqs6cq)**, **[Art 4](https://tinyurl.com/t8tjjk2)** | Hard | Learned Monotonic Queue. Very interesting problem | |14| [346. Moving Average from Data Stream](https://tinyurl.com/sfmwtr5) | [Python](https://tinyurl.com/wu6rdaw/346_Moving_Average_from_Data_Stream.py), [Swift](https://tinyurl.com/wuja3c4/346_Moving_Average_from_Data_Stream.swift)| | Easy | | |15| **[71. Simplify Path](https://tinyurl.com/y9eqaxkh)** | [Python](https://tinyurl.com/wu6rdaw/71_Simplify_Path.py), [Swift](https://tinyurl.com/wuja3c4/71_Simplify_Path.swift)| | Medium | | |16| **[1249. Minimum Remove to Make Valid Parentheses](https://tinyurl.com/y73258qd)** | [Python](https://tinyurl.com/wu6rdaw/1249_Minimum_Remove_to_Make_Valid_Parentheses.py), [Swift](https://tinyurl.com/wuja3c4/1249_Minimum_Remove_to_Make_Valid_Parentheses.swift)| [Official](https://tinyurl.com/ycku9nbn) | Medium | Must check | |17| **[636. Exclusive Time of Functions](https://tinyurl.com/y7fkfomp)** | [Python](https://tinyurl.com/wu6rdaw/636_Exclusive_Time_of_Functions.py), [Swift](https://tinyurl.com/wuja3c4/636_Exclusive_Time_of_Functions.swift)| [Art 1](https://tinyurl.com/yd5rtdkl) | Medium | Must check | |18| **[921. Minimum Add to Make Parentheses Valid](https://tinyurl.com/wjv6txp)** | [Python](https://tinyurl.com/wu6rdaw/921_Minimum_Add_to_Make_Parentheses_Valid.py), [Swift](https://tinyurl.com/wuja3c4/921_Minimum_Add_to_Make_Parentheses_Valid.swift)| --- | Medium | --- | |19| **[1209. Remove All Adjacent Duplicates in String II](https://tinyurl.com/y3e4gsgv)** | [Python](https://tinyurl.com/wu6rdaw/1209_Remove_All_Adjacent_Duplicates_in_String_II.py), [Swift](https://tinyurl.com/wuja3c4/1209_Remove_All_Adjacent_Duplicates_in_String_II.swift)| --- | Medium | --- | |20| **[227. Basic Calculator II](https://tinyurl.com/y5g4u5by)** | [Python](https://tinyurl.com/wu6rdaw/227_Basic_Calculator_II.py), [Swift](https://tinyurl.com/wuja3c4/227_Basic_Calculator_II.swift)| [Art 1](https://tinyurl.com/y3dnn3zl) | Medium | --- | |21| **[735. Asteroid Collision](https://tinyurl.com/y2dvawxw)** | [Swift](https://tinyurl.com/wuja3c4/735_Asteroid_Collision.swift)| [Vid 1](https://tinyurl.com/yf8s4ok7), [Art 1](https://tinyurl.com/yzkbhhh6), [Art 1](https://tinyurl.com/yja9dyz4) | Medium | --- | </p> </details> ### 5. [Heaps](https://www.youtube.com/watch?v=HqPJF2L5h9U) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| **[358. Rearrange String k Distance Apart](https://tinyurl.com/rb5nvc9)** | [Python](https://tinyurl.com/wu6rdaw/358_Rearrange_String_k_Distance_Apart.py)| [Educative.io](https://tinyurl.com/yx3b8y2s), [Educative.io 2](https://tinyurl.com/saw9w7x) | Hard | ๐Ÿ“Œ Similar to [621. Task Scheduler](https://leetcode.com/problems/task-scheduler/). Very Important. TODO: Check Heap approach | |02| [347. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/solution/)| [Python](https://tinyurl.com/wu6rdaw/347_Top_K_Frequent_Elements.py)| [educative.io](https://tinyurl.com/r3by7v6), [Helper 1](https://stackoverflow.com/questions/19979518/what-is-pythons-heapq-module), [Helper 2](https://stackoverflow.com/a/12373856/2089253), [heapq](https://docs.python.org/3.0/library/heapq.html), [Counter](https://docs.python.org/3/library/collections.html#collections.Counter) | Medium | --- | |03| [767. Reorganize String](https://leetcode.com/problems/reorganize-string/)| [Python](https://tinyurl.com/wu6rdaw/767_Reorganize_String.py)| --- | Medium | Also check Greedy approach | |04| **[621. Task Scheduler](https://tinyurl.com/vumg8r8)** | [Python](https://tinyurl.com/wu6rdaw/621_Task_Scheduler.py), [Swift](https://tinyurl.com/wuja3c4/621_Task_Scheduler.swift)| [Ex 1](https://tinyurl.com/y6x6jrz4), [Ex 2](https://tinyurl.com/rmlstk3), [Vid 1](https://www.youtube.com/watch?v=hVhOeaONg1Y), [Vid 2](https://www.youtube.com/watch?v=zPtI8q9gvX8), [Vid 3](https://www.youtube.com/watch?v=TV9VlHUR-Is), [Vid 4](https://www.youtube.com/watch?v=cr6Ip0J9izc&t=22s) | Medium | ๐Ÿ“Œ Extremely tricky. Classic problem | |05| **[295. Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)**| [Python](https://tinyurl.com/wu6rdaw/295_Find_Median_from_Data_Stream.py)| **[algoexpert.io](https://tinyurl.com/vwuybol), [educative.io](https://tinyurl.com/tlorqup), [educative.io 2](https://tinyurl.com/v5sxd8y), [codinginterviewclass.com](https://tinyurl.com/yxy2r3qq), [Official](https://tinyurl.com/vrx3xqv), [FollowUp 1](https://tinyurl.com/s7q75zr)** | Hard | ๐Ÿ“Œ **Very Tricky and important. TODO: Check again** | |06| **[480. Sliding Window Median](https://leetcode.com/problems/sliding-window-median/)** | [Python](https://tinyurl.com/wu6rdaw/480_Sliding_Window_Median.py)| [educative.io](https://tinyurl.com/rp96568), [Vid 1](https://tinyurl.com/uz66xbf) | Hard | ๐Ÿ“Œ Sliding window with 2 heap. very important | |07| **[4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)** | [Python](https://tinyurl.com/wu6rdaw/4_Median_of_Two_Sorted_Arrays.py)| [Article 01](https://tinyurl.com/wn5w5j2), [Art 2](https://tinyurl.com/qm3fbbu) [Video 1](https://www.youtube.com/watch?v=LPFhl65R7ww)| Hard | ๐Ÿ“Œ Classic problem | |08| [215. Kth Largest Element in an Array](https://tinyurl.com/y6cjzgbv) | [Python](https://tinyurl.com/wu6rdaw/215_Kth_Largest_Element_in_an_Array.py)| [Art 01](https://tinyurl.com/svnozo2), [Algoexpert.io](https://tinyurl.com/rjzx5hw), [educative.io](https://tinyurl.com/r34urrx)| Medium | ๐Ÿ“Œ Also check Quickselect method. | |09| **[373. Find K Pairs with Smallest Sums](https://tinyurl.com/w9succr)** | [Python](https://tinyurl.com/wu6rdaw/373_Find_K_Pairs_with_Smallest_Sums.py)| [educative.io](https://tinyurl.com/r8ovn6v) | Hard | ๐Ÿ“Œ TODO: Check again. | |10| [973. K Closest Points to Origin](https://tinyurl.com/t4d3ge7) | [Python](https://tinyurl.com/wu6rdaw/973_K_Closest_Points_to_Origin.py)| [Algoexpert.io](https://tinyurl.com/rjzx5hw), [educative.io](https://tinyurl.com/vppeh5y), [Vid 1](https://tinyurl.com/wey8mub) | Medium | ๐Ÿ“Œ Also check Quickselect and heap method | |11| [451. Sort Characters By Frequency](https://tinyurl.com/y8x876bf) | [Python](https://tinyurl.com/wu6rdaw/451_Sort_Characters_By_Frequency.py)| [Algoexpert.io](https://tinyurl.com/rjzx5hw), [educative.io](https://tinyurl.com/vtk3de8) | Medium | ๐Ÿ“Œ Also check Quickselect and heap method | |12| [692. Top K Frequent Words](https://tinyurl.com/yx69p89s) | [Python](https://tinyurl.com/wu6rdaw/692_Top_K_Frequent_Words.py)| [Algoexpert.io](https://tinyurl.com/rjzx5hw), [educative.io](https://tinyurl.com/vtk3de8) | Medium | ๐Ÿ“Œ Also check Quickselect and heap method | |13| [703. Kth Largest Element in a Stream](https://tinyurl.com/wqrgost) | [Python](https://tinyurl.com/wu6rdaw/703_Kth_Largest_Element_in_a_Stream.py)| [educative.io](https://tinyurl.com/uajjww8) | Medium | ๐Ÿ“Œ --- | |14| [895. Maximum Frequency Stack](https://tinyurl.com/szdk34w) | [Python](https://tinyurl.com/wu6rdaw/895_Maximum_Frequency_Stack.py)| [educative.io](https://tinyurl.com/w5cd6yh), [Art 1](https://tinyurl.com/y94jodcf) | Hard | ๐Ÿ“Œ TODO: Check again | |15| **[378. Kth Smallest Element in a Sorted Matrix](https://tinyurl.com/shz4289)** | [Python](https://tinyurl.com/wu6rdaw/378_Kth_Smallest_Element_in_a_Sorted_Matrix.py)| [educative.io](https://tinyurl.com/scbjgjd) | Hard | ๐Ÿ“Œ TODO: Check again the Binary Search approach. Very important | |16| **[632. Smallest Range Covering Elements from K Lists](https://tinyurl.com/v3fshwo)** | [Python](https://tinyurl.com/wu6rdaw/632_Smallest_Range_Covering_Elements_from_K_Lists.py)| [educative.io](https://tinyurl.com/ubfua7f) | Hard | ๐Ÿ“Œ TODO: Check again. Very important | |17| **[846. Hand of Straights](https://tinyurl.com/y2hfqqsv)** | [Python](https://tinyurl.com/wu6rdaw/846_Hand_of_Straights.py)| **[Art 1](https://tinyurl.com/w8pkf55)** | Medium | ๐Ÿ“Œ TODO: Check again. Very important | |18| **[1167. Minimum Cost to Connect Sticks](https://tinyurl.com/y8s5s8pq)** | [Python](https://tinyurl.com/wu6rdaw/1167_Minimum_Cost_to_Connect_Sticks.py)| [Art 1](https://tinyurl.com/ycedphuh) | Medium | | |19| **[1102. Path With Maximum Minimum Value](https://tinyurl.com/y7zqxqpq)** | [Python](https://tinyurl.com/wu6rdaw/1102_Path_With_Maximum_Minimum_Value.py)| [Art 1](https://tinyurl.com/yb7p48lk), [Art 2](https://tinyurl.com/ya34o3z2), [Art 3](https://tinyurl.com/y99bhurp) | Medium | Dijekstra | |20| **[1834. Single-Threaded CPU](https://tinyurl.com/yk66fo4v)** | [Swift](https://tinyurl.com/wuja3c4/1834_Single_Threaded_CPU.swift) | [Art 1](https://tinyurl.com/yjbn9uzs) | Medium | --- | </p> </details> ### 6. [Binary Search](https://leetcode.com/explore/learn/card/binary-search/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [704. Binary Search](https://leetcode.com/problems/binary-search/)| [Python](https://tinyurl.com/wu6rdaw/704_Binary_Search.py)| --- | Easy | Basics | |03| [240. Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/solution/)| [Python](https://tinyurl.com/wu6rdaw/240_Search_a_2D_Matrix_II.py)| [Video 01](https://www.youtube.com/watch?v=FOa55B9Ikfg), [Video 02](https://www.youtube.com/watch?v=DHSyS72BvOQ)| |04| [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)| [Python](https://tinyurl.com/wu6rdaw/74_Search_a_2D_Matrix.py)| [Video 01](https://www.youtube.com/watch?v=FOa55B9Ikfg), [Video 02](https://www.youtube.com/watch?v=DHSyS72BvOQ)| |05| [1011. Capacity To Ship Packages Within D Days](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)| [Python](https://tinyurl.com/wu6rdaw/1011_Capacity_To_Ship_Packages_Within_D_Days.py)| [Discussion 1](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/346505/Binary-classification-Python.-Detailed-explanation-Turtle-Code), [Discussion 2](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/256765/Python-Binary-search-with-detailed-explanation), [Discussion 3](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/256729/JavaC++Python-Binary-Search/306543) | Medium | Difficult to spot the pattern, revise again | |06| **[410. Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/)** | [Python](https://tinyurl.com/wu6rdaw/410_Split_Array_Largest_Sum.py)| [Vid 1](https://tinyurl.com/s3j99m4), [Art 1](https://tinyurl.com/vf43ly3), [Art 2](https://tinyurl.com/t8szkym) | Hard | ๐Ÿ“Œ TODO: Check again. It's a fucking difficult and interesting and important | |07| **[4. Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)** | [Python](https://tinyurl.com/wu6rdaw/4_Median_of_Two_Sorted_Arrays.py)| [Article 01](https://tinyurl.com/wn5w5j2), [Art 2](https://tinyurl.com/qm3fbbu) [Video 1](https://www.youtube.com/watch?v=LPFhl65R7ww)| Hard | ๐Ÿ“Œ Classic problem | |08| [981. Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/)| [Python](https://tinyurl.com/wu6rdaw/981_Time_Based_Key-Value_Store.py)| [Article 01](https://leetcode.com/problems/time-based-key-value-store/solution/)| Medium | ๐Ÿ“Œ | |09| [**222. Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)**| [Python](https://tinyurl.com/wu6rdaw/222_Count_Complete_Tree_Nodes.py), [Swift](https://tinyurl.com/wuja3c4/222_Count_Complete_Tree_Nodes.swift)| [Theory](http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/9-BinTree/bin-tree.html), [Official Solution](https://leetcode.com/problems/count-complete-tree-nodes/solution/), [Fantastic idea!](https://tinyurl.com/y5s43jtt) | Medium | ๐Ÿ“Œ BS within BS | |10| [1231. Divide Chocolate](https://leetcode.com/problems/divide-chocolate/)| [Python](https://tinyurl.com/wu6rdaw/1231_Divide_Chocolate.py)| [Art 1](https://tinyurl.com/sl7w7cb), [Art 2](https://tinyurl.com/vabdbzo), [Art 3](https://tinyurl.com/v4cablt), [Vid 1](https://www.youtube.com/watch?v=vq2OXjXQPYw&feature=emb_title) | Hard | ๐Ÿ“Œ **Not done. Check again. Solve all similar question** | |11| [69. Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [Python](https://tinyurl.com/wu6rdaw/69_Sqrt(x).py)| --- | Easy | ๐Ÿ“Œ [Binary Search Template I](https://leetcode.com/explore/learn/card/binary-search/125/template-i/938/) | |12| [374. Guess Number Higher or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/)| [Python](https://tinyurl.com/wu6rdaw/374_Guess_Number_Higher_or_Lower.py)| --- | Easy | ๐Ÿ“Œ [Binary Search Template I](https://leetcode.com/explore/learn/card/binary-search/125/template-i/938/) | |13| **[33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)** | [Python](https://tinyurl.com/wu6rdaw/33_Search_in_Rotated_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/33_Search_in_Rotated_Sorted_Array.swift) | [Educative.io](https://tinyurl.com/ufcqj97) | Medium | ๐Ÿ“Œ **[Binary Search Template I](https://leetcode.com/explore/learn/card/binary-search/125/template-i/938/), Very important**| |14| [81. Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| [Python](https://tinyurl.com/wu6rdaw/81_Search_in_Rotated_Sorted_Array_II.py)| --- | Medium | ๐Ÿ“Œ **[Binary Search Template I](https://leetcode.com/explore/learn/card/binary-search/125/template-i/938/), very important**| |15| [278. First Bad Version](https://leetcode.com/problems/first-bad-version/)| [Python](https://tinyurl.com/wu6rdaw/278_First_Bad_Version.py)| --- | Easy | ๐Ÿ“Œ **[Binary Search Template II](https://tinyurl.com/t6v6et3)**| |16| [162. Find Peak Element](https://leetcode.com/problems/find-peak-element/)| [Python](https://tinyurl.com/wu6rdaw/162_Find_Peak_Element.py)| --- | Medium | ๐Ÿ“Œ **[Binary Search Template II](https://tinyurl.com/t6v6et3)**| |17| **[153. Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)** | [Python](https://tinyurl.com/wu6rdaw/153_Find_Minimum_in_Rotated_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/153_Find_Minimum_in_Rotated_Sorted_Array.swift)| --- | Medium | ๐Ÿ“Œ **[Binary Search Template II](https://tinyurl.com/t6v6et3)**| |18| [154. Find Minimum in Rotated Sorted Array II](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| [Python](https://tinyurl.com/wu6rdaw/154_Find_Minimum_in_Rotated_Sorted_Array_II.py)| --- | Hard | ๐Ÿ“Œ **[Binary Search Template II](https://tinyurl.com/t6v6et3), not done**| |19| [34. Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)| [Python](https://tinyurl.com/wu6rdaw/34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.swift) | [Vid 1](https://tinyurl.com/wa2zqff), [Educative.io](https://tinyurl.com/s4hvqqz) | Medium | ๐Ÿ“Œ **[Binary Search Template III](https://tinyurl.com/vpsn3w8)**| |20| [658. Find K Closest Elements](https://tinyurl.com/rkpkjfo)| [Python](https://tinyurl.com/wu6rdaw/658_Find_K_Closest_Elements.py)| [Vid 1](https://tinyurl.com/w5ccjoe), [educative.io](https://tinyurl.com/uogulbz) | Medium | ๐Ÿ“Œ **[Binary Search Template III](https://tinyurl.com/vpsn3w8)**. TODO: Check Heap approach which is not done| |21| [702. Search in a Sorted Array of Unknown Size](https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/)| [Python](https://tinyurl.com/wu6rdaw/702_Search_in_a_Sorted_Array_of_Unknown_Size.py)| [Educative.io](https://tinyurl.com/qn6uuel) | Medium | ๐Ÿ“Œ [Binary Search Template I](https://leetcode.com/explore/learn/card/binary-search/125/template-i/938/) | |22| **[378. Kth Smallest Element in a Sorted Matrix](https://tinyurl.com/shz4289)** | [Python](https://tinyurl.com/wu6rdaw/378_Kth_Smallest_Element_in_a_Sorted_Matrix.py)| [educative.io](https://tinyurl.com/scbjgjd) | Hard | ๐Ÿ“Œ TODO: Check again the Binary Search approach. Very important | |23| **[1146. Snapshot Array](https://tinyurl.com/v3nb29v)** | [Python](https://tinyurl.com/wu6rdaw/1146_Snapshot_Array.py)| [Art 1](https://tinyurl.com/v3nb29v) | Medium | Tricky use of binary search | |24| **[1170. Compare Strings by Frequency of the Smallest Character](https://tinyurl.com/tcr34w3)** | [Python](https://tinyurl.com/wu6rdaw/1170_Compare_Strings_by_Frequency_of_the_Smallest_Character.py)| --- | Easy | Binary Search, Very important | |25| [852. Peak Index in a Mountain Array](https://tinyurl.com/rh5c4hs) | [Python](https://tinyurl.com/wu6rdaw/852_Peak_Index_in_a_Mountain_Array.py), [Swift](https://tinyurl.com/wuja3c4/852_Peak_Index_in_a_Mountain_Array.swift) | --- | Easy | --- | |25| **[209. Minimum Size Subarray Sum](https://tinyurl.com/wy5g8c4)** | [Python](https://tinyurl.com/wu6rdaw/209_Minimum_Size_Subarray_Sum.py), [Swift](https://tinyurl.com/wuja3c4/209_Minimum_Size_Subarray_Sum.swift) | --- | Medium | Sliding window and Binary Search | |26| **[363. Max Sum of Rectangle No Larger Than K](https://tinyurl.com/wxc73z6)** | [Python](https://tinyurl.com/wu6rdaw/363_Max_Sum_of_Rectangle_No_Larger_Than_K.py), [Swift](https://tinyurl.com/wuja3c4/363_Max_Sum_of_Rectangle_No_Larger_Than_K.swift) | [Vid 1](https://tinyurl.com/rq5sgfp), [Vid 2](https://tinyurl.com/wtyob94), [Art 1](https://tinyurl.com/vtj3d2d), [Art 2](https://tinyurl.com/w29ebes), [Art 3](https://tinyurl.com/yxx4yzvn) | Hard | DP and BS. Disn't understand S part. TODO: Check again | |27| **[875. Koko Eating Bananas](https://tinyurl.com/wjygtev)** | [Python](https://tinyurl.com/wu6rdaw/875_Koko_Eatin_Bananas.py), [Swift](https://tinyurl.com/wuja3c4/875_Koko_Eatin_Bananas.swift) | --- | Medium | I loved this problem | |28| **[1060. Missing Element in Sorted Array](https://tinyurl.com/t3z7cav)** | [Python](https://tinyurl.com/wu6rdaw/1060_Missing_Element_in_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/1060_Missing_Element_in_Sorted_Array.swift) | --- | Medium | I loved this problem | |29| **[1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold](https://tinyurl.com/uahn37k)** | [Python](https://tinyurl.com/wu6rdaw/1292_Maximum_Side_Length_of_a_Square_with_Sum_Less_than_or_Equal_to_Threshold.py), [Swift](https://tinyurl.com/wuja3c4/1292_Maximum_Side_Length_of_a_Square_with_Sum_Less_than_or_Equal_to_Threshold.swift) | [Art 1](https://tinyurl.com/t9zgbkn) | Medium | I loved this problem. Sliding window and Binary Search | |30| **[774. Minimize Max Distance to Gas Station](https://tinyurl.com/w2hznvj)** | [Python](https://tinyurl.com/wu6rdaw/774_Minimize_Max_Distance_to_Gas_Station.py), [Swift](https://tinyurl.com/wuja3c4/774_Minimize_Max_Distance_to_Gas_Station.swift) | [Vid 1](https://tinyurl.com/tjmrjgq), [Art 1](https://tinyurl.com/teqxwh8), [Art 2](https://tinyurl.com/szc6bjw), [Art 1](https://tinyurl.com/sfc5d2j) | Hard | I loved this problem. Very important | |31| **[1231. Divide Chocolate](https://tinyurl.com/rduxzj3)** | [Python](https://tinyurl.com/wu6rdaw/1231_Divide_Chocolate.py), [Swift](https://tinyurl.com/wuja3c4/1231_Divide_Chocolate.swift) | [Art 1](https://tinyurl.com/sl7w7cb), [Art 2](https://tinyurl.com/w9wbcyl), [Art 3](https://tinyurl.com/te6wq5e) | Hard | I loved this problem. Very important | |32| **[1268. Search Suggestions System](https://tinyurl.com/ybwcd5nx)** | [Python](https://tinyurl.com/wu6rdaw/1268_Search_Suggestions_System.py), [Swift](https://tinyurl.com/wuja3c4/1268_Search_Suggestions_System.swift) | [Art 1](https://tinyurl.com/yac3kvrp), [Art 2](https://tinyurl.com/y9u3g66q), [Art 3](https://tinyurl.com/yc2u3mrx) | Medium | I loved this problem. Very versatile, ca be solved in a lot of different ways | |33| **[540. Single Element in a Sorted Array](https://tinyurl.com/y78xdorh)** | [Python](https://tinyurl.com/wu6rdaw/540_Single_Element_in_a_Sorted_Array.py), [Swift](https://tinyurl.com/wuja3c4/1268_Search_Suggestions_System.swift) | | Medium | --- | |34| **[441. Arranging Coins](https://tinyurl.com/yaj6labj)** | [Python](https://tinyurl.com/wu6rdaw/441_Arranging_Coins.py), [Swift](https://tinyurl.com/wuja3c4/441_Arranging_Coins.swift) | | Easy | --- | |35| **[154. Find Minimum in Rotated Sorted Array II](https://tinyurl.com/y2tx3mow)** | [Python](https://tinyurl.com/wu6rdaw/154_Find_Minimum_in_Rotated_Sorted_Array_II.py), [Swift](https://tinyurl.com/wuja3c4/154_Find_Minimum_in_Rotated_Sorted_Array_II.swift) | [Art 1](https://tinyurl.com/y5on59nn) | Medium | **VERY IMPORTANT** | </p> </details> ### 7. [Binary Tree](https://leetcode.com/explore/learn/card/data-structure-tree/) [Binary Tree Bootcamp](https://tinyurl.com/ut5oglh) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> Check this [golden](https://tinyurl.com/ujopecz) post. | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [226. Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/solution/)| [Python](https://tinyurl.com/wu6rdaw/226_Invert_Binary_Tree.py)| |02| [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/)| [Python](https://tinyurl.com/wu6rdaw/101_Symmetric_Tree.py)| |03| [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/solution/)| [Python](https://tinyurl.com/wu6rdaw/102_Binary_Tree_Level_Order_Traversal.py)| |04| [107. Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)| [Python](https://tinyurl.com/wu6rdaw/107_Binary_Tree_Level_Order_Traversal_II.py)| |05| [103. Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| [Python](https://tinyurl.com/wu6rdaw/103_Binary_Tree_Zigzag_Level_Order_Traversal.py)| |06| [104. Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| [Python](https://tinyurl.com/wu6rdaw/104_Maximum_Depth_of_Binary_Tree.py)| [Explanation](https://leetcode.com/explore/learn/card/data-structure-tree/17/solve-problems-recursively/534/) | |07| [100. Same Tree](https://leetcode.com/problems/same-tree/)| [Python](https://tinyurl.com/wu6rdaw/100_Same_Tree.py)| | |08| [111. Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree/)| [Python](https://tinyurl.com/wu6rdaw/111_Minimum_Depth_of_Binary_Tree.py)| | Easy | --- | |09| [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)| [Python](https://tinyurl.com/wu6rdaw/110_Balanced_Binary_Tree.py)| [Video 1](https://www.youtube.com/watch?v=LU4fGD-fgJQ), [Article 1](https://leetcode.com/problems/balanced-binary-tree/discuss/36042/Two-different-definitions-of-balanced-binary-tree-result-in-two-different-judgments), [Article 2](https://leetcode.com/problems/balanced-binary-tree/discuss/35708/VERY-SIMPLE-Python-solutions-(iterative-and-recursive)-both-beat-90) | Easy | --- | |10| [105. Construct Binary Tree from Preorder and Inorder Traversal](https://tinyurl.com/y4s62xbu)| [Python](https://tinyurl.com/wu6rdaw/105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py)| [Art 1](https://tinyurl.com/y3megvpm), [Art 2](https://tinyurl.com/tazaoyz), [Vid 1](https://tinyurl.com/qoqdsqv) | Medium | DFS, Very Important | |11| [106. Construct Binary Tree from Inorder and Postorder Traversal](https://tinyurl.com/yx78og6g)| [Python](https://tinyurl.com/wu6rdaw/106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.swift) | [Art 1](https://tinyurl.com/vlntqrp) | Medium | DFS, Very Important | |12| **[889. Construct Binary Tree from Preorder and Postorder Traversal](https://tinyurl.com/y578ty5u)** | [Python](https://tinyurl.com/wu6rdaw/889_Construct_Binary_Tree_from_Preorder_and_Postorder_Traversal.py)| [Vid 1](https://tinyurl.com/r6d4ym5), **[Art 1](https://tinyurl.com/tflqhp9)**, [Art 2](https://tinyurl.com/wkq7qyu) | Medium | ๐Ÿ“Œ **TODO: Check again. Important** | |13| **[124. Binary Tree Maximum Path Sum](https://tinyurl.com/yycvxmmy)**| [Python](https://tinyurl.com/wu6rdaw/124_Binary_Tree_Maximum_Path_Sum.py), [Swift](https://tinyurl.com/wuja3c4/124_Binary_Tree_Maximum_Path_Sum.swift) | [Art 1](https://tinyurl.com/uocr9np), [Art 2](https://tinyurl.com/s23sqhe), [Vid 1](https://tinyurl.com/wwe95qx), [AlgoExpert](https://tinyurl.com/vofbonm) | Very Hard | **Very important and tricky** | |14| **[979. Distribute Coins in Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/)**| [Python](https://tinyurl.com/wu6rdaw/979_Distribute_Coins_in_Binary_Tree.py)| [Art 1](https://tinyurl.com/rugoa38), [Art 2](https://tinyurl.com/whkdbl4), [Art 3](https://tinyurl.com/s62fws7) | Medium | **Very important. Postorder DFS** | |15| [116. Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| [Python](https://tinyurl.com/wu6rdaw/116_Populating_Next_Right_Pointers_in_Each_Node.py)| [Art 1](https://tinyurl.com/t6p8kjb), [Art 2](https://tinyurl.com/ujzrhkj), **[Art 3](https://tinyurl.com/unrow77)** | Medium | BFS/DFS, Level order traversal | |16| [117. Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| [Python](https://tinyurl.com/wu6rdaw/117_Populating_Next_Right_Pointers_in_Each_Node_II.py)| [Vid 1](https://tinyurl.com/rfjhzj3), [Vid 2](https://tinyurl.com/ryghj42) | Medium | **Very tricky, check again** | |17| [199. Binary Tree Right Side View](https://tinyurl.com/y65vxqj2)| [Python](https://tinyurl.com/wu6rdaw/199_Binary_Tree_Right_Side_View.py), [Swift](https://tinyurl.com/wuja3c4/199_Binary_Tree_Right_Side_View.swift) | --- | Medium | --- | |18| **[863. All Nodes Distance K in Binary Tree](https://tinyurl.com/w5dmj3o)**| [Python](https://tinyurl.com/wu6rdaw/863_All_Nodes_Distance_K_in_Binary_Tree.py)| [Vid 1](https://tinyurl.com/tn4ncqy), [Art 1](https://tinyurl.com/t3ozct3), [Art 2](https://tinyurl.com/rvbhznn) | Medium | A combination of graph and tree. TODO: Check again. Very important | |19| [301. Remove Invalid Parentheses](https://tinyurl.com/w9lfsgt) | [Python](https://tinyurl.com/wu6rdaw/301_Remove_Invalid_Parentheses.py)| [Vid 1](https://tinyurl.com/rbp6xa7), [Vid 2](https://tinyurl.com/sjk44du), [Art 1](https://tinyurl.com/tcglxfp) | Hard | TODO: Not done, Check again. Very important. BFS and DFS | |20| [112. Path Sum](https://tinyurl.com/rg6m7ua) | [Python](https://tinyurl.com/wu6rdaw/112_Path_Sum.py)| [Art 1](https://tinyurl.com/t2dggse) | Easy | --- | |21| [113. Path Sum II](https://tinyurl.com/qm9gc2v) | [Python](https://tinyurl.com/wu6rdaw/113_Path_Sum_II.py)| [Art 1](https://tinyurl.com/rynd6fy), [Art 2](https://tinyurl.com/tn2o75s) | Medium | --- | |22| [437. Path Sum III](https://tinyurl.com/ug978np) | [Python](https://tinyurl.com/wu6rdaw/437_Path_Sum_III.py)| [Educative.io](https://tinyurl.com/vyhpcu2), [Art 1](https://tinyurl.com/w6yjxaz), **[Art 2](https://tinyurl.com/wkxjmqv)** | Medium | ๐Ÿ“Œ A good example of Prefix Sum and DFS. Very Important | |23| [543. Diameter of Binary Tree](https://tinyurl.com/womnj8m) | [Python](https://tinyurl.com/wu6rdaw/543_Diameter_of_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/543_Diameter_of_Binary_Tree.swift.swift) | [Educative.io](https://tinyurl.com/w6rrucg), [Art 1](https://tinyurl.com/vfnvg8q) | Medium | ๐Ÿ“Œ Important | |24| **[1110. Delete Nodes And Return Forest](https://tinyurl.com/rg8qomj)** | [Python](https://tinyurl.com/wu6rdaw/1110_Delete_Nodes_And_Return_Forest.py)| [Vid 1](https://tinyurl.com/t9rax3x), [Vid 2](https://tinyurl.com/uw6y3zk), [Art 1](https://tinyurl.com/ujopecz), [Art 2](https://tinyurl.com/tppglsu) | Medium | ๐Ÿ“Œ **TODO: Check again. Important | |25| [257. Binary Tree Paths](https://leetcode.com/problems/binary-tree-paths/)| [Python](https://tinyurl.com/wu6rdaw/257_Binary_Tree_Paths.py)| --- | Easy | DFS | |26| **[1145. Binary Tree Coloring Game](https://tinyurl.com/uukf2nm)**| [Python](https://tinyurl.com/wu6rdaw/1145_Binary_Tree_Coloring_Game.py)| [Art 1](https://tinyurl.com/v4k7jaj), [Art 2](https://tinyurl.com/rvwsjar) | Medium | DFS | |27| **[298. Binary Tree Longest Consecutive Sequence](https://tinyurl.com/rw2sqxr)**| [Python](https://tinyurl.com/wu6rdaw/298_Binary_Tree_Longest_Consecutive_Sequence.py)| **[Art 1](https://tinyurl.com/wmlq6md)** | Medium | DFS | |28| **[951. Flip Equivalent Binary Trees](https://tinyurl.com/wj4bqms)**| [Python](https://tinyurl.com/wu6rdaw/951_Flip_Equivalent_Binary_Trees.py)| **[Vid 1](https://tinyurl.com/uw378m8)**, [Art 1](https://tinyurl.com/r5d6jkk) | Medium | DFS | |29| **[528. Random Pick with Weight](https://tinyurl.com/vf8bruk)**| [Python](https://tinyurl.com/wu6rdaw/528_Random_Pick_with_Weight.py)| **[Vid 1](https://tinyurl.com/usd5r25)**, **[Art 1](https://tinyurl.com/rgwt57q)** | Medium | Very tricky | |30| **[236. Lowest Common Ancestor of a Binary Tree](https://tinyurl.com/y54e6gco)**| [Python](https://tinyurl.com/wu6rdaw/236_Lowest_Common_Ancestor_of_a_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/236_Lowest_Common_Ancestor_of_a_Binary_Tree.swift) | **[Vid 1](https://tinyurl.com/udf9oa9)**, **[Vid 2](https://tinyurl.com/stknbyu)**, **[Algoexpert.io](https://tinyurl.com/wwz4m5t)**, **[Official](https://tinyurl.com/yx28t8ff)**, **[Art 1](https://tinyurl.com/v86wcky)**, **[Art 2](https://tinyurl.com/tu7jdzq)**, **[Art 3](https://tinyurl.com/tgvyy7p)** | Medium | TODO: Check Again. Very Important | |31| **[114. Flatten Binary Tree to Linked List](https://tinyurl.com/yyc6ol5w)**| [Python](https://tinyurl.com/wu6rdaw/114_Flatten_Binary_Tree_to_Linked_List.py)| [Art 1](https://tinyurl.com/v5s5axv) | Medium | Classic Prolem | |32| **[297. Serialize and Deserialize Binary Tree](https://tinyurl.com/ycfugzww)**| [Python](https://tinyurl.com/wu6rdaw/297_Serialize_and_Deserialize_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/297_Serialize_and_Deserialize_Binary_Tree.swift) | [Vid 1](https://tinyurl.com/yx4w25u4) | Hard | Classic Prolem | |33| **[993. Cousins in Binary Tree](https://tinyurl.com/ybtzjhnb)**| [Python](https://tinyurl.com/wu6rdaw/993_Cousins_in_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/993_Cousins_in_Binary_Tree.swift) | | Easy(Not so) | | |34| **[572. Subtree of Another Tree](https://tinyurl.com/ybeerky9)**| [Python](https://tinyurl.com/wu6rdaw/572_Subtree_of_Another_Tree.py), [Swift](https://tinyurl.com/wuja3c4/572_Subtree_of_Another_Tree.swift) | [Art 1](https://tinyurl.com/y9epsrfa) | Easy(Not so) | | |35| **[314. Binary Tree Vertical Order Traversal](https://tinyurl.com/y7qx79no)**| [Python](https://tinyurl.com/wu6rdaw/314_Binary_Tree_Vertical_Order_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/314_Binary_Tree_Vertical_Order_Traversal.swift) | [Vid 1](https://tinyurl.com/ybb6amfl) | Medium | | |36| **[987. Vertical Order Traversal of a Binary Tree](https://tinyurl.com/y8vqh9hk)**| [Python](https://tinyurl.com/wu6rdaw/987_Vertical_Order_Traversal_of_a_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/987_Vertical_Order_Traversal_of_a_Binary_Tree.swift) | [Vid 1](https://tinyurl.com/y8byrezh), [Art 1](https://tinyurl.com/yajsqrpp), [Art 2](https://tinyurl.com/yadjj6sy) | Medium | | |37| **[958. Check Completeness of a Binary Tree](https://tinyurl.com/yd6dsk88)**| [Python](https://tinyurl.com/wu6rdaw/958_Check_Completeness_of_a_Binary_Tree.py), [Swift](https://tinyurl.com/wuja3c4/958_Check_Completeness_of_a_Binary_Tree.swift) | [Art 1](https://tinyurl.com/y729zfol) | Medium | | |38| **[865. Smallest Subtree with all the Deepest Nodes](https://tinyurl.com/y8cbxe4f)**| [Python](https://tinyurl.com/wu6rdaw/865_Smallest_Subtree_with_all_the_Deepest_Nodes.py), [Swift](https://tinyurl.com/wuja3c4/865_Smallest_Subtree_with_all_the_Deepest_Nodes.swift) | [Art 1](https://tinyurl.com/y9vq89jq), [Art 2](https://tinyurl.com/ydhfjr8t), [Art 3](https://tinyurl.com/y8z5p8u2), [Art 4](https://tinyurl.com/y8jm985p) | Medium | Vary ambigious question | |39| [1315. Sum of Nodes with Even-Valued Grandparent](https://tinyurl.com/y72q6hfn) | [Python](https://tinyurl.com/wu6rdaw/1315_Sum_of_Nodes_with_Even_Valued_Grandparent.py), [Swift](https://tinyurl.com/wuja3c4/1315_Sum_of_Nodes_with_Even_Valued_Grandparent.swift) | -- | Medium | -- | |40| [129. Sum Root to Leaf Numbers](https://tinyurl.com/yaxakdfs) | [Python](https://tinyurl.com/wu6rdaw/129_Sum_Root_to_Leaf_Numbers.py), [Swift](https://tinyurl.com/wuja3c4/129_Sum_Root_to_Leaf_Numbers.swift) | -- | Medium | -- | |41| [938. Range Sum of BST](https://tinyurl.com/r43zu3p) | [Python](https://tinyurl.com/wu6rdaw/938_Range_Sum_of_BST.py), [Swift](https://tinyurl.com/wuja3c4/938_Range_Sum_of_BST.swift) | -- | Medium | -- | |42| [1305. All Elements in Two Binary Search Trees](https://tinyurl.com/undhmra) | [Python](https://tinyurl.com/wu6rdaw/1305_All_Elements_in_Two_Binary_Search_Trees.py), [Swift](https://tinyurl.com/wuja3c4/1305_All_Elements_in_Two_Binary_Search_Trees.swift) | -- | Medium | -- | |43| [536. Construct Binary Tree from String](https://tinyurl.com/yyl5vuh7) | [Python](https://tinyurl.com/wu6rdaw/536_Construct_Binary_Tree_from_String.py), [Swift](https://tinyurl.com/wuja3c4/536_Construct_Binary_Tree_from_String.swift) | -- | Medium | -- | |44| [652. Find Duplicate Subtrees](https://tinyurl.com/y5zt6392) | [Python](https://tinyurl.com/wu6rdaw/652_Find_Duplicate_Subtrees.py), [Swift](https://tinyurl.com/wuja3c4/652_Find_Duplicate_Subtrees.swift) | -- | Medium | -- | |45| [366. Find Leaves of Binary Tree](https://tinyurl.com/yjaqjjyc) | [Swift](https://tinyurl.com/wuja3c4/366_Find_Leaves_of_Binary_Tree.swift) | -- | Medium | -- | </p> </details> ### 8. [Binary Search Tree](https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [701. Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/)| [Python](https://tinyurl.com/wu6rdaw/701_Insert_into_a_Binary_Search_Tree.py)| --- | Medium | Fundamentals | |02| [700. Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/)| [Python](https://tinyurl.com/wu6rdaw/700_Search_in_a_Binary_Search_Tree.py)| --- | Easy | Fundamentals | |03| [270. Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/)| [Python](https://tinyurl.com/wu6rdaw/270_Closest_Binary_Search_Tree_Value.py)| --- | Easy | Fundamentals | |04| [450. Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/solution/)| [Python](https://tinyurl.com/wu6rdaw/450_Delete_Node_in_a_BST.py)| --- | Medium | Fundamentals | |05| [98. Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/solution/)| [Python](https://tinyurl.com/wu6rdaw/98_Validate_Binary_Search_Tree.py)| --- | Medium | Fundamentals | |06| [94. Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)| [Python](https://tinyurl.com/wu6rdaw/94_Binary_Tree_Inorder_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/94_Binary_Tree_Inorder_Traversal.swift)| --- | Medium | Fundamentals | |07| [144. Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/)| [Python](https://tinyurl.com/wu6rdaw/144_Binary_Tree_Preorder_Traversal.py)| --- | Medium | Fundamentals | |08| [145. Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/)| [Python](https://tinyurl.com/wu6rdaw/145_Binary_Tree_Postorder_Traversal.py)| --- | Hard | Fundamentals | |09| [108. Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| [Python](https://tinyurl.com/wu6rdaw/108_Convert_Sorted_Array_to_Binary_Search_Tree.py)| --- | Easy | Fundamentals | |10| [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| [Python](https://tinyurl.com/wu6rdaw/109_Convert_Sorted_List_to_Binary_Search_Tree.py)| --- | Medium | Classic problem. Very important | |11| **[729. My Calendar I](https://tinyurl.com/r3ew2lb)** | [Python](https://tinyurl.com/wu6rdaw/729_My_Calendar_I.py), [Swift](https://tinyurl.com/wuja3c4/729_My_Calendar_I.swift)| [Art 1](https://tinyurl.com/tbd2z7u), [Art 2](https://tinyurl.com/t35fp3e) | Medium | Use self balancing BST for O(nlogn) solution. **Very important** | |12| **[449. Serialize and Deserialize BST](https://tinyurl.com/rx9rn3l)** | [Python](https://tinyurl.com/wu6rdaw/449_Serialize_and_Deserialize_BST.py), [Swift](https://tinyurl.com/wuja3c4/449_Serialize_and_Deserialize_BST.swift)| [Art 1](https://tinyurl.com/t6e2b97) | Medium | --- | |13| **[1008. Construct Binary Search Tree from Preorder Traversal](https://tinyurl.com/y6less2m)** | [Python](https://tinyurl.com/wu6rdaw/1008_Construct_Binary_Search_Tree_from_Preorder_Traversal.py), [Swift](https://tinyurl.com/wuja3c4/1008_Construct_Binary_Search_Tree_from_Preorder_Traversal.swift)| [Art 1](https://tinyurl.com/y9mondek), [Art 2](https://tinyurl.com/y8byt732), [Art 3](https://tinyurl.com/yaq7w2jt), [Art 4](https://tinyurl.com/ybwtzpzo) | Medium | --- | |14| **[653. Two Sum IV - Input is a BST](https://tinyurl.com/ydzdnawg)** | [Python](https://tinyurl.com/wu6rdaw/653_Two_Sum_IV_Input_is_a_BST.py), [Swift](https://tinyurl.com/wuja3c4/653_Two_Sum_IV_Input_is_a_BST.swift)| - | Easy | --- | |15| **[99. Recover Binary Search Tree](https://tinyurl.com/y9zxw8aj)** | [Python](https://tinyurl.com/wu6rdaw/99_Recover_Binary_Search_Tree.py), [Swift](https://tinyurl.com/wuja3c4/99_Recover_Binary_Search_Tree.swift)| - | Hard | **Very important, check again** | |16| [230. Kth Smallest Element in a BST](https://tinyurl.com/y8uku68q) | [Python](https://tinyurl.com/wu6rdaw/230_Kth_Smallest_Element_in_a_BST.py), [Swift](https://tinyurl.com/wuja3c4/230_Kth_Smallest_Element_in_a_BST.swift)| - | Medium | Easy peasy | </p> </details> ### 9. [N-Ary Tree](https://leetcode.com/explore/learn/card/n-ary-tree/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [589. N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/)| [Python](https://tinyurl.com/wu6rdaw/589_N-ary_Tree_Preorder_Traversal.py)| |02| [590. N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/)| [Python](https://tinyurl.com/wu6rdaw/590_N-ary_Tree_Postorder_Traversal.py)| |03| [429. N-ary Tree Level Order Traversal](https://leetcode.com/problems/n-ary-tree-level-order-traversal/)| [Python](https://tinyurl.com/wu6rdaw/429_N-ary_Tree_Level_Order_Traversal.py)| |04| [559. Maximum Depth of N-ary Tree](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/)| [Python](https://tinyurl.com/wu6rdaw/559_Maximum_Depth_of_N-ary_Tree.py)| |05| [431. Encode N-ary Tree to Binary Tree](https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/submissions/)| [Python](https://tinyurl.com/wu6rdaw/431_Encode_N-ary_Tree_to_Binary_Tree.py)| [Explanation](https://leetcode.com/explore/learn/card/n-ary-tree/131/recursion/922/) | |06| **[428. Serialize and Deserialize N-ary Tree](https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree/)** | [Python](https://tinyurl.com/wu6rdaw/428_Serialize_and_Deserialize_N-ary_Tree.py)| [Art 1](https://tinyurl.com/tgg874u), **[Official](https://tinyurl.com/sxds3zk)** | Hard | Very important | </p> </details> ### 10. Tree <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| **[315. Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)**| [Python](https://tinyurl.com/wu6rdaw/315_Count_of_Smaller_Numbers_After_Self.py)| [Article 1](https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/76657/3-ways-(Segment-Tree-Binary-Indexed-Tree-Binary-Search-Tree)-clean-python-code), [Article 2](https://medium.com/@timtim305/leetcode-315-count-of-smaller-numbers-after-self-be529cdfe148), [Vid 1](https://www.youtube.com/watch?v=CWDQJGaN1gY), [Vid 2](https://www.youtube.com/watch?v=ZBHKZF5w4YU) | Hard (Very) |๐Ÿ“Œ **Very hard and important. First learn [BIT](https://www.youtube.com/watch?v=CWDQJGaN1gY), [ST](https://www.youtube.com/watch?v=ZBHKZF5w4YU), [AVL-Tree](https://www.educative.io/courses/data-structures-in-python-an-interview-refresher/JYlwQZmN7V9) and [Red-Black Tree](https://www.educative.io/courses/data-structures-in-python-an-interview-refresher/YQy7Zlz1mEO) then try again**| </p> </details> ### 11. [Tries](https://leetcode.com/explore/learn/card/trie/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [208. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)| [Python](https://tinyurl.com/wu6rdaw/208_Implement_Trie_(Prefix_Tree).py)| |02| [211. Add and Search Word. Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [Python](https://tinyurl.com/wu6rdaw/211_Add_and_Search_Word_Data_structure_design.py)| [Video 01](https://www.youtube.com/watch?v=qi2ohSEyyDw), [Video 02](https://www.youtube.com/watch?v=neb_2UK5Kuo&t=13s)| |03| [642. Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/)| [Python](https://tinyurl.com/wu6rdaw/642_Design_Search_Autocomplete_System.py)| [Article 01](https://leetcode.com/problems/design-search-autocomplete-system/discuss/105386/Python-Clean-Solution-Using-Trie), [Video 01](https://www.youtube.com/watch?v=us0qySiUsGU)| Hard | --- | |04| [472. Concatenated Words](https://tinyurl.com/y9cv6dk5)| [Python](https://tinyurl.com/wu6rdaw/472_Concatenated_Words.py)| [Art 01](https://tinyurl.com/ycjm6fuo), [Art 02](https://tinyurl.com/ybvl3kbv)| Hard | Very important | |05| **[588. Design In-Memory File System](https://tinyurl.com/ya238cp4)** | [Python](https://tinyurl.com/wu6rdaw/588_Design_In_Memory_File_System.py)| --- | Hard | --- | |06| **[212. Word Search II](https://tinyurl.com/y8vcw472)** | [Python](https://tinyurl.com/wu6rdaw/212_Word_Search_II.py), [Swift](https://tinyurl.com/wuja3c4/212_Word_Search_II.swift) | [Art 1](https://tinyurl.com/y7td7eag) | Hard | --- | |07| **[1233. Remove Sub-Folders from the Filesystem](https://tinyurl.com/ybltz57l)** | [Python](https://tinyurl.com/wu6rdaw/1233_Remove_Sub_Folders_from_the_Filesystem.py), [Swift](https://tinyurl.com/wuja3c4/1233_Remove_Sub_Folders_from_the_Filesystem.swift) | [Art 1](https://tinyurl.com/ybae3tnm) | Medium | Didn't think of it as a trie. Good problem | </p> </details> ### 12. Graphs BFS, DFS, Dijkstra, Floydโ€“Warshall, Bellman-Ford, Kruskal, Prim's, Minimum Spanning Tree, Topological Ordering, Union Find. **Follow [this](https://tinyurl.com/tcpmneh) golden rule to approach any graph problem.** <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| **[207. Course Schedule](https://tinyurl.com/y2n8mekw)** | [Python](https://tinyurl.com/wu6rdaw/207_Course_Schedule.py)| **[educative.io](https://tinyurl.com/s9c4rlh)** | Medium | ๐Ÿ“Œ Very Important. Check again. BFS, Topological Sort | |02| **[210. Course Schedule II](https://tinyurl.com/t7e74n2)** | [Python](https://tinyurl.com/wu6rdaw/210_Course_Schedule_II.py)| **[educative.io](https://tinyurl.com/wz2a7f2)** | Medium | ๐Ÿ“Œ Very Important. Check again. BFS, Topological Sort | |03| **[269. Alien Dictionary](https://tinyurl.com/y6cp4783)** | [Python](https://tinyurl.com/wu6rdaw/269_Alien_Dictionary.py), [Swift](https://tinyurl.com/wuja3c4/269_Alien_Dictionary.swift) | **[educative.io](https://tinyurl.com/v9o2bq7)**, [Vid 1](https://tinyurl.com/uyq3rsr), [Vid 2](https://tinyurl.com/t2okooj), [Vid 3](https://tinyurl.com/s2mht66) | Hard | ๐Ÿ“Œ Very Important. Check again. BFS, Topological Sort | |04| **[444. Sequence Reconstruction](https://tinyurl.com/v4zalus)** | [Python](https://tinyurl.com/wu6rdaw/444_Sequence_Reconstruction.py)| **[educative.io](https://tinyurl.com/tp6dxjz)** | Medium/Hard | ๐Ÿ“Œ Check again. BFS, Topological Sort | |05| **[310. Minimum Height Trees](https://tinyurl.com/u8ej2cp)** | [Python](https://tinyurl.com/wu6rdaw/310_Minimum_Height_Trees.py)| **[educative.io](https://tinyurl.com/t83ley2)** | Hard | ๐Ÿ“Œ TODO: Check again, very hard, didn't get the intuition. BFS, Topological Sort | |06| **[329. Longest Increasing Path in a Matrix](https://tinyurl.com/vmb7btv)** | [Python](https://tinyurl.com/wu6rdaw/329_Longest_Increasing_Path_in_a_Matrix.py)| [Official](https://tinyurl.com/sddke8e), [Art 1](https://tinyurl.com/s2t4dhh), [Art 2](https://tinyurl.com/ra8s2hz) | Hard | ** ๐Ÿ“Œ TODO: Not Done, very hard and important. DP, Topological Sort ** | |07| **[1203. Sort Items by Groups Respecting Dependencies](https://tinyurl.com/vaz5vrk)** | [Python](https://tinyurl.com/wu6rdaw/1203_Sort_Items_by_Groups_Respecting_Dependencies.py)| | Hard | ๐Ÿ“Œ TODO: Not Done, very hard, didn't get the intuition. BFS, Topological Sort | |08| **[695. Max Area of Island](https://leetcode.com/problems/max-area-of-island/)** | [Python](https://tinyurl.com/wu6rdaw/695_Max_Area_of_Island.py)| --- | Medium | DFS | |09| **[200. Number of Islands](https://leetcode.com/problems/number-of-islands/)** | [Python](https://tinyurl.com/wu6rdaw/200_Number_of_Islands.py)| [Algoexpert.io - DFS](https://tinyurl.com/wux27jk), **[Union Find](https://tinyurl.com/tgzexdk)**, [Art 1](https://tinyurl.com/wgum82w) | Medium | DFS + DFS, Union Find | |10| **[305. Number of Islands II](https://tinyurl.com/qpca3gz)** | [Python](https://tinyurl.com/wu6rdaw/305_Number_of_Islands_II.py)| **[Union Find](https://tinyurl.com/tgzexdk)**, [Art 0](https://tinyurl.com/vla7uya), [Art 1](https://tinyurl.com/v3sjgb2), [Art 2](https://tinyurl.com/wshbuf9), [Art 3](https://tinyurl.com/qohtl3m), [Art 4](https://tinyurl.com/tb5yjrz), [Art 5](https://tinyurl.com/tzwzzqy) | Hard | Union Find | |11| **[399. Evaluate Division](https://tinyurl.com/sjl9mqh)** | [Python](https://tinyurl.com/wu6rdaw/399_Evaluate_Division.py)| **[Art 0](https://tinyurl.com/v4mlv9o)**, **[Art 1](https://tinyurl.com/vn8g56l)**, **[Art 2](https://tinyurl.com/tcpmneh)**, [Art 3](https://tinyurl.com/rvzopd4), [Art 4](https://tinyurl.com/tcuwpnn), [Art 5](https://tinyurl.com/rxqn7gb) | Medium | TODO: Solve it using Union Find | |12| [841. Keys and Rooms](https://tinyurl.com/wphmoou) | [Python](https://tinyurl.com/wu6rdaw/841_Keys_and_Rooms.py)| **[codinginterviewclass.com](https://tinyurl.com/s6ygbtj)**, [Art 1](https://tinyurl.com/s8retco), [Art 2](https://tinyurl.com/w5m9e5n) | Medium | BFS, DFS | |13| **[490. The Maze](https://tinyurl.com/srh3vzz)** | [Python](https://tinyurl.com/wu6rdaw/490_The_Maze.py)| **[codinginterviewclass.com](https://tinyurl.com/qo5rrt4)**, [Vid 1](https://tinyurl.com/s9wse7o), **[Art 1](https://tinyurl.com/ueg56of)**, **[Art 2](https://tinyurl.com/wyn5yrl)**, [Art 3](https://tinyurl.com/t95pdp4), [Art 4](https://tinyurl.com/wxvd26q), [Art 5](https://tinyurl.com/vmjgh6v) | Medium | **Modified BFS and DFS** | |14| **[130. Surrounded Regions](https://tinyurl.com/tnmbzep)** | [Python](https://tinyurl.com/wu6rdaw/130_Surrounded_Regions.py)| **[codinginterviewclass.com](https://tinyurl.com/uclclqk)**, **[Art 1](https://tinyurl.com/yx859xh6)**, **[Art 2](https://tinyurl.com/wbnnm8n)** | Medium | **TODO: Solve it using Union Find. Modified BFS and DFS** | |15| **[127. Word Ladder](https://tinyurl.com/y99azp8z)** | [Python](https://tinyurl.com/wu6rdaw/127_Word_Ladder.py)| **[backtobackswe.com](https://tinyurl.com/y9thba6e)**, **[Official](https://tinyurl.com/y99azp8z)**, **[Art 1](https://tinyurl.com/ya3vr264)** | Medium | **Very important and tricky. Modified BFS. Shortest Path finding** | |16| **[126. Word Ladder II](https://tinyurl.com/jubpmll)** | [Python](https://tinyurl.com/wu6rdaw/126_Word_Ladder_II.py)| **[backtobackswe.com](https://tinyurl.com/y9thba6e)**, **[Official](https://tinyurl.com/y99azp8z)**, **[Vid 1](https://tinyurl.com/ws465le)**, **[Vid 2](https://tinyurl.com/y7apdbwu)**, **[Art 1 - Must](https://tinyurl.com/y89mjm4c)** | Hard | **TODO: Not Done. Extremely tricky. Modified BFS. Learned [Bidirectional Search](https://tinyurl.com/vx3oqbf)** | |17| **[785. Is Graph Bipartite?](https://tinyurl.com/wvwqw2j)** | [Python](https://tinyurl.com/wu6rdaw/785_Is_Graph_Bipartite.py), [Swift](https://tinyurl.com/wuja3c4/785_Is_Graph_Bipartite.swift)| **[backtobackswe.com](https://tinyurl.com/y46j3se6)**, **[Official](https://tinyurl.com/rynbqly)** | Medium | **Important, Learned new things. Undirected Graph** | |18| **[133. Clone Graph](https://tinyurl.com/y42nwqz8)** | [Python](https://tinyurl.com/wu6rdaw/133_Clone_Graph.py), [Swift](https://tinyurl.com/wuja3c4/133_Clone_Graph.swift) | **[backtobackswe.com](https://tinyurl.com/y8tluhov)**, **[Official](https://tinyurl.com/usxjk49)** | Medium | **Important, Learned new things. Undirected Graph** | |19| **[332. Reconstruct Itinerary](https://tinyurl.com/gn2mv3k)** | [Python](https://tinyurl.com/wu6rdaw/332_Reconstruct_Itinerary.py)| [Vid 1](https://tinyurl.com/w47evd9), [Vid 2](https://tinyurl.com/uvop34p), [Art 1](https://tinyurl.com/tsy24pl), [Art 2](https://tinyurl.com/srazxo3), [Art 3](https://tinyurl.com/wluob5j), **[Art 4](https://tinyurl.com/y4s9crf6)** | Medium | **Important, Learned new things. Directed Graph. Eulerian path and top Sort** | |20| **[1153. String Transforms Into Another String](https://tinyurl.com/sv9hpo8)** | [Python](https://tinyurl.com/wu6rdaw/1153_String_Transforms_Into_Another_String.py)| **[Vid 1](https://tinyurl.com/ty2ga7d)**, [Vid 2](https://tinyurl.com/vxr9zxp), [Art 1](https://tinyurl.com/rklzgkk), [Art 2](https://tinyurl.com/seb6vqq), [Art 3](https://tinyurl.com/vfjwn5h), [Art 4](https://tinyurl.com/w62hpq2), [Art 5](https://tinyurl.com/tteucry), [Art 6](https://tinyurl.com/uvctnvz) | Extremely Hard | **TODO: Check again. Very Important and tricky, Learned new things. Digraph.** | |21| **[743. Network Delay Time](https://tinyurl.com/yd88jryl)** | [Python](https://tinyurl.com/wu6rdaw/743_Network_Delay_Time.py)| **[Official](https://tinyurl.com/rmcr2xk)**, **[Dijkstra 1](https://tinyurl.com/r8omw8l)**, **[Dijkstra 2](https://tinyurl.com/sscslz7)**, [Vid 1](https://tinyurl.com/vucexbc), **[Art 1](https://tinyurl.com/vbetlaq)**, [Art 2](https://tinyurl.com/yxdzrw3k), **[Art 3](https://tinyurl.com/whnbv4o)**, **[Art 4](https://tinyurl.com/roq3udj)** | Medium | **TODO: Check again. Very Important. Learned (Dijkstra, Bellman, Floyed). Check references section** | |22| **[261. Graph Valid Tree](https://tinyurl.com/uw9ndt6)** | [Python](https://tinyurl.com/wu6rdaw/261_Graph_Valid_Tree.py)| [Art 1](https://tinyurl.com/yx6ehrfu), **[Art 2](https://tinyurl.com/tlw6vda)**, **[Art 3](https://tinyurl.com/yhs85tj3)**, [Art 4](https://tinyurl.com/ydkfcc5x) | Medium | Important. BFS, DFS and [Union Find](https://tinyurl.com/yhs85tj3) | |23| **[1168. Optimize Water Distribution in a Village](https://tinyurl.com/ygh8sahd)** | [Python](https://tinyurl.com/wu6rdaw/1168_Optimize_Water_Distribution_in_a_Village.py)| **[Art 1](https://tinyurl.com/yjwwoxv3)**, **[Art 2](https://tinyurl.com/yhc3a7yr)**, **[Art 3](https://tinyurl.com/yf7fjz4v)**, [Art 4](https://tinyurl.com/yh7n9wps) | Hard | TODO: Check AGain. Prim's and Kruskal's algorithm. Important. | |24| **[1197. Minimum Knight Moves](https://tinyurl.com/svox8jw)** | [Python](https://tinyurl.com/wu6rdaw/1197_Minimum_Knight_Moves.py)| **[Art 1](https://tinyurl.com/wed5c6s)** | Medium | TODO: Check AGain. Important. | |25| **[1066. Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/)** | [Python](https://tinyurl.com/wu6rdaw/1066_Campus_Bikes_II.py)| [Vid 1](https://tinyurl.com/qq6obzv), **[Art 1](https://tinyurl.com/r4wtfbo)** | Medium |๐Ÿ“Œ **TODO: CHECK Dijkstra approach again. Backtracking solution is getting TLE. Solve it and implement it with DP also. Very important** | |26| **[752. Open the Lock](https://tinyurl.com/yxpwjn7r)** | [Python](https://tinyurl.com/wu6rdaw/752_Open_the_Lock.py)| **[Art 1](https://tinyurl.com/s3oskv8)**, **[Art 2](https://tinyurl.com/rsr4tz9)** | Medium |๐Ÿ“Œ **TODO: CHECK again. Very important and interesting problem. Loved it** | |27| **[489. Robot Room Cleaner](https://tinyurl.com/yxpwjn7r)** | [Python](https://tinyurl.com/wu6rdaw/489_Robot_Room_Cleaner.py), [Swift](https://tinyurl.com/wuja3c4/489_Robot_Room_Cleaner.swift) | **[Vid 1](https://tinyurl.com/vahalvm)**, **[Vid 2](https://tinyurl.com/qpumkro)**, **[Art 1](https://tinyurl.com/rnu8679)** | Hard |๐Ÿ“Œ **TODO: CHECK again. Very important and interesting problem. I fucking loved it** | |28| **[1136. Parallel Courses](https://tinyurl.com/yxpwjn7r)** | [Python](https://tinyurl.com/wu6rdaw/11136_Parallel_Courses.py), [Swift](https://tinyurl.com/wuja3c4/11136_Parallel_Courses.swift) | --- | Hard |๐Ÿ“Œ Topological sort. | |29| **[947. Most Stones Removed with Same Row or Column](https://tinyurl.com/rrm6w2a)** | [Python](https://tinyurl.com/wu6rdaw/947_Most_Stones_Removed_with_Same_Row_or_Column.py), [Swift](https://tinyurl.com/wuja3c4/947_Most_Stones_Removed_with_Same_Row_or_Column.swift) | [Vid 1](https://tinyurl.com/sc2g6eg), [Art 1](https://tinyurl.com/sxyzxkr), [Vid 2](https://tinyurl.com/wocnrhn), [Art 2](https://tinyurl.com/sogsj74), [Art 3](https://tinyurl.com/w4pk463) | Medium |๐Ÿ“Œ DFS and Union FInd | |30| [1042. Flower Planting With No Adjacent](https://tinyurl.com/unwlzyy) | [Python](https://tinyurl.com/wu6rdaw/1042_Flower_Planting_With_No_Adjacent.py), [Swift](https://tinyurl.com/wuja3c4/1042_Flower_Planting_With_No_Adjacent.swift) | --- | Easy |๐Ÿ“Œ Could be done using DFS, BFS | |31| **[994_Rotting_Oranges](https://tinyurl.com/yavrnvu5)** | [Python](https://tinyurl.com/wu6rdaw/994_Rotting_Oranges.py), [Swift](https://tinyurl.com/wuja3c4/994_Rotting_Oranges.swift) | --- | Medium |๐Ÿ“Œ BFS | |32| **[909. Snakes and Ladders](https://tinyurl.com/yazkm38f)** | [Python](https://tinyurl.com/wu6rdaw/909_Snakes_and_Ladders.py), [Swift](https://tinyurl.com/wuja3c4/909_Snakes_and_Ladders.swift) | [Art 1](https://tinyurl.com/ya45spcc), [Art 2](https://tinyurl.com/ycafdfr4), [Art 3](https://tinyurl.com/yc3hdaw9), [Vid 1](https://tinyurl.com/yc3hdaw9), [Vid 2](https://tinyurl.com/y99hrfvk), | Medium |๐Ÿ“Œ BFS. Check again | |33| **[1192. Critical Connections in a Network](https://tinyurl.com/y6u2p7qw)** | [Python](https://tinyurl.com/wu6rdaw/1192_Critical_Connections_in_a_Network.py), [Swift](https://tinyurl.com/wuja3c4/1192_Critical_Connections_in_a_Network.swift) | [Art 1](https://tinyurl.com/yc2tzb4k), [Art 2](https://tinyurl.com/ycjd3rrr), [Art 3](https://tinyurl.com/ybj5nux8), [Art 4](https://tinyurl.com/y9wz5w8o), [Vid 1](https://tinyurl.com/y76cux54), [Vid 2](https://tinyurl.com/ybmgmv5l), [Vid 3](https://tinyurl.com/y7sa5oou) | Hard |๐Ÿ“Œ **Important, Learned new things.Tarjans SCCs algorithm. Check again** | |34| **[694. Number of Distinct Islands](https://tinyurl.com/ybf8cedn)** | [Python](https://tinyurl.com/wu6rdaw/694_Number_of_Distinct_Islands.py), [Swift](https://tinyurl.com/wuja3c4/694_Number_of_Distinct_Islands.swift) | [Art 1](https://tinyurl.com/y7rapyk6), [Art 2](https://tinyurl.com/yde8dqbb) | Medium |๐Ÿ“Œ | |35| [997. Find the Town Judge](https://tinyurl.com/y7875kls) | [Python](https://tinyurl.com/wu6rdaw/997_Find_the_Town_Judge.py), [Swift](https://tinyurl.com/wuja3c4/997_Find_the_Town_Judge.swift) | --- | Easy |๐Ÿ“Œ | |36| [733. Flood Fill](https://tinyurl.com/y9pecfd8) | [Python](https://tinyurl.com/wu6rdaw/733_Flood_Fill.py), [Swift](https://tinyurl.com/wuja3c4/733_Flood_Fill.swift) | --- | Easy |๐Ÿ“Œ | |37| [339. Nested List Weight Sum](https://tinyurl.com/y53lt8ad) | [Python](https://tinyurl.com/wu6rdaw/339_Nested_List_Weight_Sum.py), [Swift](https://tinyurl.com/wuja3c4/339_Nested_List_Weight_Sum.swift) | --- | Easy |๐Ÿ“Œ | |38| [1026. Maximum Difference Between Node and Ancestor](https://tinyurl.com/y53lt8ad) | [Python](https://tinyurl.com/wu6rdaw/1026_Maximum_Difference_Between_Node_and_Ancestor.py), [Swift](https://tinyurl.com/wuja3c4/1026_Maximum_Difference_Between_Node_and_Ancestor.swift) | --- | Medium |๐Ÿ“Œ | |39| [721. Accounts Merge](https://tinyurl.com/yaxzzqf9) | [Python](https://tinyurl.com/wu6rdaw/721_Accounts_Merge.py), [Swift](https://tinyurl.com/wuja3c4/721_Accounts_Merge.swift) | --- | Medium |๐Ÿ“Œ Loved it and hated it. Learned a lot. Very insightfull and tricky, deceiving problem. Be very carefull with your choice | |40| [1123. Lowest Common Ancestor of Deepest Leaves](https://tinyurl.com/ybn3fg7l) | [Python](https://tinyurl.com/wu6rdaw/1123_Lowest_Common_Ancestor_of_Deepest_Leaves.py), [Swift](https://tinyurl.com/wuja3c4/1123_Lowest_Common_Ancestor_of_Deepest_Leaves.swift) | --- | Medium |๐Ÿ“Œ Loved it and hated it. | |41| [419. Battleships in a Board](https://tinyurl.com/y9ag7c2o) | [Python](https://tinyurl.com/wu6rdaw/419_Battleships_in_a_Board.py), [Swift](https://tinyurl.com/wuja3c4/419_Battleships_in_a_Board.swift) | --- | Medium |๐Ÿ“Œ Union FInd and or DFS. | |42| [934. Shortest Bridge](https://tinyurl.com/yd2m8jn9) | [Python](https://tinyurl.com/wu6rdaw/934_Shortest_Bridge.py), [Swift](https://tinyurl.com/wuja3c4/934_Shortest_Bridge.swift) | [Art 1](https://tinyurl.com/ybwcd7fm) | Medium |๐Ÿ“Œ DFS and BFS | |43| [317. Shortest Distance from All Buildings](https://tinyurl.com/ybx7nqfu) | [Python](https://tinyurl.com/wu6rdaw/317_Shortest_Distance_from_All_Buildings.py), [Swift](https://tinyurl.com/wuja3c4/317_Shortest_Distance_from_All_Buildings.swift) | [Art 1](https://tinyurl.com/y6wxhuj8) | Hard |๐Ÿ“Œ BFS, a must do problem | |44| [93. Restore IP Addresses](https://tinyurl.com/y554o9ej) | [Python](https://tinyurl.com/wu6rdaw/93_Restore_IP_Addresses.py), [Swift](https://tinyurl.com/wuja3c4/93_Restore_IP_Addresses.swift) | --- | Medium |๐Ÿ“Œ A must do problem. Backtracking | |45| [1424. Diagonal Traverse II](https://tinyurl.com/y3n5k6e9) | [Python](https://tinyurl.com/wu6rdaw/1424_Diagonal_Traverse_II.py), [Swift](https://tinyurl.com/wuja3c4/1424_Diagonal_Traverse_II.swift) | --- | Medium |๐Ÿ“Œ Very interesting one. | |46| [364_Nested_List_Weight_Sum_II](https://tinyurl.com/w5d2ff4) | [Python](https://tinyurl.com/wu6rdaw/364_Nested_List_Weight_Sum_II.py), [Swift](https://tinyurl.com/wuja3c4/364_Nested_List_Weight_Sum_II.swift) | --- | Medium |๐Ÿ“Œ Hidden DFS | |47| [1245. Tree Diameter](https://tinyurl.com/yxq4uykv) | [Python](https://tinyurl.com/wu6rdaw/1245_Tree_Diameter.py), [Swift](https://tinyurl.com/wuja3c4/1245_Tree_Diameter.swift) | [Art 1](https://www.geeksforgeeks.org/longest-path-undirected-tree/) | Medium |๐Ÿ“Œ Learned, 2 BFS. Important and interesting | |48| [1376. Time Needed to Inform All Employees](https://tinyurl.com/y3e5bb22) | [Python](https://tinyurl.com/wu6rdaw/1376_Time_Needed_to_Inform_All_Employees.py), [Swift](https://tinyurl.com/wuja3c4/1376_Time_Needed_to_Inform_All_Employees.swift) | [Art 1](https://tinyurl.com/y2lw6s4j) | Medium |๐Ÿ“Œ BFS, DFS | |49| [286. Walls and Gates](https://tinyurl.com/y3ollzsl) | [Python](https://tinyurl.com/wu6rdaw/286_Walls_and_Gates.py), [Swift](https://tinyurl.com/wuja3c4/286_Walls_and_Gates.swift) | --- | Medium |๐Ÿ“Œ BFS, DFS | |50| [1138. Alphabet Board Path](https://tinyurl.com/y2xk6r98) | [Python](https://tinyurl.com/wu6rdaw/1138_Alphabet_Board_Path.py), [Swift](https://tinyurl.com/wuja3c4/1138_Alphabet_Board_Path.swift) | --- | Medium |๐Ÿ“Œ BFS | |51| [690. Employee Importance](https://tinyurl.com/yyweuk43) | [Python](https://tinyurl.com/wu6rdaw/690_Employee_Importance.py), [Swift](https://tinyurl.com/wuja3c4/690_Employee_Importance.swift) | --- | Easy |๐Ÿ“Œ BFS | |52| **[1631. Path With Minimum Effort](https://tinyurl.com/y3nh25d9)** | [Python](https://tinyurl.com/wu6rdaw/1631_Path_With_Minimum_Effort.py), [Swift](https://tinyurl.com/wuja3c4/1631_Path_With_Minimum_Effort.swift) | --- | Medium |๐Ÿ“Œ BFS, DFS, Binary search | |53| **[547. Friend Circles](https://tinyurl.com/r39pov7)** | [Python](https://tinyurl.com/wu6rdaw/547_Friend_Circles.py), [Swift](https://tinyurl.com/wuja3c4/547_Friend_Circles.swift) | [Art 1](https://tinyurl.com/y6qm62wq), [Art 2](https://tinyurl.com/y2gk7dq4) | Medium |๐Ÿ“Œ BFS, DFS, Union Find | |53| **[1254. Number of Closed Islands](https://tinyurl.com/r39pov7)** | [Swift](https://tinyurl.com/wuja3c4/1254_Number_of_Closed_Islands.swift) | [Art 1](https://tinyurl.com/yzedwp3y), [Art 2](https://tinyurl.com/ye5jolg7) | Medium |๐Ÿ“Œ BFS, DFS, Union Find | </p> </details> ### 13. [Recursion, Iteration](https://leetcode.com/explore/learn/card/recursion-i/) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [509. Fibonacci Number](https://leetcode.com/problems/fibonacci-number/)| [Python](https://tinyurl.com/wu6rdaw/509_Fibonacci_Number.py)| |02| [50. Pow(x, n)](https://leetcode.com/problems/powx-n/)| [Python](https://tinyurl.com/wu6rdaw/50_Pow(x%2C_n).py)| |00| It's a general topics which has been covered on Backtracking and graph problems| --- | --- | --- | --- | </p> </details> ### 14. [Backtracking](https://www.youtube.com/watch?v=DKCbsiDBN6c) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [211. Add and Search Word. Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [Python](https://tinyurl.com/wu6rdaw/211_Add_and_Search_Word_Data_structure_design.py)| [Video 01](https://www.youtube.com/watch?v=qi2ohSEyyDw), [Video 02](https://www.youtube.com/watch?v=neb_2UK5Kuo&t=13s)| |02| [37. Sudoku Solver](https://leetcode.com/problems/sudoku-solver/)| [Python](https://tinyurl.com/wu6rdaw/37_Sudoku_Solver.py)| [Video 01](https://www.youtube.com/watch?v=JzONv5kaPJM), [Video 02](https://www.youtube.com/watch?v=Zq4upTEaQyM&list=PLiQ766zSC5jM2OKVr8sooOuGgZkvnOCTI)| |03| [52. N-Queens II](https://leetcode.com/problems/n-queens-ii/)| [Python](https://tinyurl.com/wu6rdaw/52_N-Queens_II.py)| [Video 01](https://www.youtube.com/watch?v=xFv_Hl4B83A), [Video 02](https://www.youtube.com/watch?v=xouin83ebxE)| |04| [784. Letter Case Permutation](https://leetcode.com/problems/letter-case-permutation/)| [Python](https://tinyurl.com/wu6rdaw/784_Letter_Case_Permutation.py)| --- | Easy | Backtracking Fundamentals | |05| [1219. Path with Maximum Gold](https://leetcode.com/problems/path-with-maximum-gold/)| [Python](https://tinyurl.com/wu6rdaw/1219_Path_with_Maximum_Gold.py)| --- | Medium |๐Ÿ“Œ --- | |06| [79. Word Search](https://leetcode.com/problems/word-search/)| [Python](https://tinyurl.com/wu6rdaw/79_Word_Search.py)| [Article 1](https://leetcode.com/problems/word-search/discuss/27660/Python-dfs-solution-with-comments.) | Medium | Backtracking Fundamentals | |07| [**679. 24 Game**](https://leetcode.com/problems/24-game/)| [Python](https://tinyurl.com/wu6rdaw/679_24_Game.py)| [Art 1](https://tinyurl.com/v73ldlm), [Art 2](https://tinyurl.com/udpg8tt), [Art 3](https://tinyurl.com/so9psfl), [Official](https://tinyurl.com/rwosllt) | Very Hard |๐Ÿ“Œ Very tricky and important. Revise again. | |08| **[1066. Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/)** | [Python](https://tinyurl.com/wu6rdaw/1066_Campus_Bikes_II.py)| [Vid 1](https://tinyurl.com/qq6obzv), **[Art 1](https://tinyurl.com/r4wtfbo)** | Medium |๐Ÿ“Œ **TODO: CHECK Dijkstra approach again. Backtracking solution is getting TLE. Solve it and implement it with DP also. Very important** | |09| [1087. Brace Expansion](https://leetcode.com/problems/brace-expansion/)| [Python](https://tinyurl.com/wu6rdaw/1087_Brace_Expansion.py)| --- | Medium |๐Ÿ“Œ --- | |10| [78. Subsets](https://leetcode.com/problems/subsets/)| [Python](https://tinyurl.com/wu6rdaw/78_Subsets.py)| [Video 1](https://www.youtube.com/results?search_query=All+Subsets+of+a+Set), [Video 2](https://www.youtube.com/watch?v=MsHFNGltIxw), [Video 3](https://www.youtube.com/watch?v=xTNFs5KRV_g), [Article 1](https://tinyurl.com/y5p2ozjo), **[educative.io](https://tinyurl.com/umzgkhr)** | Medium |๐Ÿ“Œ TODO: check bit manipulation | |11| [90. Subsets II](https://tinyurl.com/rqpxyat)| [Python](https://tinyurl.com/wu6rdaw/90_Subsets_II.py)| [Video 1](https://www.youtube.com/results?search_query=All+Subsets+of+a+Set), [Video 2](https://www.youtube.com/watch?v=MsHFNGltIxw), [Video 3](https://www.youtube.com/watch?v=xTNFs5KRV_g), [Article 1](https://tinyurl.com/y5p2ozjo), **[educative.io](https://tinyurl.com/wfkx3jt)** | Medium |๐Ÿ“Œ | |12| [46. Permutations](https://leetcode.com/problems/permutations/)| [Python](https://tinyurl.com/wu6rdaw/46_Permutations.py)| [codinginterviewclass.com](https://tinyurl.com/ujv54ef), [algoexpert.io](https://tinyurl.com/tou9p8p), [educative.io](https://tinyurl.com/s3ncxtn), [Article 1](https://tinyurl.com/whkjst5), [Article 2](https://tinyurl.com/y3jq5gqm) | Medium | Backtracking Fundamentals | |13| [47. Permutations II](https://tinyurl.com/twg7jb4)| [Python](https://tinyurl.com/wu6rdaw/47_Permutations_II.py)| [codinginterviewclass.com](https://tinyurl.com/ujv54ef), [algoexpert.io](https://tinyurl.com/tou9p8p), [educative.io](https://tinyurl.com/s3ncxtn), [Article 1](https://tinyurl.com/wmpb8h3) | Medium | Backtracking Fundamentals | |14| **[31. Next Permutation](https://tinyurl.com/tprftfa)** | [Python](https://tinyurl.com/wu6rdaw/31_Next_Permutation.py), [Swift](https://tinyurl.com/wuja3c4/31_Next_Permutation.swift)| [backtobackswe.com](https://tinyurl.com/ya3oknlr), [Vid 1](https://tinyurl.com/vfmnqt4), [Art 1](https://tinyurl.com/rvn68ov), [Official](https://tinyurl.com/ybvdtjru) | Medium | Backtracking | |15| [77. Combinations](https://tinyurl.com/ufdjrht)| [Python](https://tinyurl.com/wu6rdaw/77_Combinations.py)| [codinginterviewclass.com](https://tinyurl.com/snq55o7) | Medium | Backtracking | |16| [39. Combination Sum](https://leetcode.com/problems/combination-sum/)| [Python](https://tinyurl.com/wu6rdaw/39_Combination_Sum.py)| [Article 1](https://tinyurl.com/y5fpdget), [Article 2](https://leetcode.com/problems/combination-sum/discuss/16510/Python-dfs-solution.) | Medium | Backtracking Fundamentals | |17| [40. Combination Sum II](https://tinyurl.com/roqgnjf)| [Python](https://tinyurl.com/wu6rdaw/40_Combination_Sum_II.py)| --- | Medium | Backtracking Fundamentals | |18| [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| [Python](https://tinyurl.com/wu6rdaw/17_Letter_Combinations_of_a_Phone_Number.py)| [Video 1](https://www.youtube.com/watch?v=a-sMgZ7HGW0), [Video 2 - paid course](https://codinginterviewclass.com/courses/633601/lectures/11653975), [Article 1](https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/8067/Python-easy-to-understand-backtracking-solution.) | Medium | Backtracking Fundamentals | |19| [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)| [Python](https://tinyurl.com/wu6rdaw/22_Generate_Parentheses.py), [Swift](https://tinyurl.com/wuja3c4/22_Generate_Parentheses.swift) | [educative.io](https://tinyurl.com/wady2xs), [Video 1](https://www.youtube.com/watch?v=sz1qaKt0KGQ), [Article 1](https://leetcode.com/problems/generate-parentheses/discuss/10100/Easy-to-understand-Java-backtracking-solution) | Medium | Backtracking Fundamentals | |20| [1088. Confusing Number II](https://tinyurl.com/tb7w75j)| [Python](https://tinyurl.com/wu6rdaw/1088_Confusing_Number_II.py), [Swift](https://tinyurl.com/wuja3c4/1088_Confusing_Number_II.swift) | [Art 1](https://tinyurl.com/wby5h93), [Ref 1](https://tinyurl.com/w54thz5) | Hard | Very interesting | |21| [465. Optimal Account Balancing](https://tinyurl.com/smsbk4t)| [Python](https://tinyurl.com/wu6rdaw/465_Optimal_Account_Balancing.py), [Swift](https://tinyurl.com/wuja3c4/465_Optimal_Account_Balancing.swift) | **[Art 1](https://tinyurl.com/txuvptu)** | Hard | Loved the question, awsome real life description | |22| [1079. Letter Tile Possibilities](https://tinyurl.com/r5xjymk) | [Python](https://tinyurl.com/wu6rdaw/1079_Letter_Tile_Possibilities.py), [Swift](https://tinyurl.com/wuja3c4/1079_Letter_Tile_Possibilities.swift) | --- | Medium |๐Ÿ“Œ Could be done using DFS, backtracking | |23| **[60. Permutation Sequence](https://tinyurl.com/yz98ms7h)** | [Python](https://tinyurl.com/wu6rdaw/60_Permutation_Sequence.py), [Swift](https://tinyurl.com/wuja3c4/60_Permutation_Sequence.swift) | **[Art 1](https://tinyurl.com/ybvcswyd)** | Medium | ๐Ÿ“Œ What an awesome question and smart solution. loved it. | </p> </details> ### 15. [Greedy](https://www.youtube.com/watch?v=ARvQcqJ_-NY) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| **[1055. Shortest Way to Form String](https://tinyurl.com/rpwq5bx)**| [Python](https://tinyurl.com/wu6rdaw/1055_Shortest_Way_to_Form_String.py)| [Art 1](https://tinyurl.com/t6xap4c), [Art 2](https://tinyurl.com/y2nu3o52), [Art 3](https://tinyurl.com/wsjho6w), [Art 4](https://tinyurl.com/qrfuedy), [Art 5](https://tinyurl.com/tnzxjjz) | Medium | ๐Ÿ“Œ **Very important and hard problem** | |02| [1057. Campus Bikes](https://leetcode.com/problems/campus-bikes/)| [Python](https://tinyurl.com/wu6rdaw/1057_Campus_Bikes.py)| [Video 01](https://www.youtube.com/watch?v=tG7GFge4-fQ), [Article 01](https://leetcode.com/problems/campus-bikes/discuss/371604/Python-Solution-Using-Dictionary-With-Explanation)| Medium | ๐Ÿ“Œ Solve [1066. Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/) using [DP](https://leetcode.com/problems/campus-bikes-ii/discuss/303471/Python-DP-vs-Backtracking-with-comments), [DFS](https://leetcode.com/problems/campus-bikes-ii/discuss/303383/Python-DFS-with-memorization) and [Priority Queue](https://leetcode.com/problems/campus-bikes-ii/discuss/303422/Python-Priority-Queue) | |03| **[1007. Minimum Domino Rotations For Equal Row](https://tinyurl.com/y6qgt5fk)** | [Python](https://tinyurl.com/wu6rdaw/Minimum_Domino_Rotations_For_Equal_Row.py)| [Vid 1](https://tinyurl.com/uobop48), [Vid 2](https://tinyurl.com/qkqlcmv),[Art 1](https://tinyurl.com/ufvb3kg),[Art 2](https://tinyurl.com/u85uegn),[Art 3](https://tinyurl.com/yxq7q9v6) | Medium | ๐Ÿ“Œ Hard to spot if it is a Greedy. Very Important | |04| [406. Queue Reconstruction by Height](https://leetcode.com/problems/queue-reconstruction-by-height/)| [Python](https://tinyurl.com/wu6rdaw/406_Queue_Reconstruction_by_Height.py)| [Article 1](https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89345/Easy-concept-with-PythonC%2B%2BJava-Solution), [Article 2](https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89359/Explanation-of-the-neat-Sort%2BInsert-solution) | Medium | ๐Ÿ“Œ Fundamentals | |05| [621. Task Scheduler](https://leetcode.com/problems/task-scheduler/)| [Python](https://tinyurl.com/wu6rdaw/621_Task_Scheduler.py)| [Ex 1](https://leetcode.com/problems/task-scheduler/discuss/190390/Can-anyone-explain-to-me-what-the-problem-is-asking), [Ex 2](https://leetcode.com/problems/task-scheduler/discuss/130786/Python-solution-with-detailed-explanation), [Vid 1](https://www.youtube.com/watch?v=hVhOeaONg1Y), [Vid 2](https://www.youtube.com/watch?v=zPtI8q9gvX8), [Vid 3](https://www.youtube.com/watch?v=TV9VlHUR-Is), [Vid 4](https://www.youtube.com/watch?v=cr6Ip0J9izc&t=22s) | Medium | ๐Ÿ“Œ Extremely tricky. Classic problem | |06| [392. Is Subsequence](https://leetcode.com/problems/is-subsequence/)| [Python](https://tinyurl.com/wu6rdaw/392_Is_Subsequence.py)| [Ex 1](https://leetcode.com/problems/is-subsequence/discuss/87264/Easy-to-understand-binary-search-solution), [Ex 3](https://leetcode.com/problems/is-subsequence/discuss/87302/Binary-search-solution-for-follow-up-with-detailed-comments/144323) | Easy | ๐Ÿ“Œ | |07| **[55. Jump Game](https://leetcode.com/problems/jump-game/)** | [Python](https://tinyurl.com/wu6rdaw/55_Jump_Game.py)| **[Official](https://leetcode.com/articles/jump-game/)** , [Art 1](https://tinyurl.com/yy9vyjyn)| Medium | ๐Ÿ“Œ **Must Check. Learned a lot** | |08| [45. Jump Game II](https://leetcode.com/problems/jump-game-ii/)| [Python](https://tinyurl.com/wu6rdaw/45_Jump_Game_II.py)| **[educative.io](https://tinyurl.com/rqd5mls)**, [Vid 1](https://www.youtube.com/watch?v=cETfFsSTGJI), [Vid 2](https://www.youtube.com/watch?v=jH_5ypQggWg), [Vid 3](https://www.youtube.com/watch?v=vBdo7wtwlXs), [Art 1](https://tinyurl.com/yalsno6r) | Hard | ๐Ÿ“Œ | |09| [767. Reorganize String](https://leetcode.com/problems/reorganize-string/)| [Python](https://tinyurl.com/wu6rdaw/767_Reorganize_String.py)| --- | Medium | Also check Heap approach | |10| [435. Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)| [Python](https://tinyurl.com/wu6rdaw/435_Non-overlapping_Intervals.py)| [Vid 1](https://codinginterviewclass.com/courses/633601/lectures/12471331), [Art 1](https://tinyurl.com/yx5n7963) | Medium | Classic problem | |11| [57. Insert Interval](https://tinyurl.com/wzxrkd8)| [Python](https://tinyurl.com/wu6rdaw/57_Insert_Interval.py)| [Must](https://tinyurl.com/r9zk462) | Hard | Greedy and Merge interval | |12| [986. Interval List Intersections](https://tinyurl.com/wlw4rke)| [Python](https://tinyurl.com/wu6rdaw/986_Interval_List_Intersections.py), [Swift](https://tinyurl.com/wuja3c4/986_Interval_List_Intersections.swift.swift) | --- | Medium | Greedy and Two Pointer | |13| [252. Meeting Rooms](https://tinyurl.com/whmtgr7)| [Python](https://tinyurl.com/wu6rdaw/252_Meeting_Rooms.py)| [Official](https://leetcode.com/problems/meeting-rooms/solution/) | Easy | Greedy and uses heap | |14| [253. Meeting Rooms II](https://tinyurl.com/r8vr7qo)| [Python](https://tinyurl.com/wu6rdaw/253_Meeting_Rooms_II.py), [Swift](https://tinyurl.com/wuja3c4/253_Meeting_Rooms_II.swift.swift) | [Official](https://leetcode.com/problems/meeting-rooms-ii/solution/) | Medium | Greedy and uses heap | |15| [759. Employee Free Time](https://tinyurl.com/y5z73vre)| [Python](https://tinyurl.com/wu6rdaw/759_Employee_Free_Time.py)| [Educative.io](https://tinyurl.com/v42vmyr) | Hard | Greedy and uses heap. Not done. Check again | |16| [659. Split Array into Consecutive Subsequences](https://tinyurl.com/vsbddyl) | [Python](https://tinyurl.com/wu6rdaw/659_Split_Array_into_Consecutive_Subsequences.py)| [Art 0](https://tinyurl.com/qq5jucw), [Art 1](https://tinyurl.com/qk7m78s), [Art 2](https://tinyurl.com/sjkdtre), [Art 3](https://tinyurl.com/tnewgqa), **[Vid 1](https://tinyurl.com/u2hnq84)**, **[Art 4](https://tinyurl.com/w3j4yqp)** | Medium | ๐Ÿ“Œ It's a fucking unclear problem. TODO: Not done. Check again later | |17| **[68. Text Justification](https://tinyurl.com/r7bzsul)** | [Python](https://tinyurl.com/wu6rdaw/68_Text_Justification.py)| [Vid 1](https://tinyurl.com/jkx2usg), [Vid 2](https://tinyurl.com/wd7rja2), [Vid 3](https://tinyurl.com/qlbsfqf), [Art 0](https://tinyurl.com/u5r5cuy), [Art 1](https://tinyurl.com/s84dym2) | Hard | TODO: Check again later. Very Important | |18| **[134. Gas Station](https://tinyurl.com/skyh4lj)** | [Python](https://tinyurl.com/wu6rdaw/134_Gas_Station.py), [Python](https://tinyurl.com/wu6rdaw/134_Gas_Station.py), [Swift](https://tinyurl.com/wuja3c4/134_Gas_Station.swift) | [Vid 1](https://tinyurl.com/qq8xf4v), [Art 1](https://tinyurl.com/ss9sxju) | Medium | TODO: Check again later. Very Important | |19| [1288. Remove Covered Intervals](https://tinyurl.com/wc72tcx) | [Python](https://tinyurl.com/wu6rdaw/1288_Remove_Covered_Intervals.py)| [Art 1](https://tinyurl.com/vpp5hnx) | Medium | **Line Swap with Greedy**. A must read solution. A gold mie, learned a lot | |20| [1296. Divide Array in Sets of K Consecutive Numbers](https://tinyurl.com/ycfysu46) | [Python](https://tinyurl.com/wu6rdaw/1296_Divide_Array_in_Sets_of_K_Consecutive_Numbers.swift.py), [Swift](https://tinyurl.com/wuja3c4/1296_Divide_Array_in_Sets_of_K_Consecutive_Numbers.swift)| [Art 1](https://tinyurl.com/ybwhyztk) | Medium | --- | |21| [984. String Without AAA or BBB](https://tinyurl.com/yyqqp8m4) | [Python](https://tinyurl.com/wu6rdaw/984_String_Without_AAA_or_BBB.py), [Swift](https://tinyurl.com/wuja3c4/984_String_Without_AAA_or_BBB.swift)| [Art 1](https://tinyurl.com/y3wbhwgy) | Medium | --- | </p> </details> ### 16. [Dynamic Programming](https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews) **Follow [this](https://tinyurl.com/vmmaxbe) golden rule to approach any DP problem.** <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/submissions/)| [Python](https://tinyurl.com/wu6rdaw/53_Maximum_Subarray.py)| [Vid 1](https://tinyurl.com/wnjuna5), [Algoexpert.io](https://tinyurl.com/vqcznww) | Easy | Kadane's Algorithm | |02| [518. Coin Change 2](https://leetcode.com/problems/coin-change-2/)| [Python](https://tinyurl.com/wu6rdaw/518_Coin_Change_2.py)| **[educative.io](https://tinyurl.com/ro6das2)**, [Vid 1](https://tinyurl.com/wj5xxmw), [codinginterviewclass.com](https://tinyurl.com/urd4fg5), [Algoexpert.io](https://tinyurl.com/rv4r9e6) | Medium | Unbounded Knapsack | |03| [322. Coin Change](https://leetcode.com/problems/coin-change/solution/)| [Python](https://tinyurl.com/wu6rdaw/322_Coin_Change.py)| **[educative.io](https://tinyurl.com/w7t6jpo)**, [Vid 1](https://tinyurl.com/qlqrz6z), [Algoexpert.io](https://tinyurl.com/sv32o4z) | Medium | Unbounded Knapsack | |04| **[72. Edit Distance](https://leetcode.com/problems/edit-distance/)** | [Python](https://tinyurl.com/wu6rdaw/72_Edit_Distance.py)| **[educative.com](https://tinyurl.com/wzxp6ef)**, **[algoexpert.io](https://tinyurl.com/szk8rub)**, **[codinginterviewclass.com](https://tinyurl.com/rj6d8fm)**, [Vid 1](https://tinyurl.com/y6chhmm9), [Vid 2](https://tinyurl.com/y4a7ohay)| Hard | TODO: Check again. Very important and classic. Levenshtein Distance | |05| [70. Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)| [Python](https://tinyurl.com/wu6rdaw/70_Climbing_Stairs.py)| **[educative.io](https://tinyurl.com/rs9jfvd)** | Easy | Fibonacci sequence pattern | |06| [96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)| [Python](https://tinyurl.com/wu6rdaw/96_Unique_Binary_Search_Trees.py)| [educative.io](https://tinyurl.com/s9y9sya), [Vid 1](https://tinyurl.com/ut8wh4u), [Art 1](https://tinyurl.com/wuzpywc), [Vid 2](https://tinyurl.com/vb3s4jm), [Vis 3](https://tinyurl.com/uhet84g) | Medium | ๐Ÿ“Œ Fundamentals | |07| [95. Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)| [Python](https://tinyurl.com/wu6rdaw/95_Unique_Binary_Search_Trees_II.py)| [educative.io](https://tinyurl.com/s9y9sya) | Medium | --- | |08| [221. Maximal Square](https://leetcode.com/problems/maximal-square/)| [Python](https://tinyurl.com/wu6rdaw/221_Maximal_Square.py)| [Video 01](https://www.youtube.com/watch?v=_Lf1looyJMU), [Video 02](https://www.youtube.com/watch?v=FO7VXDfS8Gk)| |09| [85. Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/)| [Python](https://tinyurl.com/wu6rdaw/85_Maximal_Rectangle.py)| [Video 01](https://www.youtube.com/watch?v=g8bSdXCG-lA)| |10| [42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)| [Python](https://tinyurl.com/wu6rdaw/42_Trapping_Rain_Water.py)| [Article 01](https://leetcode.com/problems/trapping-rain-water/solution/)| Hard | ๐Ÿ“Œ Check stack and 2 pointers based solutions | |11| [300. Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)| [Python](https://tinyurl.com/wu6rdaw/300_Longest_Increasing_Subsequence.py)| [educative.io](https://tinyurl.com/vcskq2n), [codinginterviewclass.com](https://tinyurl.com/yx477m32), [algoexpert.io](https://tinyurl.com/ydhxzrbb), [Vid 01](https://tinyurl.com/ufcrusx), [Vid 2](https://tinyurl.com/vldt7sd) | Medium | ๐Ÿ“Œ Need to check Binary Search approach, which is a lot harder | |12| [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/)| [Python](https://tinyurl.com/wu6rdaw/1143_Longest_Common_Subsequence.py)| [educative.io](https://tinyurl.com/qvv8dje), [algoexpert.io](https://tinyurl.com/vlkmx4c) | Medium | ๐Ÿ“Œ Classic DP | |13| [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)| [Python](https://tinyurl.com/wu6rdaw/5_Longest_Palindromic_Substring.py)| [educative.io](https://tinyurl.com/rwouqnc), [algoexpert.io](https://tinyurl.com/rdaxfyc), [Vid 1](https://tinyurl.com/sd7me6k) | Medium | ๐Ÿ“Œ Classic DP | |14| [1066. Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/)| [Python](https://tinyurl.com/wu6rdaw/1066_Campus_Bikes_II.py)| | Medium |๐Ÿ“Œ TODO: Backtracking solution is getting TLE. Solve it and implement it with DP also | |15| [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| [Python](https://tinyurl.com/wu6rdaw/121_Best_Time_to_Buy_and_Sell_Stock.py)| [Vid 1](https://codinginterviewclass.com/courses/coding-interview-class/lectures/12305111) | Easy | Fundamental | |16| [122. Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| [Python](https://tinyurl.com/wu6rdaw/122_Best_Time_to_Buy_and_Sell_Stock_II.py)| [Video 01](https://www.youtube.com/watch?v=blUwDD6JYaE)| Easy | More like Greedy | |17| [123. Best Time to Buy and Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| [Python](https://tinyurl.com/wu6rdaw/123_Best_Time_to_Buy_and_Sell_Stock_III.py)| **[Vid 1](https://www.youtube.com/watch?v=oDhu5uGq_ic&t=2s), [Vid 2](https://www.youtube.com/watch?v=Pw6lrYANjz4)** | Hard | Fundamental | |18| [188. Best Time to Buy and Sell Stock IV](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| [Python](https://tinyurl.com/wu6rdaw/188_Best_Time_to_Buy_and_Sell_Stock_IV.py)| **[Vid 1](https://www.youtube.com/watch?v=oDhu5uGq_ic&t=2s), [Vid 2](https://www.youtube.com/watch?v=Pw6lrYANjz4)** | Hard | **Getting "Memory Limit Exceeded"** | |19| **[309. Best Time to Buy and Sell Stock with Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)**| [Python](https://tinyurl.com/wu6rdaw/309_Best_Time_to_Buy_and_Sell_Stock_with_Cooldown.py)| **[Must](https://tinyurl.com/syuepe6)**, [Art0](https://tinyurl.com/vbzcm6z), [Art1](https://tinyurl.com/vtuga7r), **[Must 2](https://tinyurl.com/vgqsw89)** , [Art 2](https://tinyurl.com/y8uojzjl), [Art 3](https://tinyurl.com/ul95d62) | Medium | Very tricky, must check again. Couldn't solve | |20| [714. Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)| [Python](https://tinyurl.com/wu6rdaw/714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction_Fee.py)| **[Must Read](https://tinyurl.com/y7eaa7vk)** , [Art 2](https://tinyurl.com/wzawybe) | Medium | More like Greedy, but DP | |21| **[198. House Robber](https://leetcode.com/problems/house-robber/)**| [Python](https://tinyurl.com/wu6rdaw/198_House_Robber.py)| **[Must](https://tinyurl.com/vp9v27d)**, **[educative.io](https://tinyurl.com/srtvmra)** | Easy | A Gold Mine | |22| [213. House Robber II](https://leetcode.com/problems/house-robber-ii/)| [Python](https://tinyurl.com/wu6rdaw/213_House_Robber_II.py)| [Art 1](https://tinyurl.com/wwza8d5), [Art 2](https://tinyurl.com/qtqwcl4) | Medium | --- | |23| [337. House Robber III](https://leetcode.com/problems/house-robber-iii/)| [Python](https://tinyurl.com/wu6rdaw/337_House_Robber_III.py)| **[Art 1](https://tinyurl.com/yd8zjvvj)** | Medium | **[Another gold mine](https://tinyurl.com/yd8zjvvj)**, hidden greedy and DFS | |24| **[416. Partition Equal Subset Sum](https://tinyurl.com/rmf5upz)** | [Python](https://tinyurl.com/wu6rdaw/416_Partition_Equal_Subset_Sum.py)| **[educative.io](https://tinyurl.com/wpxxyjy)**, [Art 1](https://tinyurl.com/we99l2n), [Vid 1](https://tinyurl.com/vvtavaw), [Vid 2](https://tinyurl.com/wabhu46), [Vid 3](https://tinyurl.com/sk89wa3), [Vid 4](https://tinyurl.com/z352yjj) | Medium | **0/1 Knapsack**, Very important | |25| **[494. Target Sum](https://tinyurl.com/ro8wdkz)** | [Python](https://tinyurl.com/wu6rdaw/494_Target_Sum.py)| **[educative.io](https://tinyurl.com/wfhzh29)**, **[MUST MUST READ](https://tinyurl.com/vmmaxbe)** | Medium | **0/1 Knapsack**, Very important. TODO: Not DOne. Check again | |26| **[343. Integer Break](https://tinyurl.com/qsmmtc3)** | [Python](https://tinyurl.com/wu6rdaw/343_Integer_Break.py)| **[Art 1](https://tinyurl.com/wfhzh29)**, **[Art 2](https://tinyurl.com/t2rky7o)** | Medium | **Unbounded Knapsack**. TODO: Not Done. Check again | |27| **[516. Longest Palindromic Subsequence](https://tinyurl.com/r7rege5)** | [Python](https://tinyurl.com/wu6rdaw/516_Longest_Palindromic_Subsequence.py)| **[educative.io](https://tinyurl.com/rvh2x2v)**, **[Vid 1](https://tinyurl.com/vjodfau)**, [Vid 2](https://tinyurl.com/uob2dhd) | Medium | --- | |28| [647. Palindromic Substrings](https://tinyurl.com/qw3blls) | [Python](https://tinyurl.com/wu6rdaw/647_Palindromic_Substrings.py)| **[educative.io](https://tinyurl.com/wbc4eqb)** | Medium | --- | |29| [680. Valid Palindrome II](https://tinyurl.com/rcdbykq) | [Python](https://tinyurl.com/wu6rdaw/680_Valid_Palindrome_II.py)| **[educative.io](https://tinyurl.com/vehzweg)**, [Art 1](https://tinyurl.com/twetoqk), [Art 2](https://tinyurl.com/wve6da4) | Medium | --- | |30| [1312. Minimum Insertion Steps to Make a String Palindrome](https://tinyurl.com/rhzxwa6) | [Python](https://tinyurl.com/wu6rdaw/1312_Minimum_Insertion_Steps_to_Make_a_String_Palindrome.py)| **[educative.io](https://tinyurl.com/vehzweg)** | Hard | --- | |31| **[132. Palindrome Partitioning II](https://tinyurl.com/t2rqddx)** | [Python](https://tinyurl.com/wu6rdaw/132_Palindrome_Partitioning_II.py)| **[educative.io](https://tinyurl.com/ruuewtc)**, [algoexpert.io](https://tinyurl.com/u4l4zdk), [Vid 1](https://tinyurl.com/rkq7lbu), [Vid 2](https://tinyurl.com/t9cgysf) | Hard | TODO: Check again. Very difficult and important | |32| **[718. Maximum Length of Repeated Subarray](https://tinyurl.com/t5ykzen)** | [Python](https://tinyurl.com/wu6rdaw/718_Maximum_Length_of_Repeated_Subarray.py)| **[educative.io](https://tinyurl.com/teew37b)** | Medium | **Longest Common Substring** variation | |33| [583. Delete Operation for Two Strings](https://tinyurl.com/wlzmbfn) | [Python](https://tinyurl.com/wu6rdaw/583_Delete_Operation_for_Two_Strings.py)| **[educative.io](https://tinyurl.com/wy357cz)** | Medium | --- | |34| [1092. Shortest Common Supersequence](https://tinyurl.com/qlpc52j) | [Python](https://tinyurl.com/wu6rdaw/1092_Shortest_Common_Supersequence.py)| **[educative.io](https://tinyurl.com/qmro98q)**, [Art 1](https://tinyurl.com/t87jfgg) | Hard | TODO: Not Done | |35| [115. Distinct Subsequences](https://tinyurl.com/gudjxts) | [Python](https://tinyurl.com/wu6rdaw/115_Distinct_Subsequences.py)| **[educative.io](https://tinyurl.com/yx6s5c4m)** | Hard | TODO: Check again | |36| **[97. Interleaving String](https://tinyurl.com/qmp8yn5)** | [Python](https://tinyurl.com/wu6rdaw/97_Interleaving_String.py)| **[educative.io](https://tinyurl.com/uzbogsf)**, [Vid 1](https://tinyurl.com/wlmpvjo) | Hard | TODO: Check again. Very difficult and tricky to understand | |37| [1048. Longest String Chain](https://tinyurl.com/uvb5v6s) | [Python](https://tinyurl.com/wu6rdaw/1048_Longest_String_Chain.py)| [Art 1](https://tinyurl.com/tcslm9l) | Medium | Modified LIS | |38| **[801. Minimum Swaps To Make Sequences Increasing](https://tinyurl.com/rvtcyvb)** | [Python](https://tinyurl.com/wu6rdaw/801_Minimum_Swaps_To_Make_Sequences_Increasing.py)| [Art 1](https://tinyurl.com/tzx7wpv), [Art 2](https://tinyurl.com/ugybcmz) | Medium | TODO: Check again. Very analytical and tricky to come up with | |39| **[279. Perfect Squares](https://tinyurl.com/jcjc6kf)** | [Python](https://tinyurl.com/wu6rdaw/279_Perfect_Squares.py)| **[Must](https://tinyurl.com/raomm4y)**, [Vid 1](https://tinyurl.com/rxpaqe8), [Vis 2](https://tinyurl.com/uevqohx) | Medium | TODO: Check again. Very Important. Very analytical and tricky to come up with | |40| **[139. Word Break](https://tinyurl.com/yyyy9dqz)** | [Python](https://tinyurl.com/wu6rdaw/139_Word_Break.py)| **[Must](https://tinyurl.com/sdzmo32)**, [Vid 1](https://tinyurl.com/s4hvakw), [Vis 2](https://tinyurl.com/rjwjanc), [Vid 3](https://tinyurl.com/rdxmwwg) | Medium | TODO: Check again. Very Important. | |41| **[62. Unique Paths](https://tinyurl.com/j8xmh7u)** | [Python](https://tinyurl.com/wu6rdaw/62_Unique_Paths.py), [Swift](https://tinyurl.com/wuja3c4/62_Unique_Paths.swift)| **[Vid 1](https://tinyurl.com/wp6vsqq)**, [Art 1](https://tinyurl.com/roammlg), [Art 2](https://tinyurl.com/tt5fpjk) | Medium | TODO: Check again | |42| **[152. Maximum Product Subarray](https://tinyurl.com/rxbfx5k)** | [Python](https://tinyurl.com/wu6rdaw/152_Maximum_Product_Subarray.py), [Swift](https://tinyurl.com/wuja3c4/152_Maximum_Product_Subarray.swift)| **[Vid 1](https://tinyurl.com/t24rc22)**, [Art 1](https://tinyurl.com/uzdpw4k) | Medium | Kadane's algorithm on multiplication | |43| **[64. Minimum Path Sum](https://tinyurl.com/ugnoql2)** | [Python](https://tinyurl.com/wu6rdaw/64_Minimum_Path_Sum.py), [Swift](https://tinyurl.com/wuja3c4/64_Minimum_Path_Sum.swift)| --- | Medium | --- | |44| **[91. Decode Ways](https://tinyurl.com/t5yx86t)** | [Python](https://tinyurl.com/wu6rdaw/91_Decode_Ways.py), [Swift](https://tinyurl.com/wuja3c4/91_Decode_Ways.swift)| [Vid 1](https://tinyurl.com/wxc7jlj) | Medium | --- | |45| **[975. Odd Even Jump](https://tinyurl.com/y5ovyklj)** | [Python](https://tinyurl.com/wu6rdaw/975_Odd_Even_Jump.py), [Swift](https://tinyurl.com/wuja3c4/975_Odd_Even_Jump.swift)| [Vid 1](https://tinyurl.com/vxyed3g), **[Art 1](https://tinyurl.com/wbjrnyt)** | Hard | DP using stack. Vary tricky and Interesting problem, loved it | |46| **[562. Longest Line of Consecutive One in Matrix](https://tinyurl.com/u2fb4a6)** | [Python](https://tinyurl.com/wu6rdaw/562_Longest_Line_of_Consecutive_One_in_Matrix.py), [Swift](https://tinyurl.com/wuja3c4/562_Longest_Line_of_Consecutive_One_in_Matrix.swift)| [Art 1](https://tinyurl.com/vqppbae), [Art 2](https://tinyurl.com/t3xtfq8) | Medium | | |47| **[552. Student Attendance Record II](https://tinyurl.com/tnxj5oa)** | [Python](https://tinyurl.com/wu6rdaw/552_Student_Attendance_Record_II.py), [Swift](https://tinyurl.com/wuja3c4/552_Student_Attendance_Record_II.swift)| [Art 1](https://tinyurl.com/rdt2cgr), [Art 2](https://tinyurl.com/s8okmdb), [Art 3](https://tinyurl.com/uhggppt) | Hard | **This is a FUCKING difficult DP problem. Don't dare to solve it** | |48| **[1320. Minimum Distance to Type a Word Using Two Fingers](https://tinyurl.com/ur876a6)** | [Python](https://tinyurl.com/wu6rdaw/1320_Minimum_Distance_to_Type_a_Word_Using_Two_Fingers.py), [Swift](https://tinyurl.com/wuja3c4/1320_Minimum_Distance_to_Type_a_Word_Using_Two_Fingers.swift)| [Vid 1](https://tinyurl.com/u5fcb3z), [Art 1](https://tinyurl.com/w386adm), [Art 2](https://tinyurl.com/rnkbhp3), [Art 3](https://tinyurl.com/tqwgraz), [Art 4](https://tinyurl.com/v46fuzm) | Hard | **Important. TODO: Check again** | |49| **[688. Knight Probability in Chessboard](https://tinyurl.com/y8qgukyr)** | [Python](https://tinyurl.com/wu6rdaw/688_Knight_Probability_in_Chessboard.py), [Swift](https://tinyurl.com/wuja3c4/688_Knight_Probability_in_Chessboard.swift)| [Art 1](https://tinyurl.com/ycfu5ux4), [Art 2](https://tinyurl.com/y987zy5g), [Art 3](https://tinyurl.com/ybtv5p5m) | Medium(Really!) | **Important, and fucking difficult. TODO: Check again** | |50| **[140. Word Break II](https://tinyurl.com/yb9yotou)** | [Python](https://tinyurl.com/wu6rdaw/140_Word_Break_II.py), [Swift](https://tinyurl.com/wuja3c4/140_Word_Break_II.swift)| [Art 1](https://tinyurl.com/yc9jvbpl), [Art 2](https://tinyurl.com/yaa7b7lu) | Hard | **OHH Boy, you must recheck this, Important. TODO: Check again. An unique combination of DP, DFS and Backtracking** | |51| **[1027. Longest Arithmetic Sequence](https://tinyurl.com/y7w7mmfn)** | [Python](https://tinyurl.com/wu6rdaw/1027_Longest_Arithmetic_Sequence.py), [Swift](https://tinyurl.com/wuja3c4/1027_Longest_Arithmetic_Sequence.swift)| [Art 1](https://tinyurl.com/ycto2x5o), [Art 2](https://tinyurl.com/yab7byj5) | Medium | **I didn't know that map can be used in 1d bottom-up dp. learned new things** | |52| **[304. Range Sum Query 2D - Immutable](https://tinyurl.com/ybhblo57)** | [Python](https://tinyurl.com/wu6rdaw/304_Range_Sum_Query_2D_Immutable.py), [Swift](https://tinyurl.com/wuja3c4/304_Range_Sum_Query_2D_Immutable.swift)| [Art 1](https://tinyurl.com/ycto2x5o), [Art 2](https://tinyurl.com/yab7byj5) | Medium | **very good question, classical** | |53| **[1477. Find Two Non-overlapping Sub-arrays Each With Target Sum](https://tinyurl.com/ybte7ydl)** | [Python](https://tinyurl.com/wu6rdaw/1477_Find_Two_Non_overlapping_Sub_arrays_Each_With_Target_Sum.py), [Swift](https://tinyurl.com/wuja3c4/1477_Find_Two_Non_overlapping_Sub_arrays_Each_With_Target_Sum.swift)| [Art 1](https://tinyurl.com/y7rshs2j), [Art 2](https://tinyurl.com/y8x7cgxl) | Medium | **Very interesting and deceiving and tricky problem. An unique combination of sliding window and DP** | |54| **[368. Largest Divisible Subset](https://tinyurl.com/ya8sv5jr)** | [Python](https://tinyurl.com/wu6rdaw/368_Largest_Divisible_Subset.py), [Swift](https://tinyurl.com/wuja3c4/368_Largest_Divisible_Subset.swift)| Official Solution | Medium | **Interesting problem.** | |55| **[523. Continuous Subarray Sum](https://tinyurl.com/y6ce49ln)** | [Python](https://tinyurl.com/wu6rdaw/523_Continuous_Subarray_Sum.py), [Swift](https://tinyurl.com/wuja3c4/523_Continuous_Subarray_Sum.swift)| **[Art 1](https://tinyurl.com/yb3ya47s)** | Medium | **Tricky to see the DP** | |56| **[689. Maximum Sum of 3 Non-Overlapping Subarrays](https://tinyurl.com/y9nlm8tg)** | [Python](https://tinyurl.com/wu6rdaw/689_Maximum_Sum_of_3_Non_Overlapping_Subarrays.py), [Swift](https://tinyurl.com/wuja3c4/689_Maximum_Sum_of_3_Non_Overlapping_Subarrays.swift)| **[Art 1](https://tinyurl.com/__)** | Hard | **Mainly, tricly array index manipulation. TODO: need to solve it in DP and sliding window approach** | |57| **[338. Counting Bits](https://tinyurl.com/y5ly38nj)** | [Python](https://tinyurl.com/wu6rdaw/338_Counting_Bits.py), [Swift](https://tinyurl.com/wuja3c4/338_Counting_Bits.swift)| | Medium | --- | |58| **[1269. Number of Ways to Stay in the Same Place After Some Steps](https://tinyurl.com/y43jo8j3)** | [Python](https://tinyurl.com/wu6rdaw/1269_Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.py), [Swift](https://tinyurl.com/wuja3c4/1269_Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.swift)| [Art 1](https://tinyurl.com/yynv9xe2) | Hard | Loved the problem. Very versatile | |59| **[1277. Count Square Submatrices with All Ones](https://tinyurl.com/y6a82a9r)** | [Python](https://tinyurl.com/wu6rdaw/1277_Count_Square_Submatrices_with_All_Ones.py), [Swift](https://tinyurl.com/wuja3c4/1277_Count_Square_Submatrices_with_All_Ones.swift)| [Must](https://tinyurl.com/y4sa8zgk) | Medium | --- | |60| [418. Sentence Screen Fitting](https://tinyurl.com/yhtu7lld) | [Swift](https://tinyurl.com/wuja3c4/418_Sentence_Screen_Fitting.swift)| [Art 1](https://tinyurl.com/yh4xt84c) | Medium | --- | |61| [1937. Maximum Number of Points with Cost](https://tinyurl.com/yhh6dmeh) | [Swift](https://tinyurl.com/wuja3c4/1937_Maximum_Number_of_Points_with_Cost.swift)| [Art 1](https://tinyurl.com/yg6hs4md) | Medium | --- | |62| [63. Unique Paths II](https://tinyurl.com/yjh69kzh) | [Swift](https://tinyurl.com/wuja3c4/63_Unique_Paths_II.swift)| --- | Medium | --- | |63| [218. Longest Arithmetic Subsequence of Given Difference](https://tinyurl.com/yh8chvky) | [Swift](https://tinyurl.com/wuja3c4/218_Longest_Arithmetic_Subsequence_of_Given_Difference.swift)| [Art 1](https://tinyurl.com/yf6vygcp) | Medium | --- | </p> </details> ### 17. Bit Manipulation **Follow [this](https://tinyurl.com/vmmaxbe) golden rule to approach any DP problem.** <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [78. Subsets](https://leetcode.com/problems/subsets/)| [Python](https://tinyurl.com/wu6rdaw/78_Subsets.py)| [Video 1](https://www.youtube.com/results?search_query=All+Subsets+of+a+Set), [Video 2](https://www.youtube.com/watch?v=MsHFNGltIxw), [Video 3](https://www.youtube.com/watch?v=xTNFs5KRV_g) | Medium |๐Ÿ“Œ TODO: code it in all 4 ways. First complete DFS, BFS, Bit Manipulation and some easy back tracking problem. โญ ๐Ÿ˜ญ Didn't understand, check again | |02| [187. Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/)| [Python](https://tinyurl.com/wu6rdaw/187_Repeated_DNA_Sequences.py)| [Official](https://leetcode.com/problems/repeated-dna-sequences/solution/) | Medium | โญ ๐Ÿ˜ญ Didn't understand, check again | |03| [461. Hamming Distance](https://leetcode.com/problems/hamming-distance/)| [Python](https://tinyurl.com/wu6rdaw/461_Hamming_Distance.py)| --- | Easy |๐Ÿ“Œ The key here is to practice bit operation, i ignore any other attempts | |04| [371. Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)| [Python](https://tinyurl.com/wu6rdaw/371_Sum_of_Two_Integers.py)| [Video 1](https://www.youtube.com/watch?v=qq64FrA2UXQ), [Atricle 1](https://leetcode.com/problems/sum-of-two-integers/discuss/132479/Simple-explanation-on-how-to-arrive-at-the-solution) | Easy |๐Ÿ“Œ The key here is to practice bit operation, i ignore any other attempts | |05| [169. Majority Element](https://leetcode.com/problems/majority-element/)| [Python](https://tinyurl.com/wu6rdaw/169_Majority_Element.py)| [Atricle 1](https://www.geeksforgeeks.org/find-the-majority-element-set-3-bit-magic/) | Easy |๐Ÿ“Œ The key here is to practice bit operation, i ignore any other attempts | |06| [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)| [Python](https://tinyurl.com/wu6rdaw/191_Number_of_1_Bits.py)| [Article 1](https://leetcode.com/problems/number-of-1-bits/discuss/55106/Python-2-solutions.-One-naive-solution-with-built-in-functions.-One-trick-with-bit-operation) | Easy |๐Ÿ“Œ The key here is to practice bit operation | |07| [268. Missing Number](https://leetcode.com/problems/missing-number/)| [Python](https://tinyurl.com/wu6rdaw/268_Missing_Number.py)| [Educative.io](https://tinyurl.com/uefnn3a), [Official](https://leetcode.com/problems/missing-number/solution/) | Easy | ๐Ÿ“Œ Learned few very important binary logic properties. Also check cyclic sort technique | |08| [389. Find the Difference](https://leetcode.com/problems/find-the-difference/)| [Python](https://tinyurl.com/wu6rdaw/389_Find_the_Difference.py)| --- | Easy | ๐Ÿ“Œ | |09| [231. Power of Two](https://leetcode.com/problems/power-of-two/)| [Python](https://tinyurl.com/wu6rdaw/231_Power_of_Two.py)| [Official](https://leetcode.com/problems/power-of-two/solution/), [Signed number representations](https://en.wikipedia.org/wiki/Signed_number_representations) | Easy | ๐Ÿ“Œ Learned few very important binary logic properties | |10| [136. Single Number](https://leetcode.com/problems/single-number/)| [Python](https://tinyurl.com/wu6rdaw/136_Single_Number.py)| [Educative.io](https://tinyurl.com/rzkypbg) | Easy |๐Ÿ“Œ The key here is to practice bit operation, i ignore any other attempts | |11| [137. Single Number II](https://tinyurl.com/oxtpdeg)| [Python](https://tinyurl.com/wu6rdaw/137_Single_Number_II.py)| [1](https://leetcode.com/problems/single-number-ii/discuss/43302/Accepted-code-with-proper-Explaination.-Does-anyone-have-a-better-idea), [2](https://medium.com/@lenchen/leetcode-137-single-number-ii-31af98b0f462), [3](https://leetcode.com/problems/single-number-ii/discuss/43294/Challenge-me-thx/176039), Check discussion | Medium | โญ ๐Ÿ˜ญ Didn't understand, check again | |12| [260. Single Number III](https://tinyurl.com/y4hgvu2y)| [Python](https://tinyurl.com/wu6rdaw/260_Single_Number_III.py)| **[Educative.io](https://tinyurl.com/tdhj9eh)** | Medium | โญ Check again, very important | |13| [476. Number Complement](https://tinyurl.com/tadg5uf)| [Python](https://tinyurl.com/wu6rdaw/476_Number_Complement.py)| **[Educative.io](https://tinyurl.com/ucwmq5n)** | Easy | โญ Check again | |14| [832. Flipping an Image](https://tinyurl.com/uog7h9f)| [Python](https://tinyurl.com/wu6rdaw/832_Flipping_an_Image.py)| **[Educative.io](https://tinyurl.com/wyd8c4g)** | Easy | โญ Check again | |15| [67. Add Binary](https://tinyurl.com/y6hbtal7)| [Python](https://tinyurl.com/wu6rdaw/67_Add_Binary.py), [Swift](https://tinyurl.com/wuja3c4/67_Add_Binary.swift) | **[Official](https://tinyurl.com/y7w7ry8e)**, [Art 1](https://tinyurl.com/yaxg48ag), [Art 2](https://tinyurl.com/y77e2ylc), [Vid 1](https://www.youtube.com/watch?v=NLKQEOgBAnw), [Vid 2](https://www.youtube.com/watch?v=qq64FrA2UXQ&feature=emb_title) | Easy (FUCK NO) | โญ Check again | </p> </details> ### 18. Miscellaneous ([Line Swap](https://tinyurl.com/yx5pwdao), [Binary Indexed Tree](), [Segment Tree](https://tinyurl.com/w6jxpcg), [Minimax](https://tinyurl.com/twgbp6n), [Math](https://tinyurl.com/wb2h2mo), AVL Tree, Red-Black Tree, Interval Tree etc) <details><summary>Leetcode problems with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| **[218. The Skyline Problem](https://tinyurl.com/y8om73ah)** | [Python](https://tinyurl.com/wu6rdaw/218_The_Skyline_Problem.py), [Swift](https://tinyurl.com/wuja3c4/218_The_Skyline_Problem.swift)| [Vid 1](https://tinyurl.com/ryu2f5u), [Vid 2](https://tinyurl.com/rae83uz), [Vid 3](https://tinyurl.com/scmrjke), [Vid 4](https://tinyurl.com/vv5pjdz), [Art 1](https://tinyurl.com/nxotn8v) | Hard | TODO: Not Done. Very important. | |02| **[375. Guess Number Higher or Lower II](https://tinyurl.com/y6ywak9n)** | [Python](https://tinyurl.com/wu6rdaw/375_Guess_Number_Higher_or_Lower_II.py), [Swift](https://tinyurl.com/wuja3c4/375_Guess_Number_Higher_or_Lower_II.swift)| [Art 0](https://tinyurl.com/y888xrkm), [Art 1](https://tinyurl.com/oaqgkp9), [Art2 2](https://tinyurl.com/vpu9gt2), [Art 3](https://tinyurl.com/rpr83um) | Hard | TODO: Not Done. Very important. Did't understand properly | |03| **[843. Guess the Word](https://tinyurl.com/vyk9ynp)** | [Python](https://tinyurl.com/wu6rdaw/843_Guess_the_Word.py)| **[Art 1](https://tinyurl.com/wqy5ll4)** | Hard | **Minimax**. TODO: Check again. Very important and interesting | |04| [593. Valid Square](https://tinyurl.com/rr2z8l7) | [Python](https://tinyurl.com/wu6rdaw/593_Valid_Square.py)| [Art 1](https://tinyurl.com/w7gucmn), [Art 2](https://tinyurl.com/qlw7tn4) | Medium | **Math** | |05| [1272. Remove Interval](https://tinyurl.com/syvucrt) | [Python](https://tinyurl.com/wu6rdaw/1272_Remove_Interval.py)| [Art 1](https://tinyurl.com/srv4knp) | Medium | **Line Swap** | |06| **[1288. Remove Covered Intervals](https://tinyurl.com/wc72tcx)** | [Python](https://tinyurl.com/wu6rdaw/1288_Remove_Covered_Intervals.py)| [Art 1](https://tinyurl.com/vpp5hnx) | Medium | **Line Swap with Greedy**. A must read solution. A gold mie, learned a lot | |07| **[1229. Meeting Scheduler](https://tinyurl.com/t6vtlph)** | [Python](https://tinyurl.com/wu6rdaw/1229_Meeting_Scheduler.py)| [Art 1](https://tinyurl.com/rau4xcb) | Medium | **Line Swap**, learned a lot | |08| **[850. Rectangle Area II](https://tinyurl.com/utc58vb)** | [Python](https://tinyurl.com/wu6rdaw/850_Rectangle_Area_II.py)| [Art 1](https://tinyurl.com/t59zg3e), [Vid 1](https://tinyurl.com/sumo5b6), [Art 2](https://tinyurl.com/s27k9o4) | Hard | **Line Swap using heap and Segment Tree**. TODO: Solve it using Segment Tree | |09| **[307. Range Sum Query - Mutable](https://tinyurl.com/utc58vb)** | [Python](https://tinyurl.com/wu6rdaw/307_Range_Sum_Query_-_Mutable.py)| **[Vid 1](https://tinyurl.com/sumo5b6), [Art 1](https://tinyurl.com/r54yf9y), [Art 2](https://tinyurl.com/srucx8l)** | Medium | **Segment Tree Basics**. Very Important | |10| **[327. Count of Range Sum](https://tinyurl.com/ulofnqj)** | [Python](https://tinyurl.com/wu6rdaw/327_Count_of_Range_Sum.py)| **[Vid 1](https://tinyurl.com/sumo5b6), [Art 1](https://tinyurl.com/rlmha9k), [Art 2](https://tinyurl.com/qlqod4c)** | Hard | **Segment Tree Basics**. Very Important | |11| **[239. Sliding Window Maximum](https://tinyurl.com/rvhujl5)** | [Python](https://tinyurl.com/wu6rdaw/239_Sliding_Window_Maximum.py)| **[Video 1](https://tinyurl.com/v767bl3)**, [Official](https://tinyurl.com/www4np2), [Art 1](https://tinyurl.com/y8nbroux), [Art 2](https://tinyurl.com/s62fzls), **[Art 3](https://tinyurl.com/vd3dtch)**, **[Art 4](https://tinyurl.com/yx3sjp46)** | Hard | ๐Ÿ“Œ Here, I have specifically focused on solving it with AVL and Red-Black Tree. A "Queue" approach can be found o Queue section | |12| **[398. Random Pick Index](https://tinyurl.com/ydf3t2ke)** | [Python](https://tinyurl.com/wu6rdaw/398_Random_Pick_Index.py)| **[Video 1](https://tinyurl.com/ycjk3gk6)**, [Art 1](https://tinyurl.com/ych82hfp), [Art 2](https://tinyurl.com/y8hogyty), [Art 3](https://tinyurl.com/y7slu8x2), [Art 4](https://tinyurl.com/y896sqmt), [Art 5](https://tinyurl.com/yafb3esf) | Medium (Really!!??) | ๐Ÿ“Œ **Reservoir sampling**, What's the point of asking this into an interview!!?? | |13| **[319. Bulb Switcher](https://tinyurl.com/ycygg2ju)** | [Python](https://tinyurl.com/wu6rdaw/319_Bulb_Switcher.py)| [Art 1](https://tinyurl.com/y886rzfe), [Art 2](https://tinyurl.com/y9n7vo2x), [Art 3](https://tinyurl.com/ya3fookw) | Medium (Really!!??) | Are you fucking kidding me!! We are programmers, not math wizard. | |14| **[1344. Angle Between Hands of a Clock](https://tinyurl.com/yy3g8mg6)** | [Python](https://tinyurl.com/wu6rdaw/1344_Angle_Between_Hands_of_a_Clock.py), [Swift](https://tinyurl.com/wuja3c4/1344_Angle_Between_Hands_of_a_Clock.swift)| --- | Medium | FB really likes to ask tricky question. | |15| **[1276. Number of Burgers with No Waste of Ingredients](https://tinyurl.com/y4dl7mne)** | [Python](https://tinyurl.com/wu6rdaw/1276_Number_of_Burgers_with_No_Waste_of_Ingredients.py), [Swift](https://tinyurl.com/wuja3c4/1276_Number_of_Burgers_with_No_Waste_of_Ingredients.swift)| [Art 1](https://tinyurl.com/y2u668aa), [Art 2](https://tinyurl.com/y2u9nvre), [Art 3](https://tinyurl.com/yxdzbp9s) | Medium | Pure math | |16| **[777. Swap Adjacent in LR String](https://tinyurl.com/y2syu722)** | [Python](https://tinyurl.com/wu6rdaw/777_Swap_Adjacent_in_LR_String.py), [Swift](https://tinyurl.com/wuja3c4/777_Swap_Adjacent_in_LR_String.swift)| [Art 1](https://tinyurl.com/y6cfe8gy) | Medium | Brainteser | </p> </details> --- --- ## AlgoExpert <b>100 Problems</b> [My certificate of completion](https://certificate.algoexpert.io/AE-ea0a67c587) ### 1. Arrays <details><summary>Problem statement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Two_Number_Sum](algoexpert.io/questions/Two_Number_Sum.md)| [Swift](algoexpert.io/swift/Two_Number_Sum.swift), [Python](algoexpert.io/python/Two_Number_Sum.py)| |02| [Three_Number_Sum](algoexpert.io/questions/Three_Number_Sum.md) | [Python](algoexpert.io/python/Three_Number_Sum.py)| |03| [Smallest_Difference](algoexpert.io/questions/Smallest_Difference.md) | [Python](algoexpert.io/python/Smallest_Difference.py)| |04| [Four_Number_Sum](algoexpert.io/questions/Four_Number_Sum.md) | [Python](algoexpert.io/python/Four_Number_Sum.py) | |05| [Subarray_Sort](algoexpert.io/questions/Subarray_Sort.md) | [Python](algoexpert.io/python/Subarray_Sort.py) | |06| [Largest_Range](algoexpert.io/questions/Largest_Range.md) | [Python](algoexpert.io/python/Largest_Range.py) | |07| [Min_Rewards](algoexpert.io/questions/Min_Rewards.md) | [Python](algoexpert.io/python/Min_Rewards.py) | |08| [Zigzag_Traverse](algoexpert.io/questions/Zigzag_Traverse.md) | [Python](algoexpert.io/python/Zigzag_Traverse.py) | |08| [Apartment_Hunting](algoexpert.io/questions/Apartment_Hunting.md) | [Python](algoexpert.io/python/Apartment_Hunting.py) | |09| [Calendar_Matching](algoexpert.io/questions/Calendar_Matching.md) | [Python](algoexpert.io/python/Calendar_Matching.py) | |10| [Spiral_Traverse](algoexpert.io/questions/Spiral_Traverse.md) | [Python](algoexpert.io/python/Spiral_Traverse.py) | |11| [Monotonic_Array](algoexpert.io/questions/Monotonic_Array.md) | [Python](algoexpert.io/python/Monotonic_Array.py) | |12| [Move_Element_To_End](algoexpert.io/questions/Move_Element_To_End.md) | [Python](algoexpert.io/python/Move_Element_To_End.py) | |13| [Longest_Peak](algoexpert.io/questions/Longest_Peak.md) | [Python](algoexpert.io/python/Longest_Peak.py) | </p> </details> ### 2. Binary Search Tree <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [BST_Construction_Iterative](algoexpert.io/questions/BST_Construction_Iterative.md) | [Python](algoexpert.io/python/BST_Construction_Iterative.py)| |02| [BST_Construction_Recursive](algoexpert.io/questions/BST_Construction.md) | [Python](algoexpert.io/python/BST_Construction_Recursive.py)| |03| [Validate_BST](algoexpert.io/questions/Validate_BST.md) | [Python](algoexpert.io/python/Validate_BST.py)| |04| [Find_Closest_Value_in_BST](algoexpert.io/questions/Find_Closest_Value_In_BST.md) | [Python](algoexpert.io/python/Find_Closest_Value_in_BST.py)| |05| [BST_Traversal](algoexpert.io/questions/BST_Traversal.md) | [Python](algoexpert.io/python/BST_Traversal.py)| |06| [Same_BSTs](algoexpert.io/questions/Same_BSTs.md) | [Python](algoexpert.io/python/Same_BSTs.py)| </p> </details> ### 3. Binary Tree <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Invert_Binary_Tree](algoexpert.io/questions/Invert_Binary_Tree.md) | [Python](algoexpert.io/python/Invert_Binary_Tree.py)| |02| [Max_Path_Sum_In_Binary_Tree](algoexpert.io/questions/Max_Path_Sum_In_Binary_Tree.md) | [Python](algoexpert.io/python/Max_Path_Sum_In_Binary_Tree.py) | |03| [Iterative_In-order_Traversal](algoexpert.io/questions/Iterative_In-order_Traversal.md) | [Python](algoexpert.io/python/Iterative_In-order_Traversal.py) | |04| [Right_Sibling_Tree](algoexpert.io/questions/Right_Sibling_Tree.md) | [Python](algoexpert.io/python/Right_Sibling_Tree.py) | |05| [Branch_Sums](algoexpert.io/questions/Branch_Sums.md) | [Python](algoexpert.io/python/Branch_Sums.py) | |06| [Flatten_Binary_Tree](algoexpert.io/questions/Flatten_Binary_Tree.md) | [Python](algoexpert.io/python/Flatten_Binary_Tree.py) | </p> </details> ### 4. Dynamic Programming <details><summary>Problem statement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Number_Of_Ways_To_Make_Changes](algoexpert.io/questions/Number_Of_Ways_To_Make_Change.md) | [Python](algoexpert.io/python/Number_Of_Ways_To_Make_Changes.py)| |02| [Minimum_Number_Of_Coins_For_Change](algoexpert.io/questions/Min_Number_Of_Coins_For_Change.md) | [Python](algoexpert.io/python/Minimum_Number_Of_Coins_For_Change.py)| |03| [Levenshtein_Distance](algoexpert.io/questions/Levenshtein_Distance.md) | [Python](algoexpert.io/python/Levenshtein_Distance.py)| |04| [Min_Number_Of_Jumps](algoexpert.io/questions/Min_Number_Of_Jumps.md) | [Python](algoexpert.io/python/Min_Number_Of_Jumps.py) | [Video 1](https://www.youtube.com/watch?v=cETfFsSTGJI)| |05| [Max_Sum_Increasing_Subsequence](algoexpert.io/questions/Max_Sum_Increasing_Subsequence.md) | [Python](algoexpert.io/python/Max_Sum_Increasing_Subsequence.py) | |06| [Longest_Common_Subsequence](algoexpert.io/questions/Longest_Common_Subsequence.md) | [Python](algoexpert.io/python/Longest_Common_Subsequence.py) | [Video 1](https://www.youtube.com/watch?v=sSno9rV8Rhg) | |07| [Water_Area](algoexpert.io/questions/Water_Area.md) | [Python](algoexpert.io/python/Water_Area.py) | |08| [Knapsack_Problem](algoexpert.io/questions/Knapsack_Problem.md) | [Python](algoexpert.io/python/Knapsack_Problem.py) | |09| [Disk_Stacking](algoexpert.io/questions/Disk_Stacking.md) | [Python](algoexpert.io/python/Disk_Stacking.py) | |10| [Numbers_In_Pi](algoexpert.io/questions/Numbers_In_Pi.md) | [Python](algoexpert.io/python/Numbers_In_Pi.py) | |11| [Maximum_Subset_Sum_With_No_Adjacent_Element](algoexpert.io/questions/Maximum_Subset_Sum_With_No_Adjacent_Element.md) | [Python](algoexpert.io/python/Maximum_Subset_Sum_With_No_Adjacent_Element.py) | |12| [Max_Profit_With_K_Transactions](algoexpert.io/questions/Max_Profit_With_K_Transactions.md) | [Python](algoexpert.io/python/Max_Profit_With_K_Transactions.py) | |13| [Palindrome_Partitioning_Min_Cuts](algoexpert.io/questions/Palindrome_Partitioning_Min_Cuts.md) | [Python](algoexpert.io/python/Palindrome_Partitioning_Min_Cuts.py) | |14| [Longest_Increasing_Subsequence](algoexpert.io/questions/Longest_Increasing_Subsequence.md) | [Python](algoexpert.io/python/Longest_Increasing_Subsequence.py) | [Video 1](https://www.youtube.com/watch?v=fV-TF4OvZpk), [Video 2](https://www.youtube.com/watch?v=CE2b_-XfVDk), , [Video 3](https://www.hackerrank.com/challenges/longest-increasing-subsequent/problem)| |15| [Longest_String_Chain](algoexpert.io/questions/Longest_String_Chain.md) | [Python](algoexpert.io/python/Longest_String_Chain.py) | --- | </p> </details> ### 5. Famous Algorithm <details><summary>Problem statement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Kadane's_Algorithm](algoexpert.io/questions/Kadane's_Algorithm.md) | [Python](algoexpert.io/python/Kadane's_Algorithm.py)| |02| [Topological_Sort](algoexpert.io/questions/Topological_Sort.md) | [Python](algoexpert.io/python/Topological_Sort.py) | |03| [KMP_Algorithm](algoexpert.io/questions/KMP_Algorithm.md) | [Python](algoexpert.io/python/KMP_Algorithm.py) | </p> </details> ### 6. Graphs <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Youngest_Common_Ancestor](algoexpert.io/questions/Youngest_Common_Ancestor.md) | [Python](algoexpert.io/python/Youngest_Common_Ancestor.py)| |02| [Single_Cycle_Check](algoexpert.io/questions/Single_Cycle_Check.md) | [Python](algoexpert.io/python/Single_Cycle_Check.py)| |03| [River_Sizes](algoexpert.io/questions/River_Sizes.md) | [Python](algoexpert.io/python/River_Sizes.py)| |04| [Depth_First_Search](algoexpert.io/questions/Depth-first_Search.md) | [Python](algoexpert.io/python/Depth_First_Search.py)| |05| [Breadth_First_Search](algoexpert.io/questions/Breadth-first_Search.md) | [Python](algoexpert.io/python/Breadth_First_Search.py)| |06| [Boggle_Board](algoexpert.io/questions/Boggle_Board.md) | [Python](algoexpert.io/python/Boggle_Board.py) | |07| [Rectangle_Mania](algoexpert.io/questions/Rectangle_Mania.md) | [Python](algoexpert.io/python/Rectangle_Mania.py) | |07| [Airport_Connections](algoexpert.io/questions/Airport_Connections.md) | [Python](algoexpert.io/python/Airport_Connections.py) | </p> </details> ### 7. Heaps <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Min_Heap_Construction](algoexpert.io/questions/Min_Heap_Construction.md) | [Python](algoexpert.io/python/Min_Heap_Construction.py) |[Video 1](https://www.youtube.com/watch?v=HqPJF2L5h9U)| |02| [Continuous_Median](algoexpert.io/questions/Continuous_Median.md) | [Python](algoexpert.io/python/Continuous_Median.py) |[Video 1](https://www.youtube.com/watch?v=1CxyVdA_654), [Video 2](https://www.youtube.com/watch?v=VmogG01IjYc)| </p> </details> ### 8. Linked List <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Remove_Kth_Node_From_End](algoexpert.io/questions/Remove_Kth_Node_From_End.md) | [Python](algoexpert.io/python/Remove_Kth_Node_From_End.py)| |02| [Linked_List_Construction](algoexpert.io/questions/Linked_List_Construction.md) | [Python](algoexpert.io/python/Linked_List_Construction.py)| |03| [Find_Loop](algoexpert.io/questions/Find_Loop.md) | [Python](algoexpert.io/python/Find_Loop.py)| |04| [Reverse_Linked_List](algoexpert.io/questions/Reverse_Linked_List.md) | [Python](algoexpert.io/python/Reverse_Linked_List.py)| |05| [LRU_Cache](algoexpert.io/questions/LRU_Cache.md) | [Python](algoexpert.io/python/LRU_Cache.py)| |06| [Merge_Linked_List](algoexpert.io/questions/Merge_Linked_List.md) | [Python](algoexpert.io/python/Merge_Linked_List.py)| </p> </details> ### 9. Recursion <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Powerset](algoexpert.io/questions/Powerset.md) | [Python](algoexpert.io/python/Powerset.py)| |02| [Permutations](algoexpert.io/questions/Permutations.md) | [Python](algoexpert.io/python/Permutations.py)| |03| [Nth_Fibonacci](algoexpert.io/questions/Nth_Fibonacci.md) | [Python](algoexpert.io/python/Nth_Fibonacci.py)| |04| [Product_Sum](algoexpert.io/questions/Product_Sum.md) | [Python](algoexpert.io/python/Product_Sum.py) | |05| [Lowest_Common_Manager](algoexpert.io/questions/Lowest_Common_Manager.md) | [Python](algoexpert.io/python/Lowest_Common_Manager.py) | |06| [Number_Of_Possible_Binary_Tree_Topologies](algoexpert.io/questions/Number_Of_Binary_Tree_Topologies.md) | [Python](algoexpert.io/python/Number_Of_Possible_Binary_Tree_Topologies.py) | |07| [Interweaving_Strings](algoexpert.io/questions/Interweaving_Strings.md) | [Python](algoexpert.io/python/Interweaving_Strings.py) | |08| [Number_Of_Binary_Tree_Topologies](algoexpert.io/questions/Number_Of_Binary_Tree_Topologies.md) | [Python](algoexpert.io/python/Number_Of_Binary_Tree_Topologies.py) | </p> </details> ### 10. Searching <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Search_In_Sorted_Matrix](algoexpert.io/questions/Search_In_Sorted_Matrix.md) | [Python](algoexpert.io/python/Search_In_Sorted_Matrix.py)| |02| [Find_Three_Largest_Number](algoexpert.io/questions/Find_Three_Largest_Numbers.md) | [Python](algoexpert.io/python/Find_Three_Largest_Number.py)| |03| [Binary_Search](algoexpert.io/questions/Binary_Search.md) | [Python](algoexpert.io/python/Binary_Search.py)| |04| [Shifted_Binary_Search](algoexpert.io/questions/Shifted_Binary_Search.md) | [Python](algoexpert.io/python/Shifted_Binary_Search.py)| |05| [Search_For_Range](algoexpert.io/questions/Search_For_Range.md) | [Python](algoexpert.io/python/Search_For_Range.py)| |06| [Quick_Select (Kth smallest/largest element)](algoexpert.io/questions/Quick_Select.md) | [Python](algoexpert.io/python/Quick_Select.py)| </p> </details> ### 11. Sorting <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Selection_Sort](algoexpert.io/questions/Selection_Sort.md) | [Python](algoexpert.io/python/Selection_Sort.py)| |02| [Insertion_Sort](algoexpert.io/questions/Insertion_Sort.md) | [Python](algoexpert.io/python/Insertion_Sort.py)| |03| [Bubble_Sort](algoexpert.io/questions/Bubble_Sort.md) | [Python](algoexpert.io/python/Bubble_Sort.py)| |04| [Quick_Sort](algoexpert.io/questions/Quick_Sort.md) | [Python](algoexpert.io/python/Quick_Sort.py) | [Video 1](https://www.youtube.com/watch?v=uXBnyYuwPe8&t=302s)| |05| [Heap_Sort](algoexpert.io/questions/Heap_Sort.md) | [Python](algoexpert.io/python/Heap_Sort.py) | |06| [Merge_Sort](algoexpert.io/questions/Merge_Sort.md) | [Python](algoexpert.io/python/Merge_Sort.py) | </p> </details> ### 12. Stacks <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Balanced Bracket](algoexpert.io/questions/Balanced_Bracket.md)| [Python](algoexpert.io/python/Balanced_Bracket.py)| |02| [Min_Max_Stack_Construction](algoexpert.io/questions/Min_Max_Stack_Construction.md) | [Python](algoexpert.io/python/Min_Max_Stack_Construction.py)| </p> </details> ### 13. String <details><summary>Problem statement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Palindrom_Check](algoexpert.io/questions/Palindrome_Check.md) | [Python](algoexpert.io/python/Palindrom_Check.py)| |02| [Longest_Palindromic_Substring](algoexpert.io/questions/Longest_Palindromic_Substring.md) | [Python](algoexpert.io/python/Longest_Palindromic_Substring.py)| |03| [Caesar_Cipher_Encryptor](algoexpert.io/questions/Caesar_Cipher_Encryptor.md) | [Python](algoexpert.io/python/Caesar_Cipher_Encryptor.py)| |04| [Longest_Substring_Without_Duplication](algoexpert.io/questions/Longest_Substring_Without_Duplication.md) | [Python](algoexpert.io/python/Longest_Substring_Without_Duplication.py)| |05| [Underscorify_Substring](algoexpert.io/questions/Underscorify_Substring.md) | [Python](algoexpert.io/python/Underscorify_Substring.py)| --- | Hard | TODO: Check again. Difficult to analyse the space ad time complexity | |06| [Pattern_Matcher](algoexpert.io/questions/Pattern_Matcher.md) | [Python](algoexpert.io/python/Pattern_Matcher.py)| |07| [Smallest_Substring_Containing](algoexpert.io/questions/Smallest_Substring_Containing.md) | [Python](algoexpert.io/python/Smallest_Substring_Containing.py)| |08| [Group_Anagrams](algoexpert.io/questions/Group_Anagrams.md) | [Python](algoexpert.io/python/Group_Anagrams.py)| </p> </details> ### 14. Tries <details><summary>Problem sstatement from AlgoExpert.io with solutions and tutorials/videos</summary> <p> | # | Title | Solution | Tutorial | Level | Remarks | | --- | --- | --- | --- | --- | --- | |01| [Suffix_Trie_Construction](algoexpert.io/questions/Suffix_Trie_Construction.md) | [Python](algoexpert.io/python/Suffix_Trie_Construction.py)| |02| [Multi_String_Search](algoexpert.io/questions/Multi_String_Search.md) | [Python](algoexpert.io/python/Multi_String_Search.py)| </p> </details> --- --- ## References <details><summary>Some helpful links, channels, tutorials, blogs.</summary> <p> ### 1. Strategies <details><summary></summary> <p> Check this **[Golden](https://tinyurl.com/uboo399)** posts first. - **[Comprehensive Data Structure and Algorithm Study Guide](https://tinyurl.com/uboo399)** 01. [How a Googler solves coding problems](https://blog.usejournal.com/how-a-googler-solves-coding-problems-ec5d59e73ec5) 02. [Nail Every Coding Interview by Becoming Asymmetrical](https://www.youtube.com/watch?v=-THCaZWggTk) 03. [How to get into FAANG](https://drive.google.com/drive/u/0/folders/1sIdNzi4mOQL_YsPF4HAw-JsDtUneHKiu) 04. [Preparing for Programming interview with Python](https://tinyurl.com/qsqda4b) 05. [The 30-minute guide to rocking your next coding interview](https://tinyurl.com/vbqlhko) 06. [Google Interview Part-1](https://tinyurl.com/w62ou5j) , [Google Interview Part-2](https://tinyurl.com/u69s6pe), [Google Interview Part-3](https://tinyurl.com/urv95zu), [Final Part](https://tinyurl.com/y5qtujdv) 07. [Amazon เฆ“ Google เฆ เฆšเฆพเฆ•เฆฐเฆฟเฆฐ เฆธเงเฆฏเง‹เฆ— เฆชเฆพเฆ“เงŸเฆพเฆฐ เฆชเงเฆฐเฆธเงเฆคเงเฆคเฆฟ เฆชเฆฐเงเฆฌ](https://github.com/sabir4063/my_preparation) 08. [How to use LeetCode effectively](https://www.youtube.com/watch?v=iGFnsuMeUQY) 09. [How to solve ANY interview question](https://www.youtube.com/watch?v=JB78__e1tlE&t=3s) 10. [How To Ace The Google Coding Interview - Complete Guide](https://tinyurl.com/ws2d4cr) 11. [Software Engineering Interviews: The Golden Path To Passing](https://tinyurl.com/vb77j83) 12. [A MUST READ](https://tinyurl.com/vzbn34s) 13. [10 Steps to Solving a Programming Problem](https://tinyurl.com/s663j6z) 14. [Preparing to Apply or Interview at Google - Youtue playlist](https://tinyurl.com/yx7wceza) 15. [Amazon เฆ“ Google เฆ เฆšเฆพเฆ•เฆฐเฆฟเฆฐ เฆธเงเฆฏเง‹เฆ— เฆชเฆพเฆ“เงŸเฆพเฆฐ เฆชเงเฆฐเฆธเงเฆคเงเฆคเฆฟ เฆชเฆฐเงเฆฌ](https://tinyurl.com/t7dnzs8) 16. [Coding Interviews](https://tinyurl.com/rofaykt) 17. **[Tech Interview Handbook](https://tinyurl.com/rofaykt)** 18. [Complete Introduction to the 30 Most Essential Data Structures & Algorithms](https://tinyurl.com/y6e8klgj) 19. [How to Solve Any Code Challenge or Algorithm](https://tinyurl.com/y3staja5) </p> </details> ### 2. Courses/Books <details><summary></summary> <p> 01. [Data Structures in Python: An Interview Refresher](https://www.educative.io/courses/data-structures-in-python-an-interview-refresher) 02. [Grokking the Coding Interview: Patterns for Coding Questions](https://www.educative.io/courses/grokking-the-coding-interview) 03. [Grokking Dynamic Programming Patterns for Coding Interviews](https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews) 04. [Coding Interview Class](https://codinginterviewclass.com/) 05. [Competitive Programmerโ€™s Handbook](https://cses.fi/book/book.pdf) </p> </details> ### 3. Swift <details><summary></summary> <p> 01. []() </p> </details> ### 4. Python <details><summary></summary> <p> Learn the following modules by heart. Just knowing all of the following items will made most of the problem one-liners. 01. [itertools - Functions creating iterators for efficient looping](https://docs.python.org/3/library/itertools.html) - They will help you, more often than you think - [Iterators and Iterables - What Are They and How Do They Work?](https://www.youtube.com/watch?v=jTYiNjvnHZY) - [Itertools Module - Iterator Functions for Efficient Looping](https://www.youtube.com/watch?v=Qu3dThVy6KQ) 02. [collections - High-performance container datatypes](https://docs.python.org/3/library/collections.html) - Believe me, this is pretty awesome 03. [heapq - Heap queue algorithm](https://docs.python.org/3/library/heapq.html) - Obviously, we don't have to hand-code heaps anymore 04. [bisect - Array bisection algorithm](https://docs.python.org/3/library/bisect.html) - Binary Search, simplified 05. [Set](https://docs.python.org/3/library/stdtypes.html#set) 06. [Dict](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) - Now on, hash Tables are fun to work with 07. [Sorting](https://wiki.python.org/moin/HowTo/Sorting) - Don't participate in competitions without reading this completely. 08. Start using lambda extensively - [Lambda Expressions & Anonymous Functions](https://tinyurl.com/t9aptuz) - [Map, Filter, and Reduce Functions](https://tinyurl.com/rdn53js) - [Lambda, filter, reduce and map](https://www.python-course.eu/python3_lambda.php) 09. [functools](https://docs.python.org/3/library/functools.html) 10. Apart from these, all the builtin methods of default containers. - [Strings and Character Data in Python](https://realpython.com/python-strings/) 11. [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) - you will need/use it more than you can imagine 12. [Magic Methods](https://tinyurl.com/ydhyrgtq) </p> </details> ### 5. Channels <details><summary></summary> <p> 01. [Tushar Roy - Coding Made Simple](https://www.youtube.com/channel/UCZLJf_R2sWyUtXSKiKlyvAw) 02. [Back To Back SWE](https://www.youtube.com/channel/UCmJz2DV1a3yfgrR7GqRtUUA) 03. [William Fiset](https://www.youtube.com/user/purpongie/featured) 04. [Irfan Baqui](https://www.youtube.com/channel/UCYvQTh9aUgPZmVH0wNHFa1A) </p> </details> ### 6. Tree (Binary Tree, BST, AVL, Red-Black, B-Tree, B+ Tree, Segment Tree, Interval Tree, Range Tree, BIT, N-aray Tree, Trie etc) <details><summary></summary> <p> #### Tree Basics (or not so basics) 01. [Binary Tree playlist - Tushar Roy - Coding Made Simple](https://tinyurl.com/txeffh4) 02. [8 Useful Tree Data Structures Worth Knowing](https://tinyurl.com/t4f8mxg) 03. [Segment Tree Range Minimum Query](https://tinyurl.com/t3eltjb) 04. [Exploring Segment Trees](https://tinyurl.com/uqfgfyn) 05. [AVL Tree - Insertion and Rotations](https://tinyurl.com/qmtgtoc) 06. [B Trees and B+ Trees. How they are useful in Databases](https://tinyurl.com/v6n9fkm) 07. [Red Black Tree Insertion](https://tinyurl.com/vb4kf76) --- NOTE: Partho, read this 08. [Fenwick Tree or Binary Indexed Tree](https://tinyurl.com/ulq6shu) 09. [Fenwick Tree ( Binary Index Tree )](https://tinyurl.com/u95w7ud) --- NOTE: Partho, read this #### Binary Indexed Tree Vs Fenwick Tree 01. [Fenwick Tree or Binary Indexed Tree - youtube](https://www.youtube.com/watch?v=CWDQJGaN1gY) 02. [Binary Indexed Tree or Fenwick Tree - geeksforgeeks](https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/) 03. [Binary Indexed Tree or Fenwick Tree - topcoder](https://www.topcoder.com/community/competitive-programming/tutorials/binary-indexed-trees/) 04. [Segment Tree Range Minimum Query - youtube](https://www.youtube.com/watch?v=ZBHKZF5w4YU) 05. [Segment Tree | Set 1 \(Sum of given range\) - geeksforgeeks](https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/) 06. [Practical Data Structures for Frontend Applications: When to use Segment Trees](https://hackernoon.com/practical-data-structures-for-frontend-applications-when-to-use-segment-trees-9c7cdb7c2819) 07. [What is the difference between a binary indexed tree and a segment tree?](https://codeforces.com/blog/entry/6847) 08. [How does one decide when to use a Segment Tree or Fenwick Tree?](https://www.quora.com/How-does-one-decide-when-to-use-a-Segment-Tree-or-Fenwick-Tree) 09. [What are the differences between segment trees, interval trees, binary indexed trees and range trees?](https://stackoverflow.com/questions/17466218/what-are-the-differences-between-segment-trees-interval-trees-binary-indexed-t) 10. [Height, Depth and Level of a Tree](https://tinyurl.com/zvm773n) 11. [What is the difference between tree depth and height?](https://tinyurl.com/vfnvg8q) #### Self Balancing Binary Search Trees 01. [Self-balancing binary search tree](https://tinyurl.com/zlq297z) 02. [Self-Balancing-Binary-Search-Trees (Comparisons)](https://tinyurl.com/rq23p56) 03. [Self-Balancing Binary Search Trees 101](https://tinyurl.com/rtjr996) 04. [10.1 AVL Tree - Insertion and Rotations](https://tinyurl.com/qmtgtoc) 05. [Red Black tree | Introduction to Red Black trees | Data structure](https://tinyurl.com/urrwf5m) 06. [Red Black Tree Insertion](https://tinyurl.com/wd2z45k) 07. [Title](https://tinyurl.com/txeffh4) 08. [Title](https://tinyurl.com/txeffh4) 09. [Title](https://tinyurl.com/txeffh4) #### Augmented Binary Search Trees(Interval BS Vs Segment Tree Vs Range Tree) 01. [Interval Search Trees - video](https://tinyurl.com/s9xl3p8) 02. [Interval Tree](https://tinyurl.com/u8fnct9) 03. [What are the differences between segment trees, interval trees, binary indexed trees and range trees?](https://tinyurl.com/qn3vwpz) 04. [Interval Trees: One step beyond BST](https://tinyurl.com/v9k5ckt) 05. [Title](https://tinyurl.com/txeffh4) 06. [Title](https://tinyurl.com/txeffh4) </p> </details> ### 7. Graph(Dijkstra, Union Find, Kruskal, Prim's, Minimum Spanning Tree, Topological Ordering...etc) <details><summary></summary> <p> 01. [Graph Theory Playlist](https://tinyurl.com/rfgy88b) 02. [Graph Theory Playlist 2](https://tinyurl.com/yfa57nc5) 03. [Union Find \[Disjoint Set\] Playlist](https://tinyurl.com/srz7uua) 04. [Disjoint Sets Data Structure - Weighted Union and Collapsing Find](https://www.youtube.com/watch?v=wU6udHRIkcc) 05. [Codinginterviewclass.com](https://tinyurl.com/wpgl4nt) 06. Single(Di-Bel)/All(Flo) Source Shortest Path Algorithms: Dijkstra ([1](https://tinyurl.com/r8omw8l), [2](https://tinyurl.com/sscslz7)), Bellman-Ford([1](https://tinyurl.com/tghcsmz), [2](https://tinyurl.com/rdcax5b)), Floydโ€“Warshall([1](https://tinyurl.com/vsp4ulb), [2](https://tinyurl.com/s5wjb5a)) 07. Dijkstraโ€™s Algorithm Vs Bellman-Ford Algorithm Vs Floyd Warshall Algorithm ( [1](https://tinyurl.com/vxwc2je), [2](https://tinyurl.com/s6vff87), [3](https://tinyurl.com/s5o57nz) ) 08. Minimum Spanning Tree Algorithm: Prim's ( [1](https://tinyurl.com/vgbgdl2), [2](https://tinyurl.com/yecuqtty), Kruskal's ([1](https://tinyurl.com/vgbgdl2), [2](https://tinyurl.com/yhxpvpkn) ) 09. Kruskal's algorithm Vs Prim's algorithm ( [1](https://qr.ae/TSEPGc), [2](https://tinyurl.com/yz6399ck), [3](https://tinyurl.com/yz3q7vox) ) 10. [Tushar Roy - Coding Made Simple - Grapy Algorithm Playlist](https://tinyurl.com/y7qeb9ae) </p> </details> ### 8. Bit Manipulation <details><summary></summary> <p> 01. [Bit Manipulation - youtube](https://www.youtube.com/watch?v=7jkIUgLC29I) 02. [Conversion of Binary, Octal and Hexadecimal Numbers](http://www.cs.ucr.edu/~ehwang/courses/cs120a/00winter/binary.pdf) 03. [Your guide to Bit Manipulation](https://codeburst.io/your-guide-to-bit-manipulation-48e7692f314a) 04. [Python Bitwise Operators](https://www.journaldev.com/26737/python-bitwise-operators) 05. [Add Two Numbers Without The "+" Sign (Bit Shifting Basics)](https://www.youtube.com/watch?v=qq64FrA2UXQ) 06. [Binary Arithmetic](https://www.electrical4u.com/binary-arithmetic/) 07. [1โ€™s and 2โ€™s complement of a Binary Number](https://www.geeksforgeeks.org/1s-2s-complement-binary-number/) 08. [What is โ€œ2's Complementโ€?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) 09. [Bits manipulation \(Important tactics\)](https://www.geeksforgeeks.org/bits-manipulation-important-tactics/) 10. [Bit Manipulation](https://medium.com/@hitherejoe/bit-manipulation-b13b94e70f3b) 11. [Python Bitwise Operators](https://www.concretepage.com/python/python-bitwise-operators) 12. [XOR - The magical bitwise operator](https://hackernoon.com/xor-the-magical-bit-wise-operator-24d3012ed821) 13. [A summary: how to use bit manipulation to solve problems easily and efficiently - leetcode](https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary:-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently) 14. [Bit Manipulation 4% of LeetCode Problems](https://medium.com/algorithms-and-leetcode/bit-manipulation-4-of-leetcode-problems-e67db88598d1) 15. [Coding Interview University - Bitwise operations](https://github.com/jwasham/coding-interview-university#bitwise-operations) 16. [Mask (computing)](https://en.wikipedia.org/wiki/Mask_(computing)) 17. [What is Bit Masking?](https://stackoverflow.com/questions/10493411/what-is-bit-masking) 18. [Understanding Bit masks](https://abdulapopoola.com/2016/05/30/understanding-bit-masks/) 19. [Bitmasks: A very esoteric (and impractical) way of managing booleans](https://dev.to/somedood/bitmasks-a-very-esoteric-and-impractical-way-of-managing-booleans-1hlf) 20. [Hackerโ€™s Delight - BOOK](http://93.174.95.29/_ads/34DCB990FEBE54887C83E5F9534F1957) 21. [Bitwise operators โ€” Facts and Hacks](https://medium.com/@shashankmohabia/bitwise-operators-facts-and-hacks-903ca516f28c) 22. [Signed number representations](https://en.wikipedia.org/wiki/Signed_number_representations) 23. **[Vid 1](https://www.youtube.com/watch?v=NLKQEOgBAnw), [Vid 2](https://www.youtube.com/watch?v=qq64FrA2UXQ&feature=emb_title)** </p> </details> ### 9. Dynamic Programming <details><summary></summary> <p> 01. [The FAST method](https://www.byte-by-byte.com/fast-method/) 02. [A good approach to attack DP](https://leetcode.com/articles/jump-game/) 03. [Tabulation vs Memoization](https://www.geeksforgeeks.org/tabulation-vs-memoization/) 04. [Memoization vs Tabulation](https://elvrsn.blogspot.com/2015/02/memoization-vs-tabulation.html) 05. [1D Subproblems vs. 2D Subproblems](https://tinyurl.com/yfopxwjq) 06. [Memoization (1D, 2D and 3D)](https://tinyurl.com/ydw8sy6l) 07. [Introduction to Multi-dimensional Dynamic Programming](https://tinyurl.com/ydwjq3rl) 08. **[Dynamic Programming Patterns - MUST READ](https://tinyurl.com/tenzf8b)** 09. **[My experience and notes for learning DP](https://tinyurl.com/rjg4vtg)** 10. **[DP IS EASY! 5 Steps to Think Through DP Questions](https://tinyurl.com/vmmaxbe)** 11. **[Dynamic Programming Patterns](https://tinyurl.com/tenzf8b)** </p> </details> ### 10. Greedy <details><summary></summary> <p> 01. [Greedy Method - Introduction](https://www.youtube.com/watch?v=ARvQcqJ_-NY&t=2s) 02. [Introduction to Greedy Method](https://www.youtube.com/watch?v=xpNWJD24fPA) 03. [Introduction to Greedy Algorithms | GeeksforGeeks](https://www.youtube.com/watch?v=HzeK7g8cD0Y) 04. [Basics of Greedy Algorithms](https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/tutorial/) 05. [When to try greedy algorithms on problems?](https://codeforces.com/blog/entry/14032) 06. [How to spot a โ€œgreedyโ€ algorithm?](https://stackoverflow.com/questions/7887487/how-to-spot-a-greedy-algorithm) </p> </details> ### 11. DP VS Greedy <details><summary></summary> <p> 01. [Greedy Algorithm and Dynamic Programming](https://medium.com/cracking-the-data-science-interview/greedy-algorithm-and-dynamic-programming-a8c019928405) 02. [Greedy approach vs Dynamic programming](https://www.geeksforgeeks.org/greedy-approach-vs-dynamic-programming/) 03. [What is the difference between dynamic programming and greedy approach?](https://stackoverflow.com/questions/16690249/what-is-the-difference-between-dynamic-programming-and-greedy-approach) </p> </details> ### 12. Backtracking <details><summary></summary> <p> 01. [Backtracking - wiki](https://en.wikipedia.org/wiki/Backtracking) 02. [Backtracking | Introduction](https://www.geeksforgeeks.org/backtracking-introduction/) 03. [Introduction to Backtracking - Brute Force Approach](https://www.youtube.com/watch?v=DKCbsiDBN6c) 04. [Branch and Bound Introduction](https://www.youtube.com/watch?v=3RBNPc0_Q6g) 05. [The Backtracking Blueprint: The Legendary 3 Keys To Backtracking Algorithms](https://www.youtube.com/watch?v=Zq4upTEaQyM) 06. [Backtracking explained](https://medium.com/@andreaiacono/backtracking-explained-7450d6ef9e1a) 07. [Foundation of algorithms - Chapter 5 (Backtracking) notes](https://www.cpp.edu/~ftang/courses/CS331/notes/backtracking.pdf) 08. [Backtracking Search Algorithms](https://cs.uwaterloo.ca/~vanbeek/Publications/survey06.pdf) </p> </details> ### 13. Recursion <details><summary></summary> <p> 01. [Learning to think with recursion, part 1](https://medium.com/@daniel.oliver.king/getting-started-with-recursion-f89f57c5b60e) 02. [Learning to think with recursion, part 2](https://medium.com/@daniel.oliver.king/learning-to-think-with-recursion-part-2-887bd4c41274) 03. [What makes a data structure recursive?](https://stackoverflow.com/questions/45761182/what-makes-a-data-structure-recursive) 04. [Binary Tree as a Recursive Data Structure](https://opendsa-server.cs.vt.edu/ODSA/Books/CS3/html/RecursiveDS.html) 05. [Recursion Visualizer - use Viz Mode](http://www.codeskulptor.org/viz/index.html) 06. [Thinking Recursively in Python](https://realpython.com/python-thinking-recursively/) 07. [Breaking out of a recursive function?](https://stackoverflow.com/questions/10544513/breaking-out-of-a-recursive-function) 08. [Why does recursion return the first call in the stack and not the last?](https://softwareengineering.stackexchange.com/questions/333247/why-does-recursion-return-the-first-call-in-the-stack-and-not-the-last) </p> </details> ### 14. Game Theory <details><summary></summary> <p> 01. [Intuition for Solving a MiniMax Problems](https://tinyurl.com/ryxxott) 02. [Game theory โ€” Minimax](https://tinyurl.com/qtfn9jl) 03. [How to make your Tic Tac Toe game unbeatable by using the minimax algorithm](https://tinyurl.com/t9tedyf) </p> </details> ### 15. Few special DS <details><summary></summary> <p> 01. [Monotonic Queue Explained with LeetCode Problems](https://tinyurl.com/rn7rsnf) </p> </details> </p> </details> <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [last-commit-shield]: https://img.shields.io/github/last-commit/partho-maple/coding-interview-gym?style=flat [last-commit-url]: https://github.com/partho-maple/coding-interview-gym/commits/master [repo-size-shield]: https://img.shields.io/github/repo-size/partho-maple/coding-interview-gym?style=flat [repo-size-url]: https://github.com/partho-maple/coding-interview-gym [contributors-shield]: https://img.shields.io/github/contributors/partho-maple/coding-interview-gym.svg?style=flat [contributors-url]: https://github.com/partho-maple/coding-interview-gym/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/partho-maple/coding-interview-gym.svg?style=flat [forks-url]: https://github.com/partho-maple/coding-interview-gym/network/members [stars-shield]: https://img.shields.io/github/stars/partho-maple/coding-interview-gym.svg?style=flat [stars-url]: https://github.com/partho-maple/coding-interview-gym/stargazers [issues-shield]: https://img.shields.io/github/issues/partho-maple/coding-interview-gym.svg?style=flat [issues-url]: https://github.com/partho-maple/coding-interview-gym/issues [license-shield]: https://img.shields.io/github/license/partho-maple/coding-interview-gym.svg?style=flat [license-url]: https://github.com/partho-maple/coding-interview-gym/LICENSE.txt [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg??style=flat&logo=linkedin&colorB=555 [linkedin-url]: https://www.linkedin.com/in/partho-biswas/ [product-screenshot]: images/screenshot.png
171
Functional programming in Swift
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Build Status](https://travis-ci.org/typelift/Swiftz.svg?branch=master)](https://travis-ci.org/typelift/Swiftz) [![Gitter chat](https://badges.gitter.im/DPVN/chat.png)](https://gitter.im/typelift/general?utm_source=share-link&utm_medium=link&utm_campaign=share-link) Swiftz ====== Swiftz is a Swift library for functional programming. It defines functional data structures, functions, idioms, and extensions that augment the Swift standard library. For a small, simpler way to introduce functional primitives into any codebase, see [Swiftx](https://github.com/typelift/Swiftx). Introduction ------------ Swiftz draws inspiration from a number of functional libraries and languages. Chief among them are [Scalaz](https://github.com/scalaz/scalaz), [Prelude/Base](https://hackage.haskell.org/package/base), [SML Basis](http://sml-family.org/Basis/), and the [OCaml Standard Library](http://caml.inria.fr/pub/docs/manual-ocaml/stdlib.html). Elements of the library rely on their combinatorial semantics to allow declarative ideas to be expressed more clearly in Swift. Swiftz is a proper superset of [Swiftx](https://github.com/typelift/Swiftx) that implements higher-level data types like Arrows, Lists, HLists, and a number of typeclasses integral to programming with the maximum amount of support from the type system. To illustrate use of these abstractions, take these few examples: **Lists** ```swift import struct Swiftz.List //: Cycles a finite list of numbers into an infinite list. let finite : List<UInt> = [1, 2, 3, 4, 5] let infiniteCycle = finite.cycle() //: Lists also support the standard map, filter, and reduce operators. let l : List<Int> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] let twoToEleven = l.map(+1) // [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] let even = l.filter((==0) โ€ข (%2)) // [2, 4, 6, 8, 10] let sum = l.reduce(curry(+), initial: 0) // 55 //: Plus a few more. let partialSums = l.scanl(curry(+), initial: 0) // [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55] let firstHalf = l.take(5) // [1, 2, 3, 4, 5] let lastHalf = l.drop(5) // [6, 7, 8, 9, 10] ``` **Semigroups and Monoids** ```swift let xs = [1, 2, 0, 3, 4] import protocol Swiftz.Semigroup import func Swiftz.sconcat import struct Swiftz.Min //: The least element of a list can be had with the Min Semigroup. let smallestElement = sconcat(Min(2), t: xs.map { Min($0) }).value() // 0 import protocol Swiftz.Monoid import func Swiftz.mconcat import struct Swiftz.Sum //: Or the sum of a list with the Sum Monoid. let sum = mconcat(xs.map { Sum($0) }).value() // 10 import struct Swiftz.Product //: Or the product of a list with the Product Monoid. let product = mconcat(xs.map { Product($0) }).value() // 0 ``` **Arrows** ```swift import struct Swiftz.Function import struct Swiftz.Either //: An Arrow is a function just like any other. Only this time around we //: can treat them like a full algebraic structure and introduce a number //: of operators to augment them. let comp = Function.arr(+3) โ€ข Function.arr(*6) โ€ข Function.arr(/2) let both = comp.apply(10) // 33 //: An Arrow that runs both operations on its input and combines both //: results into a tuple. let add5AndMultiply2 = Function.arr(+5) &&& Function.arr(*2) let both = add5AndMultiply2.apply(10) // (15, 20) //: Produces an Arrow that chooses a particular function to apply //: when presented with the side of an Either. let divideLeftMultiplyRight = Function.arr(/2) ||| Function.arr(*2) let left = divideLeftMultiplyRight.apply(.Left(4)) // 2 let right = divideLeftMultiplyRight.apply(.Right(7)) // 14 ``` **Operators** See [Operators](https://github.com/typelift/Operadics#operators) for a list of supported operators. Setup ----- To add Swiftz to your application: **Using Carthage** - Add Swiftz to your Cartfile - Run `carthage update` - Drag the relevant copy of Swiftz into your project. - Expand the Link Binary With Libraries phase - Click the + and add Swiftz - Click the + at the top left corner to add a Copy Files build phase - Set the directory to `Frameworks` - Click the + and add Swiftz **Using Git Submodules** - Clone Swiftz as a submodule into the directory of your choice - Run `git submodule init -i --recursive` - Drag `Swiftz.xcodeproj` or `Swiftz-iOS.xcodeproj` into your project tree as a subproject - Under your project's Build Phases, expand Target Dependencies - Click the + and add Swiftz - Expand the Link Binary With Libraries phase - Click the + and add Swiftz - Click the + at the top left corner to add a Copy Files build phase - Set the directory to `Frameworks` - Click the + and add Swiftz **Using Swift Package Manager** - Add Swiftz to your `Package.swift` within your project's `Package` definition: ```swift let package = Package( name: "MyProject", ... dependencies: [ .package(url: "https://github.com/typelift/Swiftz.git", from: "0.0.0") ... ], targets: [ .target( name: "MyProject", dependencies: ["Swiftz"]), ... ] ) ``` System Requirements =================== Swiftz supports OS X 10.9+ and iOS 8.0+. License ======= Swiftz is released under the BSD license.
172
:earth_africa: Compass helps you setup a central navigation system for your application
โš ๏ธ DEPRECATED, NO LONGER MAINTAINED ![Compass logo](https://raw.githubusercontent.com/hyperoslo/Compass/master/Images/logo_v1.png) [![Version](https://img.shields.io/cocoapods/v/Compass.svg?style=flat)](http://cocoadocs.org/docsets/Compass) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![License](https://img.shields.io/cocoapods/l/Compass.svg?style=flat)](http://cocoadocs.org/docsets/Compass) [![Platform](https://img.shields.io/cocoapods/p/Compass.svg?style=flat)](http://cocoadocs.org/docsets/Compass) [![CI Status](http://img.shields.io/travis/hyperoslo/Compass.svg?style=flat)](https://travis-ci.org/hyperoslo/Compass) ![Swift](https://img.shields.io/badge/%20in-swift%203.0-orange.svg) Compass helps you setup a central navigation system for your application. This has many benefits, one of them being that controllers can now be decoupled, meaning that the list that presents the detail no longer knows about what its presenting. Controllers become agnostic and views stay stupid. The user experience stays the same but the logic and separation of concerns become clearer. The outcome is that your application will become more modular by default. Anything could potentially be presented from anywhere, but remember, with great power comes great responsibility. ## Getting Started Below are tutorials on how to use Compass - [URL Routing in iOS apps: Compass Beginner Guide](https://medium.com/flawless-app-stories/url-routing-with-compass-d59c0061e7e2): basic introduction to Compass, how to use Router and multiple use cases for deep linking, push notifications ## Setup #### Step 1 First you need to register a URL scheme for your application. <img src="https://raw.githubusercontent.com/hyperoslo/Compass/master/Images/setup-url-scheme.png"> #### Step 2 Now you need to configure Compass to use that URL scheme, a good place to do this is in your `AppDelegate`. Then configure all the routes you wish you support. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Navigator.scheme = "compass" Navigator.routes = ["profile:{username}", "login:{username}", "logout"] return true } ``` #### Step 3 Register your location request handler ```swift Navigator.handle = { [weak self] location in let arguments = location.arguments let rootController = self?.window.rootViewController as? UINavigationController switch location.path { case "profile:{username}": let profileController = ProfileController(title: arguments["username"]) rootController?.pushViewController(profileController, animated: true) case "login:{username}": let loginController = LoginController(title: arguments["username"]) rootController?.pushViewController(loginController, animated: true) case "logout": self?.clearLoginSession() self?.switchToLoginScreen() default: break } } ``` #### Step 4 Anywhere in your application, you can just use `Navigator` to navigate ```swift @IBOutlet func logoutButtonTouched() { Navigator.navigate(urn: "logout") } ``` #### Step 5 Optional. If you want to support deep linking, set up your application to respond to the URLs. Setting it up this way would mean that you could open any view from a push notification depending on the contents of the payload. ```swift func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { do { try Navigator.navigate(url: url) } catch { // Handle error } return true } ``` ## Compass life hacks ### Tip 1. Router We also have some conventional tools for you that could be used to organize your route handling code and avoid huge `switch` cases. - Implement `Routable` protocol to keep your single route navigation code in one place: ```swift struct ProfileRoute: Routable { func navigate(to location: Location, from currentController: CurrentController) throws { guard let username = location.arguments["username"] else { return } let profileController = ProfileController(title: username) currentController.navigationController?.pushViewController(profileController, animated: true) } } ``` - Create a `Router` instance and register your routes. Think of `Router` as a composite `Routable` ```swift let router = Router() router.routes = [ "profile:{username}": ProfileRoute(), "logout": LogoutRoute() ] ``` - Parse URL with **Compass** and navigate to the route with a help of your `Router` instance. ```swift func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { return handle(url) } func handle(_ url: URL) -> Bool { guard let location = Navigator.parse(url) else { return false } router.navigate(to: location, from: navigationController) return true } ``` ### Tip 2. Multiple routers You could set up multiple routers depending on app states. For example, you could have 2 routers for pre and post login. ```swift let preLoginRouter = Router() preLoginRouter.routes = [ "profile:{username}" : ProfileRoute() ] let postLoginRouter = Router() postLoginRouter.routes = [ "login:{username}" : LoginRoute() ] let router = hasLoggedIn ? postLoginRouter : preLoginRouter router.navigate(to: location, from: navigationController) ``` ## Installation **Compass** is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod 'Compass' ``` **Compass** is also available through [Carthage](https://github.com/Carthage/Carthage). To install just write into your Cartfile: ```ruby github "hyperoslo/Compass" ``` ## Author Hyper Interaktiv AS, [email protected] ## Credits The idea behind Compass came from [John Sundell](https://github.com/JohnSundell)'s tech talk "*Components & View Models in the Cloud - how Spotify builds native, dynamic UIs*" ## License **Compass** is available under the MIT license. See the LICENSE file for more info.
173
๐Ÿงฐ Case paths bring the power and ergonomics of key paths to enums!
# ๐Ÿงฐ CasePaths [![CI](https://github.com/pointfreeco/swift-case-paths/workflows/CI/badge.svg)](https://actions-badge.atrox.dev/pointfreeco/swift-case-paths/goto) [![Slack](https://img.shields.io/badge/slack-chat-informational.svg?label=Slack&logo=slack)](http://pointfree.co/slack-invite) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpointfreeco%2Fswift-case-paths%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/pointfreeco/swift-case-paths) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fpointfreeco%2Fswift-case-paths%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/pointfreeco/swift-case-paths) Case paths bring the power and ergonomics of key paths to enums! ## Motivation Swift endows every struct and class property with a [key path](https://developer.apple.com/documentation/swift/swift_standard_library/key-path_expressions). ``` swift struct User { var id: Int var name: String } \User.id // WritableKeyPath<User, Int> \User.name // WritableKeyPath<User, String> ``` This is compiler-generated code that can be used to abstractly zoom in on part of a structure, inspect and even change it, while propagating these changes to the structure's whole. They unlock the ability to do many things, like [key-value observing](https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift) and [reactive bindings](https://developer.apple.com/documentation/combine/receiving_and_handling_events_with_combine), [dynamic member lookup](https://github.com/apple/swift-evolution/blob/master/proposals/0252-keypath-dynamic-member-lookup.md), and scoping changes to the SwiftUI [environment](https://developer.apple.com/documentation/swiftui/environment). Unfortunately, no such structure exists for enum cases! ``` swift enum Authentication { case authenticated(accessToken: String) case unauthenticated } \Authentication.authenticated // ๐Ÿ›‘ ``` And so it's impossible to write similar generic algorithms that can zoom in on a particular enum case. ## Introducing: case paths This library intends to bridge this gap by introducing what we call "case paths." Case paths can be constructed simply by prepending the enum type and case name with a _forward_ slash: ``` swift import CasePaths /Authentication.authenticated // CasePath<Authentication, String> ``` ### Case paths vs. key paths While key paths package up the functionality of getting and setting a value on a root structure, case paths package up the functionality of extracting and embedding a value on a root enumeration. ``` swift user[keyPath: \User.id] = 42 user[keyPath: \User.id] // 42 let authentication = (/Authentication.authenticated).embed("cafebeef") (/Authentication.authenticated).extract(from: authentication) // Optional("cafebeef") ``` Case path extraction can fail and return `nil` because the cases may not match up. ``` swift (/Authentication.authenticated).extract(from: .unauthenticated) // nil ```` Case paths, like key paths, compose. Where key paths use dot-syntax to dive deeper into a structure, case paths use a double-dot syntax: ``` swift \HighScore.user.name // WritableKeyPath<HighScore, String> /Result<Authentication, Error>..Authentication.authenticated // CasePath<Result<Authentication, Error>, String> ``` Case paths, also like key paths, provide an "[identity](https://github.com/apple/swift-evolution/blob/master/proposals/0227-identity-keypath.md)" path, which is useful for interacting with APIs that use key paths and case paths but you want to work with entire structure. ``` swift \User.self // WritableKeyPath<User, User> /Authentication.self // CasePath<Authentication, Authentication> ``` Key paths are created for every property, even computed ones, so what is the equivalent for case paths? Well, "computed" case paths can be created by providing custom `embed` and `extract` functions: ``` swift CasePath<Authentication, String>( embed: { decryptedToken in Authentication.authenticated(token: encrypt(decryptedToken)) }, extract: { authentication in guard case let .authenticated(encryptedToken) = authentication, let decryptedToken = decrypt(token) else { return nil } return decryptedToken } ) ``` Since Swift 5.2, key path expressions can be passed directly to methods like `map`. The same is true of case path expressions, which can be passed to methods like `compactMap`: ``` swift users.map(\User.name) authentications.compactMap(/Authentication.authenticated) ``` ## Ergonomic associated value access CasePaths uses Swift reflection to automatically embed and extract associated values from _any_ enum in a single, short expression. This helpful utility is made available as a public module function that can be used in your own libraries and apps: ``` swift (/Authentication.authenticated).extract(from: .authenticated("cafebeef")) // Optional("cafebeef") ``` ## Community If you want to discuss this library or have a question about how to use it to solve a particular problem, there are a number of places you can discuss with fellow [Point-Free](http://www.pointfree.co) enthusiasts: * For long-form discussions, we recommend the [discussions](http://github.com/pointfreeco/swift-case-paths/discussions) tab of this repo. * For casual chat, we recommend the [Point-Free Community Slack](http://pointfree.co/slack-invite). ## Documentation The latest documentation for CasePaths' APIs is available [here](https://pointfreeco.github.io/swift-case-paths/). ## Other libraries - [`EnumKit`](https://github.com/gringoireDM/EnumKit) is a protocol-oriented, reflection-based solution to ergonomic enum access and inspired the creation of this library. ## Interested in learning more? These concepts (and more) are explored thoroughly in [Point-Free](https://www.pointfree.co), a video series exploring functional programming and Swift hosted by [Brandon Williams](https://github.com/mbrandonw) and [Stephen Celis](https://github.com/stephencelis). The design of this library was explored in the following [Point-Free](https://www.pointfree.co) episodes: - [Episode 87](https://www.pointfree.co/episodes/ep87-the-case-for-case-paths-introduction): The Case for Case Paths: Introduction - [Episode 88](https://www.pointfree.co/episodes/ep88-the-case-for-case-paths-properties): The Case for Case Paths: Properties - [Episode 89](https://www.pointfree.co/episodes/ep89-case-paths-for-free): Case Paths for Free <a href="https://www.pointfree.co/episodes/ep87-the-case-for-case-paths-introduction"> <img alt="video poster image" src="https://d3rccdn33rt8ze.cloudfront.net/episodes/0087.jpeg" width="480"> </a> ## License All modules are released under the MIT license. See [LICENSE](LICENSE) for details.
174
A collaborative list of awesome articles, talks, books, videos and code examples about SwiftUI.
A list of articles, tutorials, guides and videos about SwiftUI and Combine. **Feel free to contribute!** #### If you have a great content to share and want people to know about it ASAP then join our [Reddit Community](https://www.reddit.com/r/AwesomeSwiftUI/). <img src="awesome-swiftui-banner.png"/> ### Content - [Articles](#-articles) - [Tutorials](#tutorials) - [How to](#how-to) - [View and Navigation](#view-and-navigation) - [State and Binding](#state-and-binding) - [Architecture](#architecture) - [Animations](#animations) - [Inside](#inside) - [Unit Testing](#unit-testing) - [Debug](#debug) - [Other](#other) - [Combine](#combine) - [Videos](#-videos) - [Apple WWDC 2019](#apple-wwdc-2019) - [Tutorials](#tutorials) - [Examples](#-examples) - [Helpers](#helpers) - [Libraries](#libraries) - [Combine](#combine) - [Open Source Apps](#open-source-apps) - [Apps](#apps) - [Courses](#-courses) - [Books](#-books) - [SwiftUI](#swiftui) - [Combine](#combine) ## ๐Ÿ“ Articles #### [SwiftUI Cheat Sheet](https://fuckingswiftui.com/) ### Tutorials * [SwiftUI Tutorials](https://developer.apple.com/tutorials/swiftui/tutorials) by Apple * [Making real-world app with SwiftUI](https://mecid.github.io/2019/06/05/swiftui-making-real-world-app/) by Majid * [Intro to SwiftUIโ€Šโ€”โ€ŠPart 1](https://medium.com/@suyash.srijan/intro-to-swiftui-part-1-47361a3ffb2e) by Suyash Srijan * [Intro to SwiftUIโ€Šโ€”โ€ŠPart 2](https://medium.com/@suyash.srijan/intro-to-swiftui-part-2-6b7e792c21ef) by Suyash Srijan * [MessageUI, SwiftUI and UIKit integration](https://medium.com/@florentmorin/messageui-swiftui-and-uikit-integration-82d91159b0bd) by Florent Morin * [Managing Data Flow in SwiftUI](https://mecid.github.io/2019/07/03/managing-data-flow-in-swiftui/) by Majid * [Beginner SwiftUI Tutorials](https://swiftuihub.com/beginner-swiftui-tutorials/) by SwiftUI Hub * [Making a Real World Application With SwiftUI](https://medium.com/better-programming/making-a-real-world-application-with-swiftui-cb40884c1056) by Thomas Ricouard * [Building BarChart with Shape API in SwiftUI](https://mecid.github.io/2019/08/14/building-barchart-with-shape-api-in-swiftui/) by Majid * [100 Days of SwiftUI](https://www.hackingwithswift.com/100/swiftui) by Paul Hudson ### How to * [How to build a phone number text field](https://benjaminlsage.medium.com/format-phone-numbers-entirely-in-swiftui-9456f52990a1) by icyhovercraft * [How to build an onboarding screen](https://blckbirds.com/post/how-to-create-a-onboarding-screen-in-swiftui-1/) by blckbirds * [How to build a Chat App or Messenger](https://blog.usejournal.com/how-to-build-a-chat-app-or-messenger-in-swiftui-for-ios-swift-b46dbe5cc0ab) by Nick Halavins * [How to build a Form UI](https://www.appcoda.com/swiftui-form-ui/) by Simon Ng * [How to build a Weather App](https://medium.com/lunabee-studio/building-a-weather-app-with-swiftui-4ec2743ff615) by Benjamin Pisano * [How to build a Slide out Menu](https://medium.com/programming-with-swift/create-a-side-menu-with-swiftui-4225c8842d26) by Darren * [How to build a TicTacToe game](https://medium.com/@valv0/a-tictactoe-game-in-swiftui-66b24953f467) by Costantino Pistagna * [How to build a Simple Countdown Timer](https://medium.com/better-programming/make-a-simple-countdown-with-timer-and-swiftui-3ce355b54986) by Antoine Barrault * [How to create a side(hamburger) menu](https://blckbirds.com/post/side-menu-hamburger-menu-in-swiftui/) by blckbirds * [How to Implement Sign In With SwiftUI and AWS Amplify](https://medium.com/better-programming/sign-in-with-aws-amplify-and-swiftui-978b01a5cf10) by Victor Sanchez * [Build Mobile Serverless Apps Using Amazon Aurora, Amplify, and SwiftUI](https://medium.com/better-programming/build-mobile-serverless-apps-using-amazon-aurora-amplify-and-swiftui-7562ecb7df9a) by Victor Sanchez * [Build an Object Detection App Using Amazon Rekognition, Amplify, and SwiftUI](https://medium.com/better-programming/build-an-object-detection-app-using-amazon-rekognition-amplify-and-swiftui-20b51dd0024b) by Victor Sanchez ### View and Navigation * [Dynamic List & Identifiable](https://medium.com/flawless-app-stories/swiftui-dynamic-list-identifiable-73c56215f9ff) by Martin Lasek * [Create a Detail View](https://medium.com/@martinlasek/swiftui-detail-view-44772246fa2a) by Martin Lasek * [SwiftUI tips and tricks](https://www.hackingwithswift.com/quick-start/swiftui/swiftui-tips-and-tricks) by Paul Hudson * [How to use SwiftUI to Speed Up your View Coding](https://medium.com/@leonardo.dematossouza/how-to-use-swiftui-to-speed-up-your-view-coding-6dbb0fcabc99) by Leonardo Souza * [The Simple Life(cycle) of a SwiftUI View](https://medium.com/flawless-app-stories/the-simple-life-cycle-of-a-swiftui-view-95e2e14848a2) by Danny Bolella * [Alignment Guides in SwiftUI](https://swiftui-lab.com/alignment-guides/) by javier * [Custom navigation view for your applications](https://medium.com/swlh/swiftui-custom-navigation-view-for-your-applications-7f6effa7dbcf) by Dragos Ioneanu * [Reusable Components/Higher-Order-Components](https://medium.com/better-programming/swiftui-reusable-components-higher-order-components-192c65375c36) by Andrei Villasana * [How to Programmatically Push and Pop Views in SwiftUI with NavigationDestinationLink](https://ryanashcraft.com/swiftui-programmatic-navigation/) by ryanashcraft * [Programmatic navigation in SwiftUI project](https://nalexn.github.io/swiftui-deep-linking/?utm_source=awsui1) by Alexey Naumov ### State and Binding * [Understanding State](https://medium.com/flawless-app-stories/swiftui-understanding-state-8afa23fd9f1f) by Martin Lasek * [Understanding Binding](https://medium.com/flawless-app-stories/swiftui-understanding-binding-8e20269a76bc) by Martin Lasek * [Understanding Property Wrappers in SwiftUI](https://mecid.github.io/2019/06/12/understanding-property-wrappers-in-swiftui/) by Majid * [Redux-like state container in SwiftUI. Basics.](https://mecid.github.io/2019/09/18/redux-like-state-container-in-swiftui/) by Majid * [Swift Property Wrappers](https://nshipster.com/propertywrapper/) by Mattt * [Conditional views in SwiftUI](https://medium.com/@iosdev/conditional-views-in-swiftui-dc09c808bc30#95f6-9e0f877be7d4) by Vladimirs Matusevics ### Architecture * [Will Combine kill RxSwift?](https://medium.com/flawless-app-stories/will-combine-kill-rxswift-64780a150d89) by MortyMerr * [MVVM in SwiftUI](https://medium.com/flawless-app-stories/mvvm-in-swiftui-8a2e9cc2964a) by Mohammad Azam * [Clean Architecture for SwiftUI](https://nalexn.github.io/clean-architecture-swiftui/?utm_source=awsui1) by Alexey Naumov ### Animations * [Animations in SwiftUI](https://mecid.github.io/2019/06/26/animations-in-swiftui/) by Majid * [Gestures in SwiftUI](https://mecid.github.io/2019/07/10/gestures-in-swiftui/) by Majid * [UI Animations With Swift](https://medium.com/better-programming/ui-animations-with-swift-2ebb5e6d2292) by Xiomara Figueroa * [Advanced SwiftUI Animations โ€“ Part 1: Paths](https://swiftui-lab.com/swiftui-animations-part1/) by javier * [Advanced SwiftUI Animations โ€“ Part 2: GeometryEffect](https://swiftui-lab.com/swiftui-animations-part2/) by javier ### Inside * [Inside SwiftUI's Declarative Syntax's Compiler Magic](https://swiftrocks.com/inside-swiftui-compiler-magic.html) by Bruno Rocha * [Whatโ€™s this โ€œsomeโ€ in SwiftUI?](https://medium.com/@PhiJay/whats-this-some-in-swiftui-34e2c126d4c4) by Mischa Hildebrand * [Swift Opaque Result Types](https://jeroenscode.com/swift-opaque-result-types/) by Baking Swift * [Inside SwiftUI (About @State)](https://kateinoigakukun.hatenablog.com/entry/2019/06/09/081831) by kateinoigakukun ### Unit Testing * [ViewInspector](https://github.com/nalexn/ViewInspector) by Alexey Naumov * [Unit testing SwiftUI views](https://nalexn.github.io/swiftui-unit-testing/?utm_source=awsui1) by Alexey Naumov ### Debug * [How to use Instruments to profile your SwiftUI code and identify slow layouts](https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-instruments-to-profile-your-swiftui-code-and-identify-slow-layouts) by Paul Hudson * [Building SwiftUI debugging utilities](https://www.swiftbysundell.com/articles/building-swiftui-debugging-utilities/) by John Sundell ### Other * [Curated list of questions and answers about SwiftUI](https://goshdarnswiftui.com/) by Gosh Darn SwiftUI * [Answers to the most common questions about SwiftUI](https://wwdcbysundell.com/2019/swiftui-common-questions/) by John Sundell * [A first look at SwiftUI: Appleโ€™s declarative new UI framework](https://wwdcbysundell.com/2019/swiftui-first-look/) by John Sundell * [Shifting paradigms in Swift](https://www.swiftbysundell.com/articles/shifting-paradigms-in-swift) by John Sundell * [Understanding Declarative Programming](https://medium.com/better-programming/swiftui-understanding-declarative-programming-aaf05b2383bd) by Michael Long * [Rendering SwiftUI views to HTML](https://worthdoingbadly.com/swiftui-html/) by Zhuowei Zhang] * [SwiftUI: Handling optionals](https://ericasadun.com/2019/06/20/swiftui-handling-optionals/) by Erica Sadun * [Improving SwiftUI modal presentation API](https://alejandromp.com/blog/improving-swiftui-modal-presentation-api) by Alejandro Martinez * [Mixing SwiftUI, Combine, OLX](https://tech.olx.com/mixing-swiftui-combine-olx-636c4f3c4162) by Aleksander Lorenc * [The missing :SwiftWebUI](http://www.alwaysrightinstitute.com/swiftwebui/) by alwaysrightinstitute * [Rasterizing SwiftUI views from the Command-Line](https://medium.com/@eneko/rasterizing-swiftui-views-from-the-command-line-80d974356c4a) by Eneko Alonso * [A Brief Tour of Swift UI](https://www.bignerdranch.com/blog/a-brief-tour-of-swift-ui/) by Amit Bijlani * [Why You Should Consider SwiftUI for Your Next Project](https://medium.com/better-programming/why-you-should-consider-swiftui-for-your-next-project-2d67a7e3745e) by Thomas Ricouard * [What is new in SwiftUI](https://swiftwithmajid.com/2020/06/23/what-is-new-in-swiftui/) by mecid ### Combine * [Problem Solving with Combine Swift](https://medium.com/flawless-app-stories/problem-solving-with-combine-swift-4751885fda77) by Arlind Aliu * [SwiftUI & Combine: Better Together](https://medium.com/flawless-app-stories/swiftui-plus-combine-equals-love-791ad444a082) by [Peter Friese](https://twitter.com/peterfriese) * [Swift Combine Framework Tutorial: Getting Started](https://www.vadimbulavin.com/swift-combine-framework-tutorial-getting-started/) by vadimbulavin * [Variadic DisposeBag for Combine subscriptions](https://nalexn.github.io/cancelbag-for-combine/?utm_source=awsui1) Alexey Naumov ## ๐Ÿ“บ Videos ### Apple WWDC 2019 * [Introducing SwiftUI: Building Your First App](https://developer.apple.com/videos/play/wwdc2019/204/) - Start here for a quick overview and demo * [SwiftUI Essentials](https://developer.apple.com/videos/play/wwdc2019/216/) - Deeper dive into how it works and the key concepts * [Data Flow Through SwiftUI](https://developer.apple.com/videos/play/wwdc2019/226/) - How to use data in SwiftUI. A single source of truth. Explains the difference between a simple property, BindableObject, @Environment, @Binding and @State * [Building Custom Views with SwiftUI](https://developer.apple.com/videos/play/wwdc2019/237/) - Dave Abrahams, with a brief appearance from Crusty, digs deeper into how the layout process works. Second part is an impressive demo of how to use graphics to draw custom controls * [Integrating SwiftUI](https://developer.apple.com/videos/play/wwdc2019/231/) - Use a hosting controller to wrap SwiftUI for use in your existing App. Use the Representable protocol to wrap existing UIKit/AppKit/WatchKit views to use in SwiftUI. Use the BindableObject protocol to integrate external data * [Mastering Xcode Previews](https://developer.apple.com/videos/play/wwdc2019/233/) - Great demos on how Xcode previews make working with SwiftUI so easy * [Accessibility in SwiftUI](https://developer.apple.com/videos/play/wwdc2019/238/) - You get a lot for free in SwiftUI but youโ€™ll likely need to tweak some things (as with UIKit). API for setting labels, traits, actions, etc. * [SwiftUI on watchOS](https://developer.apple.com/videos/play/wwdc2019/219/) - Of course, you can now build watchOS Apps with SwiftUI. * [Mastering Xcode Previews](https://developer.apple.com/videos/play/wwdc2019/233) - Learn how previews work, how to optimize the structure of your SwiftUI app for previews, and how to add preview support to your existing views and view controllers ### Apple WWDC 2020 * [Introduction to SwiftUI](https://developer.apple.com/wwdc20/10119) - Great start for the ones who are new to SwiftUI or just need a recap on SwiftUI updated for Xcode 12 and multi-platform Apps. * [Visually edit SwiftUI views](https://developer.apple.com/wwdc20/10185) - Building a view in the Xcode preview canvas. * [Build a SwiftUI view in Swift playgrounds](https://developer.apple.com/wwdc20/10643) - Prototyping SwiftUI views using Swift playgrounds on an iPad. * [Whatโ€™s new in SwiftUI](https://developer.apple.com/wwdc20/10041) - An essential session that covers all the new in latest SwiftUI. * [Stacks, Grids, and Outlines in SwiftUI](https://developer.apple.com/wwdc20/10031) - Lazy stacks and grids, sidebar lists and outlines. * [App essentials in Swift UI](https://developer.apple.com/wwdc20/10037) - No more AppDelegate and SceneDelegate. Improved scene based state restoration. * [Data essentials in SwiftUI](https://developer.apple.com/wwdc20/10040) - Let's recap on data flow in SwiftUI and get famialiar with @StateObject, @SceneStorage and @AppStorage. * [Build document-based apps in SwiftUI](https://developer.apple.com/wwdc20/10037) - Introduction th DocumentGroup for document based apps. * [Add custom views and modifiers to the Xcode library](https://developer.apple.com/wwdc20/10649) - Great addition to Xcode 12 making it easy to share views and modifiers. * [Structure your app for SwiftUI previews](https://developer.apple.com/wwdc20/10149) - Great session with lots of tips, especially the section on where to put sample preview data. * [Build SwiftUI views for widgets](https://developer.apple.com/wwdc20/10033) - Let's build a Widget using SwiftUI views. ### Tutorials * [Your First iOS and SwiftUI App](https://www.raywenderlich.com/4919757-your-first-ios-and-swiftui-app) by raywenderlich * [Swift UI: Working With UIKit](https://www.raywenderlich.com/4279893-swift-ui-working-with-uikit) by raywenderlich * [Facebook Complex Layouts - Horizontal Scroll View](https://www.youtube.com/watch?v=7QgPpvqTfeo) by Lets Build That App * [Dynamic Lists, HStack VStack, Images with Circle Clipped Stroke Overlays](https://www.youtube.com/watch?v=bz6GTYaIQXU) by Lets Build That App * [Format phone numbers as they're typed](https://www.youtube.com/watch?v=4SnmiWFvolM&ab_channel=WhatisiSwiftUI%3F) by What is iSwiftUI? * [Fetching JSON and Image Data with BindableObject](https://www.youtube.com/watch?v=xT4wGOc2jd4) by Lets Build That App * [Reactive Intro: State Management and Bindings](https://www.youtube.com/watch?v=l7vkP6WW6Yk) by Lets Build That App * [Simple SwiftUI Application](https://www.youtube.com/watch?v=Pfw7zWxchQc) by Brian Advent * [Understanding State](https://www.youtube.com/watch?v=KD4OAjQJYPc) by Martin Lasek * [SwiftUI Complete Apps](https://www.youtube.com/watch?v=VGJBLlfSN-Y&list=PLuoeXyslFTuaZtX7xSYbWz3TR0Vpz39gK) by Paul Hudson * [Collection View 2019 - Scrolling List in Swift UI](https://youtu.be/AYQHRnYT9Jc) by maxcodes * [State Management Using View Models in SwiftUI](https://youtu.be/kXsOBDymFdI) by azamsharp * [Programmatically Navigation to Destination View in SwiftUI](https://youtu.be/-VSbZrBtTGw) by azamsharp * [Integrating Core Data with SwiftUI](https://youtu.be/NLA_2DtnHyI) by azamsharp * [Understanding ObservableObject in SwiftUI](https://youtu.be/VioWHKN1eKs) by azamsharp * [Building Relative Layouts Using GeometryReader in SwiftUI](https://youtu.be/XxZUVDSdfyA) by azamsharp * [TabView in SwiftUI](https://youtu.be/yRFzfuqjZao) by azamsharp * [Integrating Camera with SwiftUI](https://youtu.be/W60nnRFUGaI) by azamsharp * [SwiftUI and Core Data - Build a To-Do List App](https://youtu.be/-BZdQmHV4MQ) by Brian Advent ## ๐Ÿ›  Examples ### Helpers * [SwiftUI by Example](https://www.hackingwithswift.com/quick-start/swiftui/) by Paul Hudson * [Learning and Usage Guide](https://github.com/Jinxiansen/SwiftUI) by Jinxiansen * [SwiftUI Cheat Sheet](https://github.com/SimpleBoilerplates/SwiftUI-Cheat-Sheet) by SimpleBoilerplates * [SwiftUI phone number text field](https://github.com/MojtabaHs/iPhoneNumberField) by MojtabaHs * [SwiftUI Image view that displays an image downloaded from provided URL](https://github.com/dmytro-anokhin/url-image) by Dmytro Anokhin * [A SwiftUI view that manages a UIViewController that responds to keyboard events with modified additionalSafeAreaInsets](https://github.com/a2/KeyboardAvoiding) by a2 * [Re-implementation of @binding and @State](https://gist.github.com/AliSoftware/ecb5dfeaa7884fc0ce96178dfdd326f8) by AliSoftware * [SwiftUI Framework Learning and Usage Guide](https://github.com/Jinxiansen/SwiftUI) by Jinxiansen * [FlowStack is a grid layout component](https://github.com/johnsusek/FlowStack) by johnsusek * [Flux pattern for SwiftUI](https://github.com/johnsusek/fluxus/blob/master/README.md) by johnsusek * [A flexible grid layout view for SwiftUI](https://github.com/pietropizzi/GridStack) by pietropizzi * [Declarative HTTP networking, designed for SwiftUI](https://github.com/carson-katri/swift-request) by carson-katri * [SwiftUI support for drag and drop on iOS](https://github.com/brunogb/SwiftUIDragDrop) by brunogb ### Libraries * [Async image loading](https://github.com/cmtrounce/SwURL) by Callum Trounce * [QGrid: The missing SwiftUI collection view](https://github.com/Q-Mobile/QGrid) by Q-Mobile * [ASCollectionView: A SwiftUI collection view](https://github.com/apptekstudios/ASCollectionView) by Apptek Studios * [Walkthrough or onboarding flow with tap actions](https://github.com/exyte/ConcentricOnboarding) by Exyte * [Render ring chart, sunburst chart and multilevel pie chart diagrams](https://github.com/lludo/SwiftSunburstDiagram) by lludo * [SwiftSpeech: A speech recognition framework designed for SwiftUI](https://github.com/Cay-Zhang/SwiftSpeech) by Cay Zhang * [CardStack: A easy-to-use SwiftUI view for Tinder like cards on iOS, macOS & watchOS](https://github.com/dadalar/SwiftUI-CardStackView) by Deniz Adalar * [Defaults: `@State` replacement for UserDefaults](https://github.com/sindresorhus/Defaults#swiftui-support) by Sindre Sorhus * [Preferences: Create a macOS preferences window in SwiftUI](https://github.com/sindresorhus/Preferences#swiftui-support) by Sindre Sorhus * [KeyboardShortcuts: SwiftUI control to set global keyboard shortcuts in your macOS app](https://github.com/sindresorhus/KeyboardShortcuts) by Sindre Sorhus * [SharedObject: A new property wrapper for SwiftUI `ObservableObject`](https://github.com/lorenzofiamingo/SwiftUI-SharedObject) * [FontIcon: Bring Material, Font Awesome 5, Ionicons font icons into SwiftUI](https://github.com/huybuidac/SwiftUIFontIcon) by Huy Bui Dac * [SyntaxHighlight: TextMate-style syntax highlighting for SwiftUI](https://github.com/maoyama/SyntaxHighlight) by maoyama ### Combine * [Hover an async combine supported network library](https://github.com/onurhuseyincantay/Hover) by Onur H. Cantay ### Open Source Apps * [Examples projects using SwiftUI released by WWDC2019. Include Layout, UI, Animations, Gestures, Draw and Data.](https://github.com/ivanvorobei/SwiftUI) by ivanvorobei * [SwiftUI & Combine app using MovieDB API](https://github.com/Dimillian/MovieSwiftUI) by Dimillian (Thomas Ricouard) * [SwiftUI MovieDB prototype app](https://github.com/alfianlosari/SwiftUI-MovieDB) by alfianlosari * [SwiftUI and Combine based GitHubSearch example](https://github.com/marty-suzuki/GitHubSearchWithSwiftUI) by marty-suzuki * [This is an example project of SwiftUI and Combine using GitHub API](https://github.com/ra1028/SwiftUI-Combine) by ra1028 * [An app that composes text over an image in SwiftUI](https://github.com/dempseyatgithub/MemeMaker) by dempseyatgithub * [A 2048 game writing with SwiftUI](https://github.com/unixzii/SwiftUI-2048) by unixzii * [Sample iOS project built by SwiftUI + MVVM and Combine framework using GitHub API](https://github.com/kitasuke/SwiftUI-MVVM) by kitasuke * [Sample iOS project built by SwiftUI + Flux and Combine framework using GitHub API](https://github.com/kitasuke/SwiftUI-Flux) by kitasuke * [ChartView made in SwiftUI](https://github.com/AppPear/ChartView) by AppPear * [Swift UI Demo for an instagram copy](https://github.com/leavenstee/InstaFake-Swift-UI) by leavenstee * [A to-do list app using SwiftUI and combine with restful api](https://github.com/jamfly/SwiftUI-Combine-todo-example) by jamfly * [Anime schedule, korean subtitle for iOS with SwiftUI + Combine and MVVM architecture](https://github.com/PangMo5/AniTime) by PangMo5 * [A notes app written in >100 lines of swift using SwiftUI](https://gist.github.com/jnewc/35692b2a5985c3c99e847ec56098a451) by jnewc * [A weather forecast app using the OpenWeather API, MapKit, and SwiftUI!](https://github.com/jhatin94/tempatlas-swiftui) by jhatin94 * [Hacker News reader built with SwiftUI and Combine](https://github.com/woxtu/SwiftUI-HackerNews) by woxtu * [Currency Converter App](https://github.com/alexliubj/SwiftUI-Currency-Converter) by alexliubj * [A basic SwiftUI chat app that leverages the new URLSessionWebSocketTask](https://github.com/niazoff/Chat) by niazoff * [A simple SwiftUI weather app using MVVM](https://github.com/niazoff/Weather) by niazoff * [Koober a ride-hailing app from Advanced iOS App Architecture book](https://github.com/raywenderlich/swiftui-example-app-koober) by raywenderlich * [Design+Code app that shows how you can use SwiftUI to create beautiful UI](https://github.com/mythxn/DesignCode-SwiftUI) by mythxn * [Shopping List app showing how to use SwiftUI with Core Data](https://github.com/ericlewis/ShoppingList) by ericlewis * [Carbode Barcode QRCode scanner](https://github.com/heart/CarBode-Barcode-Scanner-For-SwiftUI) by heart * [Clean Architecture for SwiftUI demo app](https://github.com/nalexn/clean-architecture-swiftui) by Alexey Naumov * [Address Book project with Core Data](https://github.com/hbmartin/Directory-SwiftUI) by Harold Martin * [Imgur app with SwiftUI and Combine using MVVM](https://github.com/YetAnotherRzmn/Imgur.iOS) by Nikita Razumnyi * [Mac app that shows pull request last modified each line of a file](https://github.com/maoyama/GitBlamePR) by maoyama * [Animal Crossing New Horizons Companion App](https://github.com/Dimillian/ACHNBrowserUI) by Dimillian (Thomas Ricouard) ## Apps * [Healr](https://apps.apple.com/ca/app/healr/id1492834816) by Healr Street * [Photo Widget](https://apps.apple.com/app/id1532588789) by Sindre Sorhus ## ๐Ÿ’ป Courses * [SwiftUI Quick Start Guide with iOS 13 and Xcode 11](https://www.udemy.com/course/swiftui-quick-start-guide-with-ios-13-and-xcode-11/) by DevTechie Interactive * [SwiftUI - Declarative Interfaces for any Apple Device](https://www.udemy.com/course/swiftui-declarative-interfaces-for-any-apple-device/?couponCode=SWIFTUIMEDIUM) by Mohammad Azam * [Learn SwiftUI](https://learn.designcode.io/swiftui) by Meng To * [Build an app with SwiftUI](https://designcode.io/swiftui/) by Meng To ## ๐Ÿ“– Books ### SwiftUI * [SwiftUI by Tutorials](https://store.raywenderlich.com/products/swiftui-by-tutorials) by raywenderlich.com * [SwiftUI Views](https://www.bigmountainstudio.com/swiftui-views-book) by Mark Moeykens (Big Mountain Studio) * [SwiftUI - Declarative Interfaces for any Apple Device](https://www.udemy.com/course/swiftui-declarative-interfaces-for-any-apple-device/) by Mohammad Azam ### Combine * [Combine: Asynchronous Programming with Swift](https://store.raywenderlich.com/products/combine-asynchronous-programming-with-swift) by raywenderlich.com * [Using Combine](https://heckj.github.io/swiftui-notes/) by Joseph Heck
175
A Swift wrapper for the LLVM C API (version 11.0)
# LLVMSwift [![Build Status](https://travis-ci.org/llvm-swift/LLVMSwift.svg?branch=master)](https://travis-ci.org/llvm-swift/LLVMSwift) [![Documentation](https://cdn.rawgit.com/llvm-swift/LLVMSwift/master/docs/badge.svg)](https://llvm-swift.github.io/LLVMSwift) [![Slack Invite](https://llvmswift-slack.herokuapp.com/badge.svg)](https://llvmswift-slack.herokuapp.com) LLVMSwift is a pure Swift interface to the [LLVM](http://llvm.org) API and its associated libraries. It provides native, easy-to-use components to make compiler development fun. ## Introduction ### LLVM IR The root unit of organization of an LLVM IR program is a `Module` ```swift let module = Module(name: "main") ``` LLVM IR construction is handled by `IRBuilder` objects. An `IRBuilder` is a cursor pointed inside a context, and as such has ways of extending that context and moving around inside of it. Defining a function and moving the cursor to a point where we can begin inserting instructions is done like so: ```swift let builder = IRBuilder(module: module) let main = builder.addFunction("main", type: FunctionType([], IntType.int64)) let entry = main.appendBasicBlock(named: "entry") builder.positionAtEnd(of: entry) ``` Inserting instructions creates native `IRValue` placeholder objects that allow us to structure LLVM IR programs just like Swift programs: ```swift let constant = IntType.int64.constant(21) let sum = builder.buildAdd(constant, constant) builder.buildRet(sum) ``` This simple program generates the following IR: ```llvm // module.dump() define i64 @main() { entry: ret i64 42 } ``` ### Types LLVM IR is a strong, statically typed language. As such, values and functions are tagged with their types, and conversions between them must be explicit (see [Conversion Operators](http://llvm.org/docs/LangRef.html#conversion-operations)). LLVMSwift represents this with values conforming to the `IRType` protocol and defines the following types: |**Type** | **Represents** | |:---:|:---:| | VoidType | Nothing; Has no size | | IntType | Integer and Boolean values (`i1`) | | FloatType | Floating-point values | | FunctionType | Function values | | LabelType | Code labels | | TokenType | Values paired with instructions | | MetadataType | Embedded metadata | | X86MMXType | X86 MMX values | | PointerType | Pointer values | | VectorType | SIMD data | | ArrayType | Homogeneous values | | Structure Type | Heterogeneous values | ### Control Flow Control flow is changed through the unconditional and conditional `br` instruction. LLVM is also famous for a control-flow specific IR construct called a [PHI node](http://llvm.org/docs/LangRef.html#phi-instruction). Because all instructions in LLVM IR are in SSA (Single Static Assignment) form, a PHI node is necessary when the value of a variable assignment depends on the path the flow of control takes through the program. For example, let's try to build the following Swift program in IR: ```swift func calculateFibs(_ backward : Bool) -> Double { let retVal : Double if !backward { // the fibonacci series (sort of) retVal = 1/89 } else { // the fibonacci series (sort of) backwards retVal = 1/109 } return retVal } ``` Notice that the value of `retVal` depends on the path the flow of control takes through this program, so we must emit a PHI node to properly initialize it: ```swift let function = builder.addFunction("calculateFibs", type: FunctionType([IntType.int1], FloatType.double)) let entryBB = function.appendBasicBlock(named: "entry") builder.positionAtEnd(of: entryBB) // allocate space for a local value let local = builder.buildAlloca(type: FloatType.double, name: "local") // Compare to the condition let test = builder.buildICmp(function.parameters[0], IntType.int1.zero(), .equal) // Create basic blocks for "then", "else", and "merge" let thenBB = function.appendBasicBlock(named: "then") let elseBB = function.appendBasicBlock(named: "else") let mergeBB = function.appendBasicBlock(named: "merge") builder.buildCondBr(condition: test, then: thenBB, else: elseBB) // MARK: Then Block builder.positionAtEnd(of: thenBB) // local = 1/89, the fibonacci series (sort of) let thenVal = FloatType.double.constant(1/89) // Branch to the merge block builder.buildBr(mergeBB) // MARK: Else Block builder.positionAtEnd(of: elseBB) // local = 1/109, the fibonacci series (sort of) backwards let elseVal = FloatType.double.constant(1/109) // Branch to the merge block builder.buildBr(mergeBB) // MARK: Merge Block builder.positionAtEnd(of: mergeBB) let phi = builder.buildPhi(FloatType.double, name: "phi_example") phi.addIncoming([ (thenVal, thenBB), (elseVal, elseBB), ]) builder.buildStore(phi, to: local) let ret = builder.buildLoad(local, type: FloatType.double, name: "ret") builder.buildRet(ret) ``` This program generates the following IR: ```llvm define double @calculateFibs(i1) { entry: %local = alloca double %1 = icmp ne i1 %0, false br i1 %1, label %then, label %else then: ; preds = %entry br label %merge else: ; preds = %entry br label %merge merge: ; preds = %else, %then %phi_example = phi double [ 0x3F8702E05C0B8170, %then ], [ 0x3F82C9FB4D812CA0, %else ] store double %phi_example, double* %local %ret = load double, double* %local ret double %ret } ``` ### JIT LLVMSwift provides a JIT abstraction to make executing code in LLVM modules quick and easy. Let's execute the PHI node example from before: ```swift // Setup the JIT let jit = try JIT(machine: TargetMachine()) typealias FnPtr = @convention(c) (Bool) -> Double _ = try jit.addEagerlyCompiledIR(module) { (name) -> JIT.TargetAddress in return JIT.TargetAddress() } // Retrieve a handle to the function we're going to invoke let addr = try jit.address(of: "calculateFibs") let fn = unsafeBitCast(addr, to: FnPtr.self) // Call the function! print(fn(true)) // 0.00917431192660551... print(fn(false)) // 0.0112359550561798... ``` ## Installation There are a couple annoying steps you need to accomplish before building LLVMSwift: - Install LLVM 11.0+ using your favorite package manager. For example: - `brew install llvm@11` - Ensure `llvm-config` is in your `PATH` - That will reside in the `/bin` folder wherever your package manager installed LLVM. - Create a pkg-config file for your specific LLVM installation. - We have a utility for this: `swift utils/make-pkgconfig.swift` Once you do that, you can add LLVMSwift as a dependency for your own Swift compiler projects! ### Installation with Swift Package Manager ```swift .package(url: "https://github.com/llvm-swift/LLVMSwift.git", from: "0.8.0") ``` ### Installation without Swift Package Manager We really recommend using SwiftPM with LLVMSwift, but if your project is structured in such a way that makes using SwiftPM impractical or impossible, use the following instructions: - Xcode: - Add this repository as a git submodule - Add the files in `Sources/` to your Xcode project. - Under `Library Search Paths` add the output of `llvm-config --libdir` - Under `Header Search Paths` add the output of `llvm-config --includedir` - Under `Link Target with Libraries` drag in `/path/to/your/llvm/lib/libLLVM.dylib` This project is used by [Trill](https://github.com/harlanhaskins/trill) for all its code generation. ## Authors - Harlan Haskins ([@harlanhaskins](https://github.com/harlanhaskins)) - Robert Widmann ([@CodaFi](https://github.com/CodaFi)) ## License This project is released under the MIT license, a copy of which is available in this repo.
176
Unidirectional Data Flow in Swift - Inspired by Redux
# ReSwift [![Build Status](https://img.shields.io/travis/ReSwift/ReSwift/master.svg?style=flat-square)](https://travis-ci.org/ReSwift/ReSwift) [![Code coverage status](https://img.shields.io/codecov/c/github/ReSwift/ReSwift.svg?style=flat-square)](http://codecov.io/github/ReSwift/ReSwift) [![CocoaPods Compatible](https://img.shields.io/cocoapods/v/ReSwift.svg?style=flat-square)](https://cocoapods.org/pods/ReSwift) [![Platform support](https://img.shields.io/badge/platform-ios%20%7C%20osx%20%7C%20tvos%20%7C%20watchos-lightgrey.svg?style=flat-square)](https://github.com/ReSwift/ReSwift/blob/master/LICENSE.md) [![License MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/ReSwift/ReSwift/blob/master/LICENSE.md) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg?style=flat-square)](https://houndci.com) **Supported Swift Versions:** Swift 4.2, 5.x For Swift 3.2 or 4.0 Support use [Release 5.0.0](https://github.com/ReSwift/ReSwift/releases/tag/5.0.0) or earlier. For Swift 2.2 Support use [Release 2.0.0](https://github.com/ReSwift/ReSwift/releases/tag/2.0.0) or earlier. # Introduction ReSwift is a [Redux](https://github.com/reactjs/redux)-like implementation of the unidirectional data flow architecture in Swift. ReSwift helps you to separate three important concerns of your app's components: - **State**: in a ReSwift app the entire app state is explicitly stored in a data structure. This helps avoid complicated state management code, enables better debugging and has many, many more benefits... - **Views**: in a ReSwift app your views update when your state changes. Your views become simple visualizations of the current app state. - **State Changes**: in a ReSwift app you can only perform state changes through actions. Actions are small pieces of data that describe a state change. By drastically limiting the way state can be mutated, your app becomes easier to understand and it gets easier to work with many collaborators. The ReSwift library is tiny - allowing users to dive into the code, understand every single line and [hopefully contribute](#contributing). ReSwift is quickly growing beyond the core library, providing experimental extensions for routing and time traveling through past app states! Excited? So are we ๐ŸŽ‰ Check out our [public gitter chat!](https://gitter.im/ReSwift/public) # Table of Contents - [About ReSwift](#about-reswift) - [Why ReSwift?](#why-reswift) - [Getting Started Guide](#getting-started-guide) - [Installation](#installation) - [Checking Out Source Code](#checking-out-source-code) - [Demo](#demo) - [Extensions](#extensions) - [Example Projects](#example-projects) - [Contributing](#contributing) - [Credits](#credits) - [Get in touch](#get-in-touch) # About ReSwift ReSwift relies on a few principles: - **The Store** stores your entire app state in the form of a single data structure. This state can only be modified by dispatching Actions to the store. Whenever the state in the store changes, the store will notify all observers. - **Actions** are a declarative way of describing a state change. Actions don't contain any code, they are consumed by the store and forwarded to reducers. Reducers will handle the actions by implementing a different state change for each action. - **Reducers** provide pure functions, that based on the current action and the current app state, create a new app state ![](Docs/img/reswift_concept.png) For a very simple app, that maintains a counter that can be increased and decreased, you can define the app state as following: ```swift struct AppState { var counter: Int = 0 } ``` You would also define two actions, one for increasing and one for decreasing the counter. In the [Getting Started Guide](http://reswift.github.io/ReSwift/master/getting-started-guide.html) you can find out how to construct complex actions. For the simple actions in this example we can define empty structs that conform to action: ```swift struct CounterActionIncrease: Action {} struct CounterActionDecrease: Action {} ``` Your reducer needs to respond to these different action types, that can be done by switching over the type of action: ```swift func counterReducer(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() switch action { case _ as CounterActionIncrease: state.counter += 1 case _ as CounterActionDecrease: state.counter -= 1 default: break } return state } ``` In order to have a predictable app state, it is important that the reducer is always free of side effects, it receives the current app state and an action and returns the new app state. To maintain our state and delegate the actions to the reducers, we need a store. Let's call it `mainStore` and define it as a global constant, for example in the app delegate file: ```swift let mainStore = Store<AppState>( reducer: counterReducer, state: nil ) @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { [...] } ``` Lastly, your view layer, in this case a view controller, needs to tie into this system by subscribing to store updates and emitting actions whenever the app state needs to be changed: ```swift class CounterViewController: UIViewController, StoreSubscriber { @IBOutlet var counterLabel: UILabel! override func viewWillAppear(_ animated: Bool) { mainStore.subscribe(self) } override func viewWillDisappear(_ animated: Bool) { mainStore.unsubscribe(self) } func newState(state: AppState) { counterLabel.text = "\(state.counter)" } @IBAction func increaseButtonTapped(_ sender: UIButton) { mainStore.dispatch( CounterActionIncrease() ) } @IBAction func decreaseButtonTapped(_ sender: UIButton) { mainStore.dispatch( CounterActionDecrease() ) } } ``` The `newState` method will be called by the `Store` whenever a new app state is available, this is where we need to adjust our view to reflect the latest app state. Button taps result in dispatched actions that will be handled by the store and its reducers, resulting in a new app state. This is a very basic example that only shows a subset of ReSwift's features, read the Getting Started Guide to see how you can build entire apps with this architecture. For a complete implementation of this example see the [CounterExample](https://github.com/ReSwift/CounterExample) project. ### Create a subscription of several substates combined Just create a struct representing the data model needed in the subscriber class, with a constructor that takes the whole app state as a param. Consider this constructor as a mapper/selector from the app state to the subscriber state. Being `MySubState` a struct and conforming to `Equatable`, ReSwift (by default) will not notify the subscriber if the computed output hasn't changed. Also, Swift will be able to infer the type of the subscription. ```swift struct MySubState: Equatable { // Combined substate derived from the app state. init(state: AppState) { // Compute here the substate needed. } } ``` ```swift store.subscribe(self) { $0.select(MySubState.init) } func newState(state: MySubState) { // Profit! } ``` # Why ReSwift? Model-View-Controller (MVC) is not a holistic application architecture. Typical Cocoa apps defer a lot of complexity to controllers since MVC doesn't offer other solutions for state management, one of the most complex issues in app development. Apps built upon MVC often end up with a lot of complexity around state management and propagation. We need to use callbacks, delegations, Key-Value-Observation and notifications to pass information around in our apps and to ensure that all the relevant views have the latest state. This approach involves a lot of manual steps and is thus error prone and doesn't scale well in complex code bases. It also leads to code that is difficult to understand at a glance, since dependencies can be hidden deep inside of view controllers. Lastly, you mostly end up with inconsistent code, where each developer uses the state propagation procedure they personally prefer. You can circumvent this issue by style guides and code reviews but you cannot automatically verify the adherence to these guidelines. ReSwift attempts to solve these problem by placing strong constraints on the way applications can be written. This reduces the room for programmer error and leads to applications that can be easily understood - by inspecting the application state data structure, the actions and the reducers. This architecture provides further benefits beyond improving your code base: - Stores, Reducers, Actions and extensions such as ReSwift Router are entirely platform independent - you can easily use the same business logic and share it between apps for multiple platforms (iOS, tvOS, etc.) - Want to collaborate with a co-worker on fixing an app crash? Use [ReSwift Recorder](https://github.com/ReSwift/ReSwift-Recorder) to record the actions that lead up to the crash and send them the JSON file so that they can replay the actions and reproduce the issue right away. - Maybe recorded actions can be used to build UI and integration tests? The ReSwift tooling is still in a very early stage, but aforementioned prospects excite me and hopefully others in the community as well! [You can also watch this talk on the motivation behind ReSwift](https://academy.realm.io/posts/benji-encz-unidirectional-data-flow-swift/). # Getting Started Guide [A Getting Started Guide that describes the core components of apps built with ReSwift lives here](http://reswift.github.io/ReSwift/master/getting-started-guide.html). To get an understanding of the core principles we recommend reading the brilliant [redux documentation](http://redux.js.org/). # Installation ## CocoaPods You can install ReSwift via [CocoaPods](https://cocoapods.org/) by adding it to your `Podfile`: ``` use_frameworks! source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' pod 'ReSwift' ``` And run `pod install`. ## Carthage You can install ReSwift via [Carthage](https://github.com/Carthage/Carthage) by adding the following line to your `Cartfile`: ``` github "ReSwift/ReSwift" ``` ## Accio You can install ReSwift via [Accio](https://github.com/JamitLabs/Accio) by adding the following line to your `Package.swift`: ```swift .package(url: "https://github.com/ReSwift/ReSwift.git", .upToNextMajor(from: "5.0.0")), ``` Next, add `ReSwift` to your App targets dependencies like so: ```swift .target( name: "App", dependencies: [ "ReSwift", ] ), ``` Then run `accio update`. ## Swift Package Manager You can install ReSwift via [Swift Package Manager](https://swift.org/package-manager/) by adding the following line to your `Package.swift`: ```swift import PackageDescription let package = Package( [...] dependencies: [ .package(url: "https://github.com/ReSwift/ReSwift.git", from: "5.0.0"), ] ) ``` # Checking out Source Code After checking out the project run `pod install` to get the latest supported version of [SwiftLint](https://github.com/realm/SwiftLint), which we use to ensure a consistent style in the codebase. # Demo Using this library you can implement apps that have an explicit, reproducible state, allowing you, among many other things, to replay and rewind the app state, as shown below: ![](Docs/img/timetravel.gif) # Extensions This repository contains the core component for ReSwift, the following extensions are available: - [ReSwift-Thunk](https://github.com/ReSwift/ReSwift-Thunk): Provides a ReSwift middleware that lets you dispatch thunks (action creators) to encapsulate processes like API callbacks. - [ReSwift-Router](https://github.com/ReSwift/ReSwift-Router): Provides a ReSwift compatible Router that allows declarative routing in iOS applications - [ReSwift-Recorder](https://github.com/ReSwift/ReSwift-Recorder): Provides a `Store` implementation that records all `Action`s and allows for hot-reloading and time travel # Example Projects - [CounterExample](https://github.com/ReSwift/CounterExample): A very simple counter app implemented with ReSwift. - [CounterExample-Navigation-TimeTravel](https://github.com/ReSwift/CounterExample-Navigation-TimeTravel): This example builds on the simple CounterExample app, adding time travel with [ReSwiftRecorder](https://github.com/ReSwift/ReSwift-Recorder) and routing with [ReSwiftRouter](https://github.com/ReSwift/ReSwift-Router). - [GitHubBrowserExample](https://github.com/ReSwift/GitHubBrowserExample): A real world example, involving authentication, network requests and navigation. Still WIP but should be the best resource for starting to adapt `ReSwift` in your own app. - [ReduxMovieDB](https://github.com/cardoso/ReduxMovieDB): A simple App that queries the tmdb.org API to display the latest movies. Allows searching and viewing details. - [Meet](https://github.com/Ben-G/Meet): A real world application being built with ReSwift - currently still very early on. It is not up to date with the latest version of ReSwift, but is the best project for demonstrating time travel. - [Redux-Twitter](https://github.com/Goktug/Redux-Twitter): A basic Twitter search implementation built with ReSwift and RxSwift, involing Twitter authentication, network requests and navigation. ## Production Apps with Open Source Code - [Persephone](https://github.com/danbee/persephone), a MPD music player daemon controller for macOS - [Product Hunt for OS X](https://github.com/producthunt/producthunt-osx) Official Product Hunt client for macOS # Contributing There's still a lot of work to do here! We would love to see you involved! You can find all the details on how to get started in the [Contributing Guide](/CONTRIBUTING.md). # Credits - Thanks a lot to [Dan Abramov](https://github.com/gaearon) for building [Redux](https://github.com/reactjs/redux) - all ideas in here and many implementation details were provided by his library. # Get in touch If you have any questions, you can find the core team on twitter: - [@benjaminencz](https://twitter.com/benjaminencz) - [@karlbowden](https://twitter.com/karlbowden) - [@ARendtslev](https://twitter.com/ARendtslev) - [@ctietze](https://twitter.com/ctietze) - [@mjarvis](https://twitter.com/mjarvis) We also have a [public gitter chat!](https://gitter.im/ReSwift/public)
177
ไธ€ไธช็บฏ Swift ็š„่ฝป้‡็บงใ€็ตๆดปไธ”ๆ˜“ไบŽไฝฟ็”จ็š„ pageView
# DNSPageView [![Version](https://img.shields.io/cocoapods/v/DNSPageView.svg?style=flat)](http://cocoapods.org/pods/DNSPageView) [![License](https://img.shields.io/cocoapods/l/DNSPageView.svg?style=flat)](http://cocoapods.org/pods/DNSPageView) [![Platform](https://img.shields.io/cocoapods/p/DNSPageView.svg?style=flat)](http://cocoapods.org/pods/DNSPageView) [English Introduction](https://github.com/Danie1s/DNSPageView/blob/master/README_EN.md) DNSPageView ไธ€ไธช็บฏ Swift ็š„่ฝป้‡็บงใ€็ตๆดปไธ”ๆ˜“ไบŽไฝฟ็”จ็š„ `PageView` ๆก†ๆžถ๏ผŒ`titleView` ๅ’Œ `contentView` ๅฏไปฅๅธƒๅฑ€ๅœจไปปๆ„ๅœฐๆ–น๏ผŒๅฏไปฅ็บฏไปฃ็ ๅˆๅง‹ๅŒ–๏ผŒไนŸๅฏไปฅไฝฟ็”จ `xib` ๆˆ–่€… `storyboard` ๅˆๅง‹ๅŒ–๏ผŒๅนถไธ”ๆไพ›ไบ†ๅธธ่งๆ ทๅผๅฑžๆ€ง่ฟ›่กŒ่ฎพ็ฝฎใ€‚ ๅฆ‚ๆžœไฝ ไฝฟ็”จ็š„ๅผ€ๅ‘่ฏญ่จ€ๆ˜ฏ Objective-C๏ผŒ่ฏทไฝฟ็”จ [DNSPageView-ObjC](https://github.com/Danie1s/DNSPageView-ObjC) - [Features](#features) - [Requirements](#requirements) - [Installation](#installation) - [Example](#example) - [Usage](#usage) - [็›ดๆŽฅไฝฟ็”จ PageView ๅˆๅง‹ๅŒ–](#็›ดๆŽฅไฝฟ็”จ-pageview-ๅˆๅง‹ๅŒ–) - [ไฝฟ็”จ xib ๆˆ–่€… storyboard ๅˆๅง‹ๅŒ–](#ไฝฟ็”จ-xib-ๆˆ–่€…-storyboard-ๅˆๅง‹ๅŒ–) - [ไฝฟ็”จ PageViewManager ๅˆๅง‹ๅŒ–](#ไฝฟ็”จ-pageviewmanager-ๅˆๅง‹ๅŒ–) - [ๆ ทๅผ ](#ๆ ทๅผ) - [ไบ‹ไปถๅ›ž่ฐƒ](#ไบ‹ไปถๅ›ž่ฐƒ) - [ๅธธ่ง้—ฎ้ข˜](#ๅธธ่ง้—ฎ้ข˜) - [License](#license) ## Features: - [x] ไฝฟ็”จ็ฎ€ๅ• - [x] ๅคš็งๅˆๅง‹ๅŒ–ๆ–นๅผ - [x] ็ตๆดปๅธƒๅฑ€ - [x] ๅธธ่ง็š„ๆ ทๅผ - [x] ๅŒๅ‡ป `titleView` ็š„ๅ›ž่ฐƒ - [x] `contentView` ๆป‘ๅŠจ็›‘ๅฌ - [x] ้€‚้… iOS 13 Dark Mode - [x] ๅŠจๆ€ๆ”นๅ˜ๆ ทๅผ - [x] ้€‚้… RTL ๅธƒๅฑ€ ## Requirements - iOS 9.0+ - Xcode 10.2+ - Swift 5.0+ ## Installation ### CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: ```bash $ gem install cocoapods ``` > CocoaPods 1.1+ is required to build DNSPageView. To integrate DNSPageView into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '9.0' use_frameworks! target '<Your Target Name>' do pod 'DNSPageView' end ``` Then, run the following command: ```bash $ pod install ``` ### Manually If you prefer not to use any of the aforementioned dependency managers, you can integrate DNSPageView into your project manually. ## Example To run the example project, clone the repo, and run `DNSPageView.xcodeproj` . <img src="https://github.com/Danie1s/DNSPageView/blob/master/Images/1.gif" width="30%" height="30%"> <img src="https://github.com/Danie1s/DNSPageView/blob/master/Images/2.gif" width="30%" height="30%"> <img src="https://github.com/Danie1s/DNSPageView/blob/master/Images/3.gif" width="30%" height="30%"> <img src="https://github.com/Danie1s/DNSPageView/blob/master/Images/4.gif" width="30%" height="30%"> ## Usage ### ็›ดๆŽฅไฝฟ็”จ PageView ๅˆๅง‹ๅŒ– ```swift // ๅˆ›ๅปบ PageStyle๏ผŒ่ฎพ็ฝฎๆ ทๅผ let style = PageStyle() style.isTitleViewScrollEnabled = true style.isTitleScaleEnabled = true // ่ฎพ็ฝฎๆ ‡้ข˜ๅ†…ๅฎน let titles = ["ๅคดๆก", "่ง†้ข‘", "ๅจฑไน", "่ฆ้—ฎ", "ไฝ“่‚ฒ" , "็ง‘ๆŠ€" , "ๆฑฝ่ฝฆ" , "ๆ—ถๅฐš" , "ๅ›พ็‰‡" , "ๆธธๆˆ" , "ๆˆฟไบง"] // ๅˆ›ๅปบๆฏไธ€้กตๅฏนๅบ”็š„ controller let childViewControllers: [UIViewController] = titles.map { _ -> UIViewController in let controller = UIViewController() addChild(controller) return controller } let y = UIApplication.shared.statusBarFrame.height + (navigationController?.navigationBar.frame.height ?? 0) let size = UIScreen.main.bounds.size // ๅˆ›ๅปบๅฏนๅบ”็š„ PageView๏ผŒๅนถ่ฎพ็ฝฎๅฎƒ็š„ frame // titleView ๅ’Œ contentView ไผš่ฟžๅœจไธ€่ตท let pageView = PageView(frame: CGRect(x: 0, y: y, width: size.width, height: size.height - y), style: style, titles: titles, childViewControllers: childViewControllers) view.addSubview(pageView) ``` ### ไฝฟ็”จ xib ๆˆ–่€… storyboard ๅˆๅง‹ๅŒ– ๅœจ `xib` ๆˆ–่€… `storyboard` ไธญๆ‹–ๅ‡บ 2 ไธช `UIView`๏ผŒ่ฎฉๅฎƒไปฌๅˆ†ๅˆซ็ปงๆ‰ฟ `PageTitleView` ๅ’Œ `PageContentView`๏ผŒๆ‹–็บฟๅˆฐไปฃ็ ไธญ ```swift @IBOutlet weak var titleView: PageTitleView! @IBOutlet weak var contentView: PageContentView! ``` ๅฏน PageTitleView ๅ’Œ PageContentView ่ฟ›่กŒ่ฎพ็ฝฎ ```swift // ๅˆ›ๅปบ PageStyle๏ผŒ่ฎพ็ฝฎๆ ทๅผ let style = PageStyle() style.titleViewBackgroundColor = UIColor.red style.isShowCoverView = true // ่ฎพ็ฝฎๆ ‡้ข˜ๅ†…ๅฎน let titles = ["ๅคดๆก", "่ง†้ข‘", "ๅจฑไน", "่ฆ้—ฎ", "ไฝ“่‚ฒ"] // ่ฎพ็ฝฎ้ป˜่ฎค็š„่ตทๅง‹ไฝ็ฝฎ let startIndex = 2 // ๅˆ›ๅปบๆฏไธ€้กตๅฏนๅบ”็š„ controller let childViewControllers: [UIViewController] = titles.map { _ -> UIViewController in let controller = UIViewController() addChild(controller) return controller } // ๅˆ›ๅปบ PageViewManager ๆฅ่ฎพ็ฝฎๅฎƒไปฌ็š„ๆ ทๅผๅ’Œๅธƒๅฑ€ let pageViewManager = PageViewManager(style: style, titles: titles, childViewControllers: children, currentIndex: currentIndex, titleView: titleView, contentView: contentView) ``` ### ไฝฟ็”จ PageViewManager ๅˆๅง‹ๅŒ– ๅˆ›ๅปบ PageViewManager ```swift private lazy var pageViewManager: PageViewManager = { // ๅˆ›ๅปบ PageStyle๏ผŒ่ฎพ็ฝฎๆ ทๅผ let style = PageStyle() style.isShowBottomLine = true style.isTitleViewScrollEnabled = true style.titleViewBackgroundColor = UIColor.clear // ่ฎพ็ฝฎๆ ‡้ข˜ๅ†…ๅฎน let titles = ["ๅคดๆก", "่ง†้ข‘", "ๅจฑไน", "่ฆ้—ฎ", "ไฝ“่‚ฒ"] // ๅˆ›ๅปบๆฏไธ€้กตๅฏนๅบ”็š„ controller let childViewControllers: [UIViewController] = titles.map { _ -> UIViewController in let controller = UIViewController() addChild(controller) return controller } return PageViewManager(style: style, titles: titles, childViewControllers: childViewControllers) }() ``` ๅธƒๅฑ€ titleView ๅ’Œ contentView ```swift // ๅ•็‹ฌ่ฎพ็ฝฎ titleView ็š„ frame navigationItem.titleView = pageViewManager.titleView pageViewManager.titleView.frame = CGRect(x: 0, y: 0, width: 180, height: 44) // ๅ•็‹ฌ่ฎพ็ฝฎ contentView ็š„ๅคงๅฐๅ’Œไฝ็ฝฎ๏ผŒๅฏไปฅไฝฟ็”จ autolayout ๆˆ–่€… frame let contentView = pageViewManager.contentView view.addSubview(pageViewManager.contentView) contentView.snp.makeConstraints { (maker) in maker.edges.equalToSuperview() } ``` ### ๆ ทๅผ `PageStyle` ไธญๆไพ›ไบ†ๅธธ่งๆ ทๅผ็š„ๅฑžๆ€ง๏ผŒๅฏไปฅๆŒ‰็…งไธๅŒ็š„้œ€ๆฑ‚่ฟ›่กŒ่ฎพ็ฝฎ๏ผŒๅŒ…ๆ‹ฌๅฏไปฅ่ฎพ็ฝฎๅˆๅง‹ๆ˜พ็คบ็š„้กต้ข ### ไบ‹ไปถๅ›ž่ฐƒ DNSPageView ๆไพ›ไบ†ๅธธ่งไบ‹ไปถ็›‘ๅฌๅ›ž่ฐƒ๏ผŒๅฎƒๅฑžไบŽ `PageTitleViewDelegate` ็š„ไธญ็š„ๅฏ้€‰ๅฑžๆ€ง ```swift /// DNSPageView ็š„ไบ‹ไปถๅ›ž่ฐƒ๏ผŒๅฆ‚ๆžœๆœ‰้œ€่ฆ๏ผŒ่ฏท่ฎฉๅฏนๅบ”็š„ childViewController ้ตๅฎˆ่ฟ™ไธชๅ่ฎฎ @objc public protocol PageEventHandleable: class { /// ้‡ๅค็‚นๅ‡ป pageTitleView ๅŽ่ฐƒ็”จ @objc optional func titleViewDidSelectSameTitle() /// pageContentView ็š„ไธŠไธ€้กตๆถˆๅคฑ็š„ๆ—ถๅ€™๏ผŒไธŠไธ€้กตๅฏนๅบ”็š„ controller ่ฐƒ็”จ @objc optional func contentViewDidDisappear() /// pageContentView ๆปšๅŠจๅœๆญข็š„ๆ—ถๅ€™๏ผŒๅฝ“ๅ‰้กตๅฏนๅบ”็š„ controller ่ฐƒ็”จ @objc optional func contentViewDidEndScroll() } ``` ### ๅธธ่ง้—ฎ้ข˜ - `style.isTitleViewScrollEnabled` ๅฆ‚ๆžœ `titles` ็š„ๆ•ฐ้‡ๆฏ”่พƒๅฐ‘๏ผŒๅปบ่ฎฎ่ฎพ็ฝฎ `style.isTitleViewScrollEnabled = false`๏ผŒ`titleView` ไผšๅ›บๅฎš๏ผŒ`style.titleMargin` ไธ่ตทไฝœ็”จ๏ผŒๆฏไธช `title` ๅนณๅˆ†ๆ•ดไธช `titleView` ็š„ๅฎฝๅบฆ๏ผŒไธ‹ๅˆ’็บฟ็š„ๅฎฝๅบฆ็ญ‰ไบŽ`title` ็š„ๅฎฝๅบฆใ€‚ ๅฆ‚ๆžœๆ ‡็ญพๆฏ”่พƒๅคš๏ผŒๅปบ่ฎฎ่ฎพ็ฝฎ `style.isTitleViewScrollEnabled = true`๏ผŒ`titleView` ไผšๆป‘ๅŠจ๏ผŒไธ‹ๅˆ’็บฟ็š„ๅฎฝๅบฆ้š็€ `title` ๆ–‡ๅญ—็š„ๅฎฝๅบฆๅ˜ๅŒ–่€Œๅ˜ๅŒ– - ๆ ‡็ญพไธ‹ๅˆ’็บฟ็š„ๅฎฝๅบฆ่ทŸ้šๆ–‡ๅญ—็š„ๅฎฝๅบฆ ่ฎพ็ฝฎ `style.isTitleViewScrollEnabled = true`๏ผŒๅฏไปฅๅ‚่€ƒ `Demo` ไธญ็š„็ฌฌๅ››็งๆ ทๅผใ€‚ - ็”ฑไบŽ `DNSPageView` ๆ˜ฏๅŸบไบŽ `UIScrollView` ๅฎž็Žฐ๏ผŒ้‚ฃไนˆๅฐฑๆ— ๆณ•้ฟๅ…ๅฎƒ็š„ไธ€ไบ›็‰นๆ€ง๏ผš - ๅฝ“ๆŽงๅˆถๅ™จ่ขซ `UINavigationController` ็ฎก็†๏ผŒไธ” `navigationBar.isTranslucent = true` ็š„ๆ—ถๅ€™๏ผŒๅฝ“ๅ‰ๆŽงๅˆถๅ™จ็š„ `view` ๆ˜ฏไปŽ `y = 0` ๅผ€ๅง‹ๅธƒๅฑ€็š„๏ผŒๆ‰€ไปฅไธบไบ†้˜ฒๆญข้ƒจๅˆ†ๅ†…ๅฎน่ขซ `navigationBar` ้ฎๆŒก๏ผŒ็ณป็ปŸ้ป˜่ฎคไผš็ป™ `UIScrollView` ๆทปๅŠ  offsetใ€‚ๅฆ‚ๆžœๆƒณๅ–ๆถˆ่ฟ™ไธช็‰นๆ€ง๏ผš - iOS 11 ไปฅๅ‰๏ผŒๅœจๆŽงๅˆถๅ™จไธญ่ฎพ็ฝฎ `automaticallyAdjustsScrollViewInsets = false ` - iOS 11 ไปฅๅŽๅผ•ๅ…ฅ `SafeArea` ๆฆ‚ๅฟต๏ผŒ่ฎพ็ฝฎ `UIScrollView` ็š„ๅฑžๆ€ง `contentInsetAdjustmentBehavior = .never` - ๅ…ถๅฎž่ฟ™ไธชๆ•ˆๆžœ่ฟ˜ไธŽ `UIViewController` ็š„ๅ…ถไป–ๅฑžๆ€งๆœ‰ๅ…ณ็ณป๏ผŒไฝ†ๅ› ไธบๅ„็ง็ป„ๅˆ็š„ๆƒ…ๆ™ฏ่ฟ‡ไบŽๅคๆ‚๏ผŒๆ‰€ไปฅไธๅœจๆญคไธ€ไธ€ๆ่ฟฐ - `PageContentView` ็”จ `UICollectionView` ๅฎž็Žฐ๏ผŒๆ‰€ไปฅ่ฟ™ไธช็‰นๆ€งๆœ‰ๆœบไผš้€ ๆˆ `UICollectionView` ็š„็ปๅ…ธ่ญฆๅ‘Š๏ผš > The behavior of the UICollectionViewFlowLayout is not defined because: > > the item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values ไปŽ่€Œๅผ•ๅ‘ไธ€ไบ› Bug - ไปฅไธŠๅชๆ˜ฏๅฏ่ƒฝๅ‡บ็Žฐ็š„ Bug ไน‹ไธ€๏ผŒ็”ฑไบŽ `Demo` ไธ่ƒฝ่ฆ†็›–ๆ‰€ๆœ‰็š„ๅœบๆ™ฏ๏ผŒไธๅŒ็š„ๅธƒๅฑ€้œ€ๆฑ‚ๅฏ่ƒฝไผšๅผ•่ตทไธๅŒ็š„ Bug๏ผŒๅผ€ๅ‘่€…้œ€่ฆๆ˜Ž็กฎไบ†่งฃ่‡ชๅทฑ็š„ๅธƒๅฑ€้œ€ๆฑ‚๏ผŒๆณจๆ„็ป†่Š‚๏ผŒไบ†่งฃ iOS ๅธƒๅฑ€็‰นๆ€ง๏ผŒๅนถไธ”ไฝœๅ‡บๅฏนๅบ”็š„่ฐƒๆ•ด๏ผŒไธ่ƒฝๅฎŒๅ…จๅ‚็…ง `Demo`ใ€‚ ## License DNSPageView is available under the MIT license. See the LICENSE file for more info.
178
This is the demos to show 30 demos finishes in 30 days (or more)
All the codes have been updated to Swift 4.1. ![](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/bannerForSwift.png) # 30-swift-projects-in-30-days ไธญๆ–‡็‰ˆ๏ผš[ๆŠ“ไฝiOS็š„ๆœชๆฅ - 30ๅคฉๅญฆไน ็ผ–ๅ†™30ไธชSwiftๅฐ็จ‹ๅบ](http://www.jianshu.com/p/c6ae28964ad5) For any problem, please send me the e-mail: [email protected]. Project 30 - Google Now App ![GoogleNow.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/30.Google%20Now/GoogleNow.gif) What I learned: - How to do Transition Animation for Present/Dismiss - How to do combine animation based on [BubbleTransition](https://github.com/andreamazz/BubbleTransition) - Draw round button, the codes are: ```` triggerButton.layer.cornerRadius = triggerButton.frame.width / 2 triggerButton.layer.masksToBounds = true ```` Project 29 - Beauty Contest ![BeautyContest.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/29.Beauty%20Contest/BeautyContest.gif) What I learned - This project is based on [Yalantis็š„Koloda](https://github.com/Yalantis), Koloda is a very useful UIImage Selector. - Two ways to use lazy load in Swift: ```` lazy var firstWay = "first" ```` And ```` lazy var secondWay: String = {return "Second"}() ```` Warning: For the second way, you must define the TYPE FIRST, so the complier could check in the beginning. Project 28 - SnapChat Like App ![Snap Chat Like App.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/28.SnapChatLikeApp/Snap%20Chat%20Like%20App.gif) What I learned - Usage of UIScrollView, e.g., how to forbidden bounces property, isPagingEnabled property, and contentOffset property - How to use addChildViewController - How to use AVCaptureSession Project 27: Carousel Effect (่ท‘้ฉฌ็ฏๆ•ˆๆžœ) ![Carousel Effect.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/27.Carousel%20Effect/Carousel%20Effect.gif) What I learned - Usage of UICollectionView, for example, to deal with padding within cells, you could adjust with minimumLineSpacingForSection - To customize a layout, you need to realize such func: ```` prepare() shouldInvalidateLayout(forBoundsChange newBounds: CGRect) targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) layoutAttributesForElements(in rect: CGRect) ```` - Usage of Visual Effect View Project 26 - Twitter-like Splash ![TwitterLikeSplash.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/26.TwitterLikeSplash/TwitterLikeSplash.gif) What I learned - Usage of CAAnimation - reference of Keypath in CAAnimation - add Key Animation Frame by using CAKeyFrameAnimation Project 25 Custom Transition ![CustomTransition.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/25.CustomTransition/CustomTransition.gif) What I learned - We can customize animation of navigationcontroller, that is to say, to implement the func in ````UINavigationControllerDelegate```` - If we only need to focus on fromVC & toVC, we only need to implement such methods: ```` navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? ```` Project 24 - Vertical Menu Transition ![Vertical Menu Transition.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/24.Vertical%20Menu%20Transition/Vertical%20Menu%20Transition.gif) What I learned - Customize naviation transition for Present/Dismiss - Generally speaking, for target-action, we will set target to "self". But if we set target to "delegate", then the action should be set ````#selector(CustomTransitionDelegate.functionName)```` - In the transition Animation complete block, please insert following func: ```` transitionContext.completeTransition(true) fromViewController?.endAppearanceTransition() toViewController?.endAppearanceTransition() ```` Project 23 - Side Navigation App ![SideNavigation.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/23.Side%20Navigation/SideNavigation.gif) What I learned - Mix Swift with Objective-C - New a head file, e.g., Bridge.h - Click Project file, then Build Setting, then Objective-C Bridge Header, set the file path in Bridge.h - Then import all the header files in Bridge.h - Learned how to use [SWRevealViewController](https://github.com/John-Lluch/SWRevealViewController) Project 22 - Basic Animations ![Basic Animations.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/22.Basic%20Animations/Basic%20Animations.gif) What I learned - For animation related to position, we can both implement by modify the origin, and by setting the transform property of UIView - For animation related to Opacity, we can modify the alpha directly - For animation related to Scale, set the transform property of UIView, e.g.: ```` heartView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) ```` - For animation related to Color, modify the backgroundColor property - For animation related to Rotation, set the Scale Object to transform, e.g.: ```` heartView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) ```` Project 21 CoreData App ![CoreDataAppDemo.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/21.CoreDataApp/CoreDataAppDemo.gif) What I learned - In order to autogenerate some codes for you, please check UseCoreData while creating new project. - Don't have to use Editor to generate Subclass - [Reference](http://www.cnblogs.com/Free-Thinker/p/5944551.html) Project 20 - Apple Watch OS App - Guess Game ![WatchApp_Guess.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/20.WatchApp%20Guess/WatchApp_Guess.gif) What I learned - Need to select Watch OS while creating the project. - Have to use Storyboard to do the layout for apple watch, and the related file is Interface.storyboard - Use WCSession to do the interaction between Watch and Main App - Usecase refer too:[WatchKit Introduction: Building a Simple Guess Game](http://www.appcoda.com/watchkit-introduction-tutorial/) Project 19 - TodayWidget ![TodayWidget.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/19.TodayWidget/TodayWidget.gif) What I learned - Create Today Widget: "File > New > Target"๏ผŒthen select the iOS section's "Application Extension's __Today Extension__" - In order to share data between widget and app, please open the "App group" function. "target -> capability -> App Group -> Open it" - Add the group and name it, then redo this steps in Extension's target, and select the group you created just now. - Can use UserDefault as the shared storage between Main App and Widget, but we can't use StandardUserDefaults here, only to use suitName, and the name must follow the named group, e.g.: ```` let userDefault = UserDefaults(suiteName: "group.nimoAndHisFriend.watchDemo") ```` Project 18 - Spotlight Search ![SpotlightSearch.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/18.Spotlight%20Search/SpotlightSearch.gif) What I learned - How to use Spotlight Search: - import CoreSpotlight - Add the object as CSSearchableItem: Create a CSSearchableItemAttributeSet, then fill it's properties, such as title, contentDescription, and thumbData - CSSearchableItemAttribuitSet's thumbData can be catched either by UIImageJPEGRepresentation or by UIImagePNGRepresentation(Depend on the type of photo) - Create CSSearchableItem Obj, then add to SearchIndex by indexSearchableItems: ```` let tmpItems = [searchItem] CSSearchableIndex.default().indexSearchableItems(tmpItems) { (error) in } ```` - If you face problems in debug, please reset the simulator, or just debug with Device. Project 17 - 3D Touch Quick Action ![3DTouchQuickAction.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/17.3D%20Touch%20Quick%20Action/3DTouchQuickAction.gif) - Please make sure the application can support 3D Press function: ````self.window?.traitCollection.forceTouchCapability == .available```` - There are two kinds of operation with 3D Press: By long press icon in Spring Board(destop in iOS), and by long press some certain element and have a Peek View in Application. - For the first type, create the item with ````UIApplicationShortcutItem````, then set the application's shortcutItems property. Please remember, you can't use custom icon. - For the second type, please add related event in the ViewController you want to: - implement ````UIViewControllerPreviewingDelegate```` - register 3D Touch support : ````self.registerForPreviewing(with: self, sourceView: self.view)```` - implement following methods: ```` func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) ```` Project 16 - LoginAnimation ![LoginAnimation.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/16.LoginAnimation/LoginAnimation.gif) What I learned - Bounce animation need to use ```usingSpringWithDamping````, and please pay attention to: - usingSpringWithDamping๏ผšthe less the more exaggerate - initialSpringVelocity: the initial speed of animation - options: you can choose the animation method, such as EaseIn, EaseOut, EaseInOut... - Reference[Doc1](http://blog.csdn.net/youshaoduo/article/details/53203211),[Doc2](http://easings.net/zh-cn) - This kind of animation is so amazing, I like it :P Project 15 - Tumblr Menu ![Tumblr Menu.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/15.Tumblr%20Menu/Tumblr%20Menu.gif) What I learned - animation + BlurEffect - These lines of icon's appearing has a sequence, please control it by setting different delay value - For custom button, I refered to :[Custom Button](http://blog.csdn.net/dfqin/article/details/37813591) Project 14 - Video Splash ![VideoSplash.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/14.VideoSplash/VideoSplash.gif) What I learned - Create an AVPlayerViewController, then set it as the background of View - Then autoplay with AVPlayerViewController - Refered to a lib called ````VideoSplashViewController```` Project 13: Animation In TableViewCell ![AnimationInTableViewCell.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/13.AnimationInTableViewCell/AnimationInTableViewCell.gif) What I learned - Do the animation in method: ````viewWillAppear````. Then get all the cells by visibleCells of tableView, then do enumerate it and do animation - Do animation by using ````usingSpringWithDamping````, set 0.8 to ````usingSpringWithDamping````, 0 to ````initalSpringVelocity````. Project 12 - Emoji Slot Machine ![Emoji Slot Machine.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/12.Emoji%20Slot%20Machine/Emoji%20Slot%20Machine.gif) What I learned - Use UIPicker to do this game - In order to avoid show the edge of the UIPickerView, the first value and the last value of UIPickerView is forbidden. ````Int(arc4random())%(emojiArray.count - 2) + 1```` - Add double click action to make sure it will trigger the 'bingo' - I love this game. :) Project 11 - Gradient in TableView ![GradientInTableView.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/11.Gradient%20in%20TableView/GradientInTableView.gif) What I learned - Use CAGradientLayer on UITableViewCell - I suggest to use CAGradientLayer as the backgroundView of cell - hide the useless style of UITableViewCell: ```` table.separatorStyle = .none cell.selectionStyle = .none ```` Project 10 - Stretchy Header ![Stretchy Header.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/10.Stretchy%20Header/Stretchy%20Header.gif) What I learned - get the offset of ScrollView by implementing ````scrollViewDidScroll```` of UIScrollView - then set Max and Min of the scale for picture - set the transform of UIImageView to finish it: ```` bannerImgView.transform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) ```` Project 9 - Swipeable Cell ![Swipeable Cell.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/09.Swipeable%20Cell/Swipeable%20Cell.gif) What I learned - use ````editActionsForRowAt```` for UItableView, and set the functions as a array to the return value:````Array<UITableViewRowAction>```` - for each action please init UITableViewRowAction, and set the logic in block. - this demo only for general usage of swipeable cell, if you want to custom the swiped button, you must customize the Cell and implement functions by UIPanGesture Project 8 - Color Gradient ![ColorGradient.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/08.Color%20Gradient/ColorGradient.gif) What I learned - Use CAGradientLayer for the Gradient effect - Color set's concept will help to make the array of color. Please pay attention hat the property is CGColor - Changing color by scrolling is implemented by PanGestureRecognizer, and the effect and operation refered to : [Solar](https://itunes.apple.com/ca/app/solar-weather/id542875991?mt=8) Project 7 - Simple Photo Browser ![SimplePhotoBrowser.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/07.Simple%20Photo%20Browser/SimplePhotoBrowser.gif) What I learned - Set imageView on ScrollView to do Image Zoom - Set maxZoomScale / minZoomScale - implement viewForZooming method Project 6 - Video Player ![Video Player.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/06.Video%20Player/Video%20Player.gif) What I learned - How to use AVPlayer, AVPlayerViewController and AVPlayerLayer - How to run app in background by do configuration in plist - Show info in Lock Screen(remoteControlReceived) - Grammer: do...catch... - [Reference]((http://www.jianshu.com/p/174fd2673897)) Project 5 - Pull To Refresh ![PullToRefresh.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/05.Pull%20To%20Refresh/PullToRefresh.gif) What I learned - Usage of UIRefreshControll: message: ````attributedTitle````, action: ````UIControlEvents.valueChanged```` Project 4 - Limited Input Text Field ![Limit Input Text Field.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/04.Limit%20Input%20Text%20Field/Limit%20Input%20Text%20Field.gif) What I learned - limit input by capturing texting method: textViewDidChange - By observing NSNotification.Name.UIKeyboardWillChangeFrame, we can get the pop and dismiss of system keyboard. Project 3 - Find My Position ![Find My Position.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/03.Find%20My%20Position/Find%20My%20Position.gif) What I learned - configuration of location: in plist, please add: <key>NSLocationAlwaysUsageDescription</key> <true/> - can use CLLocationManger to do locate - if you face ```Domain=GEOErrorDomain Code=-8 "(null)"```, please change ````CLGeocoder```` var to global var Project 2: Watch Demo ![Watch's Demo.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/02.Watch'sDemo/Watch's%20Demo.gif) What I learned - Update cocoaPods to 1.2.0 - Learn how to use SnapKit (Quite similar with Monsary) - Learn how to use Timer in Swift - What I learned๏ผš guard๏ผŒrefer to [guard](http://www.jianshu.com/p/3a8e45af7fdd) Project 1: Change Custom Font ![Custom Font.gif](https://github.com/nimomeng/30-swift-projects-in-30-days/blob/master/01.CustomFont/Custom%20Font.gif) What I learned - How to change property of font - we could search font name in Storyboard, or following codes: ```` func printAllSupportedFontNames() { let familyNames = UIFont.familyNames for familyName in familyNames { print("++++++ \(familyName)") let fontNames = UIFont.fontNames(forFamilyName: familyName) for fontName in fontNames { print("----- \(fontName)") }}} ````
179
Parallax Scroll-Jacking Effects Engine for iOS / tvOS
# Parade [![Build Status](https://travis-ci.org/HelloElephant/Parade.svg?branch=master)](https://travis-ci.org/HelloElephant/Parade) [![codecov.io](https://codecov.io/gh/HelloElephant/Parade/branch/master/graphs/badge.svg)](https://codecov.io/gh/HelloElephant/Parade/branch/master) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)]() [![Cocoapods Compatible](https://img.shields.io/badge/pod-v1.0.0-blue.svg)]() [![Platform](https://img.shields.io/badge/platform-ios%20%7C%20tvos-lightgrey.svg)]() [![License](https://img.shields.io/badge/license-MIT-343434.svg)]() # Introduction Communicating to cells inside of UICollectionViews, UITableViews, or UIScrollViews, has always been a challenge. It almost always relies on a messy process of trying to relay the scroll to progress to cells in triggering special scrolling effects. Weโ€™ve designed this framework to minimize the effort needed to animate views. With a simple blocks-based builder weโ€™ve made it easy to define view statesโ€”**from** where they appear and where they will disappear **to**. <p align="center"> <img align="center" src="/Documentation/assets/03_state_changes_intro.png?raw=true"/> </p> # Features - Supports UICollectionView, UITableView, UIScrollview - Simple Blocks-Based Syntax - Minimal Integration Requirements - Supports Chaining Animatable Views - Adjustable Progress Ranges - 46 Different Parametric Curves # Interactive Demo There is a demo app included as part of the project that contains the following implemented examples for the following scrolling effects within the animated gif below. | | Included Examples | | ------------- | ------------- | |![alt tag](/Documentation/assets/08_animated_demo.gif?raw=true)|The demo contains a single ``ParallaxImageViewController`` as the root, and displays these cells as examples in the following order:<br/><br/>- [``ParallaxIntroCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxIntroCollectionViewCell.swift#L87) : Scale / Transform / Alpha<br/><br/>- [``ParallaxScaleCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxScaleCollectionViewCell.swift#L62) : Scale / Center<br/><br/>- [``ParallaxDoubleImageCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxDoubleImageCollectionViewCell.swift#L98) : Center / Transform<br/><br/>- [``ParallaxImageAppearCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxImageAppearCollectionViewCell.swift#L115) : Animation Chain Parallax<br/><br/>- [``ParallaxImageCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxImageCollectionViewCell.swift#L61) : Scale / Alpha / Transform <br/><br/>- [``ParallaxTheEndCollectionViewCell``](https://github.com/HelloElephant/Parade/blob/master/Parade-Demo/Parade-Demo/ParallaxCells/ParallaxTheEndCollectionViewCell.swift#L81) : Transform 3D<br/><br/>Note: The examples also contain custom ranges discussed later in the documentation.<br/>| # Installation * **Requirements** : XCode 9.0+, iOS 10.0+, tvOS 10.0+ * [Installation Instructions](/Documentation/installation.md) * [Release Notes](/Documentation/release_notes.md) # Communication - If you **found a bug**, or **have a feature request**, open an issue. - If you **want to contribute**, review the [Contribution Guidelines](/Documentation/CONTRIBUTING.md), and submit a pull request. - If you **contribute**, please ensure that the there is **100%** code coverage # Basic Use At its core, this framework defines **start** and **end** states for your animatable viewsโ€”with the scroll view interpolating between the states accordingly. The **start** state defines where views appear from as they scroll onto screenโ€”while **end** state defines where views will disappear. The only requirements beyond defining the states is to implement the PDAnimatableType on views to animate, the rest is seamless. Each animation consists of a **start** or **end** state which is defined by the developerโ€”plus a **snapshot** state that is automatically configured the first time the view begins to scroll. Before creating, consider the diagram below to get a sense of the coordinate space that the progress is calculated against. Progress is relative to the bounds of the scrollview itself. When scrolling horizontallyโ€”the difference in X value to the center point of the viewport is equal to the width of the scrollview itself. Just as the difference in Y value when scrolling vertically, as demonstrated below. ![alt tag](/Documentation/assets/02_all_ranges.png?raw=true) **NOTE :** There is control to adjust these ranges, and instructions can be found in the *Bounding Progress Range* section below. ## Initialization Initialize the Parade in ``application(:didFinishLaunchingWithOptions:)`` when the application is launched. Once initialized, the base UIScrollView will begin communicating scrolling progress to animatable views contained within. ```swift UIScrollView.initializeParade() ``` ## Create Animatable View The first step is to make a view animatable by implement the ``PDAnimatableType`` protocol, and the scrollview will begin to communicate progress to it's subviews accordingly. ```swift public protocol PDAnimatableType { // The progress animator definition that // interpolates over animatable properties func configuredAnimator() -> PDAnimator; } ``` Any of the following views, and their subviews, can implement the ``PDAnimatableType`` and be animated: - `UICollectionViewCell` - `UITableViewCell` - `UIScrollView`'s subviews But before the scrollview can communicate the progress, define an animator with the relative scroll direction that the scrollview will be tracking against. Bundled with the framework is recursive blocks based builder, that allows for simple creation of complex animations to interpolate against while scrolling. #### Vertical Direction Scroll Animator The following is an example to create a vertical animator for scrolling vertically. The closure returns an animator that can be used to create from, and to, state for any specific view within the hierarchy. ```swift func configuredAnimator() -> PDAnimator { /* Create a vertical tracking animator call this class method */ return PDAnimator.newVerticalAnimator { (animator) in } } ``` #### Horizontal Direction Scroll Animator The following is an example to create a horizontal animator for scrolling horizontally. The closure returns an animator that can be used to create from, and to, state for any specific view within the hierarchy. ```swift func configuredAnimator() -> PDAnimator { /* Create a horizontal tracking animator with this class method */ return PDAnimator.newHorizontalAnimator { (animator) in } } ``` The closure returns an animator that can be used to create from, and to, states for a specific view accordingly. ## Configuring Animation States #### Configure End State To have a view fade in relative to the scrolling progress, define a start state by calling the `startState(for:)` method as follows. Each time a state is added, it returns a state maker that can be used to append multiple properties to interpolate over. ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 return PDAnimator.newVerticalAnimator { (animator) in animator.startState(for: animatedImageView, { (s) in s.alpha(offScreenAlpha) }) } } ``` #### Configure End State Building on the last example, to have a view fade out relative to the scrolling progress off the screen, define an end state by calling the `endState(for:)` method as follows. ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 return PDAnimator.newVerticalAnimator { (animator) in animator.startState(for: animatedImageView, { (s) in s.alpha(offScreenAlpha) }).endState(for: animatedImageView, { (s) in s.alpha(offScreenAlpha) }) } } ``` #### Configure Start & End State Building on the prior example, it appears that the appearing and disappearing alpha is the same. In the case both **start**, and **end** state values are the same, use the `startEndState(for:)` method to set the value for both states simultaneously. ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 return PDAnimator.newVerticalAnimator { (animator) in animator.startEndState(for: animatedImageView, { (s) in s.alpha(offScreenAlpha) }) } } ``` #### Start & End State for Multiple Views In the case there are multiple views that need to perform the same animation, helper methods have been defined for creating animations for an array of views too. The following is an example of how these can be used. ```swift func configuredAnimator() -> PDAnimator { var animatedViews = [view1, view2, view3, view4] let offScreenAlpha : CGFloat = 0.0 return PDAnimator.newVerticalAnimator { (animator) in animator.startEndState(forViews: animatedViews, { (s) in s.alpha(offScreenAlpha) }) } } ``` The following can also be used with multiple views. ```swift func startState(forViews views: [UIView], _ callback : ... ) -> PDAnimationMaker func endState(forViews views: [UIView], _ callback : ... ) -> PDAnimationMaker func startEndState(forViews views: [UIView], _ callback : ... ) -> PDAnimationMaker ``` #### State Properties The framework provides quite a few helpers to define state properties for views, and/or, their backing layer with ease. ```swift /* View Property Setters */ public func alpha(_ value : CGFloat) -> PDAnimatablePropertyMaker public func backgroundColor(_ value : UIColor) -> PDAnimatablePropertyMaker public func bounds(_ value : CGSize) -> PDAnimatablePropertyMaker public func center(_ value : CGPoint) -> PDAnimatablePropertyMaker public func size(_ value : CGSize) -> PDAnimatablePropertyMaker public func transform(_ value : CGAffineTransform) -> PDAnimatablePropertyMaker /* Layer Property Setters */ public func borderColor(_ value : UIColor) -> PDAnimatablePropertyMaker public func borderWidth(_ value : CGFloat) -> PDAnimatablePropertyMaker public func contentsRect(_ value : CGRect) -> PDAnimatablePropertyMaker public func cornerRadius(_ value : CGFloat) -> PDAnimatablePropertyMaker public func shadowColor(_ value : UIColor) -> PDAnimatablePropertyMaker public func shadowOffset(_ value : CGSize) -> PDAnimatablePropertyMaker public func shadowOpacity(_ value : CGFloat) -> PDAnimatablePropertyMaker public func shadowRadius(_ value : CGFloat) -> PDAnimatablePropertyMaker public func transform3D(_ value : CATransform3D) -> PDAnimatablePropertyMaker public func zPosition(_ value : CGFloat) -> PDAnimatablePropertyMaker ``` In the case a setter is not defined, and there is a need to set a specific property to interpolate between, there are two defined setters that use KVC for views, and/or, their backing layer accordingly. ```swift public func viewValue(_ value : Any?, forKey key : String) -> PDAnimatablePropertyMaker public func layerValue(_ value : Any?, forKey key : String) -> PDAnimatablePropertyMaker ``` #### Parametric Easing There are 46 different parametric curves that can be applied to the interpolation of uniquely per property. The framework comes bundled with the following supported parametric curves that can be applied to each property individually. <table> <tbody> <tr> <td> .inSine<br> .inOutSine<br> .outSine<br> .outInSine</td> <td> .inQuadratic<br> .inOutQuadratic<br> .outQuadratic<br> .outInQuadratic</td> <td> .inCubic<br> .inOutCubic<br> .outCubic<br> .outInCubic</td> <td> .inQuartic<br> .inOutQuartic<br> .outQuartic<br> .outInQuartic</td> <td> .inQuintic <br> .inOutQuintic<br> .outQuintic<br> .outInQuintic</td> <td> .inAtan<br> .inOutAtan<br> .outAtan<br>*</td> </tr> <tr> <td> .inExponential<br> .inOutExponential<br> .outExponential<br> .outInExponential</td> <td> .inCircular <br> .inOutCircular<br> .outCircular<br> .outInCircular</td> <td> .inBack <br> .inOutBack<br> .outBack<br> .outInBack</td> <td> .inElastic <br> .inOutElastic<br> .outElastic<br> .outInElastic </td> <td> .inBounce<br> .inOutBounce<br> .outBounce<br> .outInBounce</td> <td> .linear<br> .smoothStep<br> .smootherStep<br>*</td> </tr> </tbody> </table> Just append it to the state's property definition while building the view's state. A good reference for some of the supported parametric curves can be found [here](http://easings.net/) ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 let offScreenTransform = CGAffineTransform.identity.scaledBy(x: 0.5, y: 0.5) return PDAnimator.newVerticalAnimator { (animator) in animator.startEndState(for: animatedImageView, { (s) in s.alpha(offScreenAlpha).easing.(.inSine) s.transform(offScreenTransform).easing(.inOutCubic) }) } } ``` ## Advanced View Animations #### Chaining Animations Animation progress does not have to apply only to the top level view that is being scrolled. If a subview implements the ``PDAnimatableType``, and is part of the subview hierarchy, attaching it to the animator can create a chain. The animator will then communicate the progress to the subview's animator, subviews can be attached to subviews, or even have the subviews attach to their subviews, to create chains that can traverse multiple levels in the end to make some fun effects. To attach an animatable view, call the `attachAnimatableView(:)` method as follows. ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 let offScreenTransform = CGAffineTransform.identity.translatedBy(x: 0.0, y: 100.0) return PDAnimator.newVerticalAnimator { (animator) in animator.startEndState(for: animatedImageView, { (s) in s.transform(offScreenTransform).easing(.inOutCubic) }).attachAnimatableView(animatedImageView) } } ``` #### Bounding Progress Range There is sometimes a need to adjust where the progress actually takes place. This is especially useful when animatable view is smaller than the bounding size of the scrollview. Observe the examples of the ranges defined, and how it effects the progress. By defining a range, this is basically telling the scrollview where the progress counts from 0 to 100. ![alt tag](/Documentation/assets/03_range_progress.png?raw=true) Ranges can be defined on a per property basis just like easing โ€“ thus allowing for different properties interpolating over different coordinate spaces. The following example defines two different ranges for each property, and can visually be referenced above as to where the interpolation will take place. ```swift func configuredAnimator() -> PDAnimator { let offScreenAlpha : CGFloat = 0.0 let offScreenTransform = CGAffineTransform.identity.translatedBy(x: 0.0, y: 100.0) return PDAnimator.newVerticalAnimator { (animator) in animator.startState(for: animatedImageView, { (s) in s.transform(offScreenTransform).easing(.inOutCubic).range(0.5...1.0) s.alpha(offScreenTransform).easing(.inOutCubic).range(0.25...0.75) }) } } ``` ## License *Parade is released under the MIT license. See [License](https://github.com/HelloElephant/Parade/blob/master/LICENSE) for details.*
180
A simple, customizable popup dialog for iOS written in Swift. Replaces UIAlertController alert style.
<img src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialogLogo.png?raw=true" width="300"> <p>&nbsp;</p> ![Swift Version](https://img.shields.io/badge/Swift-5-orange.svg) [![Version](https://img.shields.io/cocoapods/v/PopupDialog.svg?style=flat)](http://cocoapods.org/pods/PopupDialog) [![License](https://img.shields.io/cocoapods/l/PopupDialog.svg?style=flat)](http://cocoapods.org/pods/PopupDialog) [![Platform](https://img.shields.io/cocoapods/p/PopupDialog.svg?style=flat)](http://cocoapods.org/pods/PopupDialog) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Build Status Master](https://travis-ci.org/Orderella/PopupDialog.svg?branch=master)](https://travis-ci.org/Orderella/PopupDialog) [![Build Status Development](https://travis-ci.org/Orderella/PopupDialog.svg?branch=development)](https://travis-ci.org/Orderella/PopupDialog) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) <p>&nbsp;</p> # Introduction Popup Dialog is a simple, customizable popup dialog written in Swift. <img align="left" src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialog01.gif?raw=true" width="300"> <img src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialog02.gif?raw=true" width="300"> <img align="left" src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialog03.gif?raw=true" width="300"> <img src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialogDark01.png?raw=true" width="300"> ## Features - [x] Easy to use API with hardly any boilerplate code - [x] Convenient default view with image, title, message - [x] Supports custom view controllers - [x] Slick transition animations - [x] Fully themeable via appearance, including fonts, colors, corner radius, shadow, overlay color and blur, etc. - [x] Can be dismissed via swipe and background tap - [x] Objective-C compatible - [x] Works on all screens and devices supporting iOS 10.0+ <p>&nbsp;</p> # Installation This version is Swift 5 compatible. For the Swift 4.2 version, please use [V1.0.0](https://github.com/Orderella/PopupDialog/releases/tag/1.0.0). ## CocoaPods PopupDialog is available through [CocoaPods](http://cocoapods.org). Simply add the following to your Podfile: ```ruby use_frameworks! target '<Your Target Name>' pod 'PopupDialog', '~> 1.1' ``` ## Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. A minimum version of `0.17` is required. To install, simply add the following lines to your Cartfile: ```ruby github "Orderella/PopupDialog" ~> 1.1 ``` ## Manually If you prefer not to use either of the above mentioned dependency managers, you can integrate PopupDialog into your project manually by adding the files contained in the [Classes](https://github.com/trungp/PopupDialog/tree/master/PopupDialog/Classes) folder to your project. Moreover, you have to manually add the classes of [DynamicBlurView](https://github.com/KyoheiG3/DynamicBlurView/tree/master/DynamicBlurView) to your project. <p>&nbsp;</p> # Example You can find this and more example projects in the repo. To run it, clone the repo, and run `pod install` from the Example directory first. ```swift import PopupDialog // Prepare the popup assets let title = "THIS IS THE DIALOG TITLE" let message = "This is the message section of the popup dialog default view" let image = UIImage(named: "pexels-photo-103290") // Create the dialog let popup = PopupDialog(title: title, message: message, image: image) // Create buttons let buttonOne = CancelButton(title: "CANCEL") { print("You canceled the car dialog.") } // This button will not the dismiss the dialog let buttonTwo = DefaultButton(title: "ADMIRE CAR", dismissOnTap: false) { print("What a beauty!") } let buttonThree = DefaultButton(title: "BUY CAR", height: 60) { print("Ah, maybe next time :)") } // Add buttons to dialog // Alternatively, you can use popup.addButton(buttonOne) // to add a single button popup.addButtons([buttonOne, buttonTwo, buttonThree]) // Present dialog self.present(popup, animated: true, completion: nil) ``` <p>&nbsp;</p> # Usage PopupDialog is a subclass of UIViewController and as such can be added to your view controller modally. You can initialize it either with the handy default view or a custom view controller. ## Default Dialog ```swift public convenience init( title: String?, message: String?, image: UIImage? = nil, buttonAlignment: UILayoutConstraintAxis = .vertical, transitionStyle: PopupDialogTransitionStyle = .bounceUp, preferredWidth: CGFloat = 340, tapGestureDismissal: Bool = true, panGestureDismissal: Bool = true, hideStatusBar: Bool = false, completion: (() -> Void)? = nil) ``` The default dialog initializer is a convenient way of creating a popup with image, title and message (see image one and three). Bascially, all parameters are optional, although this makes no sense at all. You want to at least add a message and a single button, otherwise the dialog can't be dismissed, unless you do it manually. If you provide an image it will be pinned to the top/left/right of the dialog. The ratio of the image will be used to set the height of the image view, so no distortion will occur. ## Custom View Controller ```swift public init( viewController: UIViewController, buttonAlignment: UILayoutConstraintAxis = .vertical, transitionStyle: PopupDialogTransitionStyle = .bounceUp, preferredWidth: CGFloat = 340, tapGestureDismissal: Bool = true, panGestureDismissal: Bool = true, hideStatusBar: Bool = false, completion: (() -> Void)? = nil) ``` You can pass your own view controller to PopupDialog (see image two). It is accessible via the `viewController` property of PopupDialog, which has to be casted to your view controllers class to access its properties. Make sure the custom view defines all constraints needed, so you don't run into any autolayout issues. Buttons are added below the controllers view, however, these buttons are optional. If you decide to not add any buttons, you have to take care of dismissing the dialog manually. Being a subclass of view controller, this can be easily done via `dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?)`. ## Button Alignment Buttons can be distributed either `.horizontal` or `.vertical`, with the latter being the default. Please note distributing buttons horizontally might not be a good idea if you have more than two buttons. ```swift public enum UILayoutConstraintAxis : Int { case horizontal case vertical } ``` ## Transition Style You can set a transition animation style with `.bounceUp` being the default. The following transition styles are available ```swift public enum PopupDialogTransitionStyle: Int { case bounceUp case bounceDown case zoomIn case fadeIn } ``` ## Preferred Width PopupDialog will always try to have a max width of 340 . On iPhones with smaller screens, like iPhone 5 SE, width would be 320. 340 is also the standard width for iPads. By setting preferredWidth you can override the max width of 340 for iPads only. ## Gesture Dismissal Gesture dismissal allows your dialog being dismissed either by a background tap or by swiping the dialog down. By default, this is set to `true`. You can prevent this behavior by setting either `tapGestureDismissal` or `panGestureDismissal` to `false` in the initializer. ## Hide Status Bar PopupDialog can hide the status bar whenever it is displayed. Defaults to `false`. Make sure to add `UIViewControllerBasedStatusBarAppearance` to `Info.plist` and set it to `YES`. ## Completion This completion handler is called when the dialog was dismissed. This is especially useful for catching a gesture dismissal. <p>&nbsp;</p> # Default Dialog Properties If you are using the default dialog, you can change selected properties at runtime: ```swift // Create the dialog let popup = PopupDialog(title: title, message: message, image: image) // Present dialog self.present(popup, animated: true, completion: nil) // Get the default view controller and cast it // Unfortunately, casting is necessary to support Objective-C let vc = popup.viewController as! PopupDialogDefaultViewController // Set dialog properties vc.image = UIImage(...) vc.titleText = "..." vc.messageText = "..." vc.buttonAlignment = .horizontal vc.transitionStyle = .bounceUp ``` <p>&nbsp;</p> # Styling PopupDialog Appearance is the preferred way of customizing the style of PopupDialog. The idea of PopupDialog is to define a theme in a single place, without having to provide style settings with every single instantiation. This way, creating a PopupDialog requires only minimal code to be written and no "wrappers". This makes even more sense, as popup dialogs and alerts are supposed to look consistent throughout the app, that is, maintain a single style. ## Dialog Default View Appearance Settings If you are using the default popup view, the following appearance settings are available: ```swift let dialogAppearance = PopupDialogDefaultView.appearance() dialogAppearance.backgroundColor = .white dialogAppearance.titleFont = .boldSystemFont(ofSize: 14) dialogAppearance.titleColor = UIColor(white: 0.4, alpha: 1) dialogAppearance.titleTextAlignment = .center dialogAppearance.messageFont = .systemFont(ofSize: 14) dialogAppearance.messageColor = UIColor(white: 0.6, alpha: 1) dialogAppearance.messageTextAlignment = .center ``` ## Dialog Container Appearance Settings The container view contains the PopupDialogDefaultView or your custom view controller. the following appearance settings are available: ```swift let containerAppearance = PopupDialogContainerView.appearance() containerAppearance.backgroundColor = UIColor(red:0.23, green:0.23, blue:0.27, alpha:1.00) containerAppearance.cornerRadius = 2 containerAppearance.shadowEnabled = true containerAppearance.shadowColor = .black containerAppearance.shadowOpacity = 0.6 containerAppearance.shadowRadius = 20 containerAppearance.shadowOffset = CGSize(width: 0, height: 8) containerAppearance.shadowPath = CGPath(...) ``` ## Overlay View Appearance Settings This refers to the view that is used as an overlay above the underlying view controller but below the popup dialog view. If that makes sense ;) ```swift let overlayAppearance = PopupDialogOverlayView.appearance() overlayAppearance.color = .black overlayAppearance.blurRadius = 20 overlayAppearance.blurEnabled = true overlayAppearance.liveBlurEnabled = false overlayAppearance.opacity = 0.7 ``` #### Note Setting `liveBlurEnabled` to true, that is enabling realtime updates of the background view, results in a significantly higher CPU usage /power consumption and is therefore turned off by default. Choose wisely whether you need this feature or not ;) ## Button Appearance Settings The standard button classes available are `DefaultButton`, `CancelButton` and `DestructiveButton`. All buttons feature the same appearance settings and can be styled separately. ```swift var buttonAppearance = DefaultButton.appearance() // Default button buttonAppearance.titleFont = .systemFont(ofSize: 14) buttonAppearance.titleColor = UIColor(red: 0.25, green: 0.53, blue: 0.91, alpha: 1) buttonAppearance.buttonColor = .clear buttonAppearance.separatorColor = UIColor(white: 0.9, alpha: 1) // Below, only the differences are highlighted // Cancel button CancelButton.appearance().titleColor = .lightGray // Destructive button DestructiveButton.appearance().titleColor = .red ``` Moreover, you can create a custom button by subclassing `PopupDialogButton`. The following example creates a solid blue button, featuring a bold white title font. Separators are invisible. ```swift public final class SolidBlueButton: PopupDialogButton { override public func setupView() { defaultFont = .boldSystemFont(ofSize: 16) defaultTitleColor = .white defaultButtonColor = .blue defaultSeparatorColor = .clear super.setupView() } } ``` These buttons can be customized with the appearance settings given above as well. <p>&nbsp;</p> ## Dark mode example The following is an example of a *Dark Mode* theme. You can find this in the Example project `AppDelegate`, just uncomment it to apply the custom appearance. ```swift // Customize dialog appearance let pv = PopupDialogDefaultView.appearance() pv.titleFont = UIFont(name: "HelveticaNeue-Light", size: 16)! pv.titleColor = .white pv.messageFont = UIFont(name: "HelveticaNeue", size: 14)! pv.messageColor = UIColor(white: 0.8, alpha: 1) // Customize the container view appearance let pcv = PopupDialogContainerView.appearance() pcv.backgroundColor = UIColor(red:0.23, green:0.23, blue:0.27, alpha:1.00) pcv.cornerRadius = 2 pcv.shadowEnabled = true pcv.shadowColor = .black // Customize overlay appearance let ov = PopupDialogOverlayView.appearance() ov.blurEnabled = true ov.blurRadius = 30 ov.liveBlurEnabled = true ov.opacity = 0.7 ov.color = .black // Customize default button appearance let db = DefaultButton.appearance() db.titleFont = UIFont(name: "HelveticaNeue-Medium", size: 14)! db.titleColor = .white db.buttonColor = UIColor(red:0.25, green:0.25, blue:0.29, alpha:1.00) db.separatorColor = UIColor(red:0.20, green:0.20, blue:0.25, alpha:1.00) // Customize cancel button appearance let cb = CancelButton.appearance() cb.titleFont = UIFont(name: "HelveticaNeue-Medium", size: 14)! cb.titleColor = UIColor(white: 0.6, alpha: 1) cb.buttonColor = UIColor(red:0.25, green:0.25, blue:0.29, alpha:1.00) cb.separatorColor = UIColor(red:0.20, green:0.20, blue:0.25, alpha:1.00) ``` <img src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialogDark01.png?raw=true" width="260"> <img src="https://github.com/Orderella/PopupDialog/blob/master/Assets/PopupDialogDark02.png?raw=true" width="260"> I can see that there is room for more customization options. I might add more of them over time. <p>&nbsp;</p> # Screen sizes and rotation Rotation and all screen sizes are supported. However, the dialog will never exceed a width of 340 points on iPhones. For iPads, you can set `preferredWidth` when initializing a new PopupDialog. However, landscape mode will not work well if the height of the dialog exceeds the width of the screen. <p>&nbsp;</p> # Working with text fields If you are using text fields in your custom view controller, popup dialog makes sure that the dialog is positioned above the keyboard whenever it appears. You can opt out of this behaviour by setting `keyboardShiftsView` to false on a PopupDialog. # Testing PopupDialog exposes a nice and handy method that lets you trigger a button tap programmatically: ```swift public func tapButtonWithIndex(_ index: Int) ``` Other than that, PopupDialog unit tests are included in the root folder. <p>&nbsp;</p> # Objective-C PopupDialog can be used in Objective-C projects as well. Here is a basic example: ```objective-c PopupDialog *popup = [[PopupDialog alloc] initWithTitle: @"Title" message: @"This is a message" image: nil buttonAlignment: UILayoutConstraintAxisVertical transitionStyle: PopupDialogTransitionStyleBounceUp preferredWidth: 380 tapGestureDismissal: NO panGestureDismissal: NO hideStatusBar: NO completion: nil]; DestructiveButton *delete = [[DestructiveButton alloc] initWithTitle: @"Delete" height: 45 dismissOnTap: YES action: nil]; CancelButton *cancel = [[CancelButton alloc] initWithTitle: @"Cancel" height: 45 dismissOnTap: YES action: nil]; DefaultButton *ok = [[DefaultButton alloc] initWithTitle: @"OK" height: 45 dismissOnTap: YES action: nil]; [dialog addButtons:@[delete, cancel, ok]]; [self presentViewController:popup animated:YES completion:nil]; ``` <p>&nbsp;</p> # Bonus ## Shake animation If you happen to use PopupDialog to validate text input, for example, you can call the handy `shake()` method on PopupDialog. <p>&nbsp;</p> # Requirements Minimum requirement is iOS 10.0. This dialog was written with Swift 5, for support of older versions please head over to releases. <p>&nbsp;</p> # Changelog * **1.1.1** Updates dependencies to Swift 5 * **1.1.0** Swift 5 support * **1.0.0** Pinned Swift version to 4.2<br>Dropped iOS 9 support as of moving to ios-snapshot-test-case * **0.9.2** Fixes crash when presenting dialog while app is inactive * **0.9.1** Fixes Carthage support * **0.9.0** Swift 4.2 support * **0.8.1** Added shadow appearance properties * **0.8.0** Separated tap and pan gesture dismissal * **0.7.1** Fixes Objective-C compatability<br>Improved Carthage handling * **0.7.0** Removed FXBlurView while switching to DynamicBlurView * **0.6.2** Added preferredWidth option for iPads * **0.6.1** Added shake animation<br>Introduced hideStatusBar option * **0.6.0** Swift 4 support<br>Dropped iOS8 compatibility * **0.5.4** Fixed bug where blur view would reveal hidden layer<br>Improved view controller lifecycle handling<br>Scroll views can now be used with gesture dismissal * **0.5.3** Fixed memory leak with custom view controllers<br>Added UI automation & snapshot tests * **0.5.2** Fixed image scaling for default view * **0.5.1** Introduced custom button height parameter<br>Reintroduced iOS8 compatibility * **0.5.0** Swift 3 compatibility / removed iOS8 * **0.4.0** iOS 8 compatibility * **0.3.3** Fixes buttons being added multiple times * **0.3.2** Dialog repositioning when interacting with keyboard<br>Non dismissable buttons option<br>Additional completion handler when dialog is dismissed * **0.3.1** Fixed Carthage issues * **0.3.0** Objective-C compatibility * **0.2.2** Turned off liveBlur by default to increase performance * **0.2.1** Dismiss via background tap or swipe down transition * **0.2.0** You can now pass custom view controllers to the dialog. This introduces breaking changes. * **0.1.6** Defer button action until animation completes * **0.1.5** Exposed dialog properties<br>(titleText, messageText, image, buttonAlignment, transitionStyle) * **0.1.4** Pick transition animation style * **0.1.3** Big screen support<br>Exposed basic shadow appearance * **0.1.2** Exposed blur and overlay appearance * **0.1.1** Added themeing example * **0.1.0** Intitial version <p>&nbsp;</p> # Author Martin Wildfeuer, [email protected] for Orderella Ltd., [orderella.co.uk](http://orderella.co.uk)<br> You might also want to follow us on Twitter, [@theMWFire](https://twitter.com/theMWFire) | [@Orderella](https://twitter.com/orderella) # Thank you Thanks to everyone who uses, enhances and improves this library, especially the contributors. Moreover, thanks to KyoheiG3 for porting FXBlurView to [DynamicBlurView](https://github.com/KyoheiG3/DynamicBlurView). <p>&nbsp;</p> # License PopupDialog is available under the MIT license. See the LICENSE file for more info.
181
A library to imitate the iOS 10 Maps UI.
# Pulley <p align="center"> <a href="https://github.com/52inc/Pulley/actions?query=workflow%3Adeploy_to_cocoapods"><img src="https://github.com/52inc/Pulley/workflows/deploy_to_cocoapods/badge.svg"></a> <a href="https://cocoapods.org/pods/Pulley"><img src="https://img.shields.io/cocoapods/v/Pulley.svg?style=flat"></a> <a href="https://github.com/Carthage/Carthage/"><img src="https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat"></a> <a href="https://swift.org/package-manager/"><img src="https://img.shields.io/badge/SPM-supported-DE5C43.svg?style=flat"></a> <br /> <a href="https://raw.githubusercontent.com/52inc/Pulley/master/LICENSE"><img src="https://img.shields.io/cocoapods/l/Pulley.svg?style=flat"></a> <a href="https://github.com/52inc/Pulley/"><img src="https://img.shields.io/cocoapods/p/Pulley.svg?style=flat"></a> </p> A library to imitate the drawer in Maps for iOS 10/11. The master branch follows the latest currently released version of Swift. If you need an older version of Swift, you can specify it's version (e.g. 1.0.x) in your Podfile or use the code on the branch for that version. Older branches are unsupported. ### Update / Migration Info **ATTENTION:** Pulley 2.9.0 has new properties to support a new displayMode. The base functionality should work without any significant changes. The biggest change being the new displayMode of `.compact` to replicate Apple Maps Behavior on the iPhone SE size class devices. This is an exact replica of the behavior of the Apple Maps drawer, therefor when the `currentDisplayMode` of the `PulleyViewController` is `.compact` then the only `supportedDrawerPositions` for the view controller when in `.compact` mode are `.open`, `.closed`, and `.collapsed`. This mode also has new @IBInspectable properties, `compactInsets` and `compactWidth`. This mode behaves in a very similar way to `.panel` mode. See the pull request [here](https://github.com/52inc/Pulley/pull/347) for the motivation behind this feature. Also in this release, `setDrawerContentViewController(controller: UIViewController, position: PulleyPosition? = nil, animated: Bool = true, completion: PulleyAnimationCompletionBlock?)` has a new optional parameter `position` to set a new drawer position the drawer when a new `DrawerContentViewController` is set. See [this](https://github.com/52inc/Pulley/pull/349) pull request for the motivation behind this feature. Pulley 2.5.0 had significant renaming changes to support new features. Although property names have changed, the functionality should work without any significant changes (aside from renaming). See [this thread](https://github.com/52inc/Pulley/issues/252) for additional information. Pulley 2.4.0 changed PulleyPosition from an enum to a class. This won't affect most uses, but may affect your switch statements. Continue to use the static PulleyPosition values as usual and add a default case. This was done to allow marking some `PulleyDrawerViewControllerDelegate` methods as optional so they don't need to be implemented if you aren't using certain positions (or wish to use the default values). If you have questions, please open an issue. _Technical reason: Optional protocol methods require the @objc attribute. Arrays of Swift enums can't be exposed to Objective-C, and supportedDrawerPositions previously returned an array of PulleyPosition enums. This change allows for marking the protocol @objc so methods can be marked optional._ ### Introduction Pulley is an easy to use drawer library meant to imitate the drawer in iOS 10/11's Maps app. It exposes a simple API that allows you to use any UIViewController subclass as the drawer content or the primary content. **Here's a preview (apologies for the potato gif):** ![Pulley Preview](http://i.imgur.com/bmEWqy7.gif) ![Pulley iPad Preview](https://i.imgur.com/HwsdMSO.png) ### Installation ##### Installation with Cocoapods `pod 'Pulley'` ##### Installation with Carthage `github "52inc/Pulley"` Please read this [issue](https://github.com/52inc/Pulley/issues/331#issue-435421067) regarding setup if using Carthage. ##### Installation with Swift Package Manager Follow the [developer documentation](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app) for Swift Package Manager (versions 2.8.x) ##### Manual Installation Simply copy the files in the PulleyLib folder into your project. ### How To use #### Interface Builder Pulley supports loading embedded view controllers from Interface Builder. In order to use Pulley with Interface Builder, you'll need to setup your `PulleyViewController` like this: 1. Add 2 container views to the `PulleyViewController` view. One for the drawer content and one for the primary (background) content. 2. Connect the container view for the primary (background) content to the outlet named **primaryContentContainerView**. 3. Connect the container view for the drawer content to the outlet named **drawerContentContainerView**. 4. Create an 'embed' segue between each container view and the view controller you want to display for that part of the drawer. 5. Make sure you set the Module for the view controller to 'Pulley'. [See this issue.](https://github.com/52inc/Pulley/issues/29) If you would like to customize the height of the "Collapsed" or "Partially Revealed" states of the drawer, have your Drawer Content view controller implement `PulleyDrawerViewControllerDelegate`. You can provide the height for your drawer content for both the Collapsed and Partially Revealed states. ![Interface Builder Screenshot](http://i.imgur.com/htzo50L.png=500x) #### Programmatically Pulley supports loading view controllers programmatically. In order to use Pulley programmatically, please consider the following code snippet: ```swift let mainContentVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("PrimaryContentViewController") let drawerContentVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("DrawerContentViewController") let pulleyController = PulleyViewController(contentViewController: mainContentVC, drawerViewController: drawerContentVC) ``` ### API **Important:** The background of the internal drawer view is clear. If your view controller's view is also clear then you'll see the shadow rendering below where the view is. I'd recommend giving your view a color or using a UIVisualEffectView to make sure you don't see the shadow. You can set the shadow opacity to 0.0 if you want the shadow to be hidden. **Important:** Drawer Content views are made **20pt too long** in order to account for the bounce animation. Make sure your drawer content view is aware that the bottom 20pts will be offscreen. **Important:** PulleyViewController is not accessible as a parent or as `self.pulleyViewController` until _during or after_ -viewWillAppear: if you're loading Pulley from Storyboards. #### iOS 11, Safe Areas, and the iPhone X Pulley has support for safe areas and the iPhone X. The sample project includes full support for this, and does a couple of UI tricks to make things look better. These are documented throughout the sample project. The basic concepts of using Pulley post-iOS 11 are: 1. The -topInset property is _from_ the top safe area, not the top of the screen. 2. Most delegate methods have a new parameter that tells you the current bottom safe area. 3. The drawer itself doesn't do anything special for the bottom safe area because everyone's UI will want to treat it a little differently. HOWEVER: The delegate methods have been updated to deliver you the current bottom safe area anytime that a value for a drawer position is requested from you. You can use this variable to compute the value you want to return for the drawer position. Checkout the sample project for a simple example on an easy approach to this. 4. If you have UI bottom safe area customizations that you want to perform, I recommend using the delegate method `drawerPositionDidChange(drawer:bottomSafeArea:)` to modify your UI based on the value of bottomSafeArea. Any time the size of the Pulley view controller changes, this method will be called with a new bottom safe area height. The sample project uses this to modify the drawer 'header' height, as well as to adjust the contentInset for the UITableView. It's not automatically taken care of for you, but it should be a fairly simple thing to add. 5. I do _not_ recommend constraining views to the safe are of the drawer content view controller. It won't actually work for the safe areas. 6. If you want the map (or other UI) in the primary view controller to render under the status bar (or in the ears of the iPhone X), make sure you constrain it directly to the superview's 'top'. You may need to double click on the constraint, and then make sure it _isn't_ constrained 'relative to margin'. 7. For backwards compatibility, iOS 9/10 use topLayoutGuide as the top safe area. Your implementation shouldn't need to worry about iOS versions, as that's taken care of for you by Pulley. If you have any problems / questions while updating Pulley to iOS 11 SDK, please feel free to create an issue if the above information didn't solve your problem. Even if you've already seen the example project, I highly encourage looking at the new post-iOS 11 version of the sample project. It may have something that could help your iPhone X / safe area implementation. #### 3 protocols exist for you to use: * `PulleyDelegate`: The protocol the other protocols inherit from. It's exposed as the .delegate property of `PulleyViewController`. NOTE: If the object you're wanting to receive delegate callbacks is either the Primary Content or Drawer Content view controllers...don't use the .delegate property. Continue reading for the other protocols. * `PulleyDrawerViewControllerDelegate`: Includes all of the methods from `PulleyDelegate` and adds methods for providing custom heights for the Collapsed and Partially Revealed states. Your Drawer Content view controller should implement this protocol if it wants to receive callbacks for changes in the drawer state or to provide custom heights for the aforementioned drawer states. Implementing this protocol is optional for the Drawer Content view controller, but if you don't then defaults will be used instead. * `PulleyPrimaryContentControllerDelegate`: This is currently identical to `PulleyDelegate`. However, this protocol may be implemented by your Primary Content view controller if you want to receive callbacks for changes in drawer state. Eventually specialized methods may be added to this protocol. #### Changing view controllers after creation: You'll likely need to change out the contents of the drawer or the primary view controller after creation. Here's how to do that programmatically. **NOTE:** If you pass animated: true then you'll get a subtle crossfade animation. This doesn't work well with all views / view hierarchies (Notably UIVisualEffectView). You've been warned. **Changing the Primary Content View Controller:** ```swift if let drawer = self.parentViewController as? PulleyViewController { let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("PrimaryContentViewController") drawer.setPrimaryContentViewController(primaryContent, animated: true) } ``` **Changing the Drawer Content View Controller:** ```swift if let drawer = self.parentViewController as? PulleyViewController { let drawerContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("DrawerContentViewController") drawer.setDrawerContentViewController(drawerContent, animated: false) } ``` #### Customizing the drawer 1. See the 3 protocols above. 2. You can adjust the inset from the top of the screen in the "Open" state by setting the -topInset property on the `PulleyViewController`. 3. You can enable / disable drawer positions by implementing `PulleyDrawerViewControllerDelegate` in your 'drawer' view controller. If you need to change it, call `setNeedsSupportedDrawerPositionsUpdate()` on the `PulleyViewController` so it will recalculate the drawer based on your new settings. 4. You can adjust the corner radius applied to the drawer by setting the -drawerCornerRadius property on the `PulleyViewController`. 5. You can adjust the shadow opacity applied to the drawer by setting the -shadowOpacity property on the `PulleyViewController`. 6. You can adjust the shadow radius applied to the drawer by setting the -shadowRadius property on the `PulleyViewController`. 7. You can adjust the background dimming color by setting the -backgroundDimmingColor to an opaque color on the `PulleyViewController`. 8. You can adjust / remove the background blur effect by setting the -drawerBackgroundVisualEffectView property on the `PulleyViewController`. 9. You can adjust the alpha of the background dimming color by setting the -backgroundDimmingOpacity property on the `PulleyViewController`. 10. You can change the drawer position by calling setDrawerPosition( : ) on the `PulleyViewController`. 11. If an object needs to receive delegate callbacks and _isn't_ one of the view controller's presented then you can use the -delegate property on the `PulleyViewController`. 12. The Swift Interface for `PulleyViewController` is documented in case you want to see real documentation instead of a numbered list of useful things. 13. You can set the initial drawer position by using the initialDrawerPosition property on the `PulleyViewController`. 14. Most settings for the `PulleyViewController` are exposed in Interface Builder. Select the `PulleyViewController` View Controller (not the view) to access them via IBInspectable. 15. By default, Pulley will only use the 'bottom' display mode (to preserve backwards compatibility). If you want to use the iPad / iPhone landscape modes, you can use 'panel' for the display mode. If you want it to automatically switch like Maps.app on iOS, you can set the display mode to 'automatic'. 16. You can apply a custom mask to the Pulley drawer by setting your drawerViewController's view.layer.mask property to a CAShapeLayer. That mask will also be applied to the drawer in Pulley. 17. You can specify which corner you'd like the panel to display in (when in 'panel' displayMode) by using the 'panelCornerPlacement` property. ## Requirements - iOS 9.0+ - Swift 4.0+
182
Auto Layout made easy
<h3 align="center"> <img src="/README/logo.png" alt="EasyPeasy Logo" /> </h3> [![CI Status](http://img.shields.io/travis/nakiostudio/EasyPeasy.svg?style=flat)](https://travis-ci.org/nakiostudio/EasyPeasy) [![Version](https://img.shields.io/cocoapods/v/EasyPeasy.svg?style=flat)](http://cocoapods.org/pods/EasyPeasy) [![Carthage compatible](https://img.shields.io/badge/carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://travis-ci.org/nakiostudio/EasyPeasy) **EasyPeasy** is a Swift framework that lets you create *Auto Layout* constraints programmatically without headaches and never ending boilerplate code. Besides the basics, **EasyPeasy** resolves most of the constraint conflicts for you and also can attach to a constraint conditional closures that are evaluated before applying a constraint, this way you can install an *Auto Layout* constraint depending on platform, size classes, orientation... or the state of your controller, easy peasy! In this quick tour through **EasyPeasy** we assume that you already know the advantages and disadvantages of the different *Auto Layout* APIs and therefore you won't see here a comparison of the code side by side, just read and decide whether **EasyPeasy** is for you or not. ### A touch of EasyPeasy The example below is quite simple but shows how effortless its implementation result using **EasyPeasy**. <h3 align="center"> <br> <img width="80%" src="/README/first_touch.png" alt="First touch" /> </h3> ### Features * Compatible with iOS, tvOS and OS X. * Lightweight and easy to use domain specific language. * Resolution of *Auto Layout* conflicts. * Fast and *hassle-free* update of constraints. * Conditional application of constraints. * `UILayoutGuide` and `NSLayoutGuide` support. ### Guides * [Mastering Auto Layout with EasyPeasy I: Introduction](https://medium.com/@yaid/mastering-auto-layout-with-easypeasy-i-introduction-341f12230074) * [Mastering Auto Layout with EasyPeasy II: Basics](https://medium.com/@yaid/mastering-auto-layout-with-easypeasy-ii-basics-3057e1db817) * [Mastering Auto Layout with EasyPeasy III: Relationships](https://medium.com/@yaid/mastering-auto-layout-with-easypeasy-iii-relationships-91fc140e4755) * Mastering Auto Layout with EasyPeasy IV: Priorities *(coming soon...)* * Mastering Auto Layout with EasyPeasy V: Layout Guides *(coming soon...)* * Mastering Auto Layout with EasyPeasy VI: Advanced *(coming soon...)* ## Table of contents * [Installation](#installation) * [Usage](#usage) * [Constants](#constants) * [Attributes](#attributes) * [DimensionAttributes](#dimensionattributes) * [PositionAttributes](#positionattributes) * [CompoundAttributes](#compoundattributes) * [Priorities](#priorities) * [Conditions](#conditions) * [ContextualConditions](#contextualconditions) * [UILayoutGuides](#uilayoutguides) * [Lastly](#lastly) * [Updating constraints](#updating-constraints) * [Clearing constraints](#clearing-constraints) * [Animating constraints](#animating-constraints) * [Example projects](#example-projects) * [EasyPeasy playground](#easypeasy-playground) * [Autogenerated documentation](#autogenerated-documentation) ## Installation ### Swift compatibility * To work with Swift 2.2 use EasyPeasy `v.1.2.1` or earlier versions of the library. * To work with Swift 2.3 use EasyPeasy `v.1.3.1`. * To work with Swift 3 use EasyPeasy `v.1.4.2`. * To work with Swift 4 use EasyPeasy `v.1.8.0`. * To work with Swift 5 use EasyPeasy `v.1.9.0` and above. (thanks [Bas van Kuijck](https://github.com/basvankuijck)). ### Cocoapods EasyPeasy is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "EasyPeasy" ``` ### Carthage EasyPeasy is [Carthage](https://github.com/Carthage/Carthage) compatible. To add **EasyPeasy** as a dependency to your project, just add the following line to your Cartfile: ```ruby github "nakiostudio/EasyPeasy" ``` And run ` carthage update ` as usual. ### Compatibility **EasyPeasy** is compatible with iOS (8 and above), tvOS (9 and above) and OS X (10.10 and above). The framework has been tested with Xcode 7 and Swift 2.0, however don't hesitate to report any issues you may find with different versions. ## Usage **EasyPeasy** is a set of position and dimension attributes that you can apply to your views. You can manage these from the `easy` property available within all the UI classes that work with Auto Layout (view subclasses, layout guides, etc). For instance, to set a width of 200px to a view you would create an attribute of class `Width` with a constant value of `200`, then the attribute is applied to the view by using the `easy.layout(_:)` method. ```swift myView.easy.layout(Width(200)) ``` Because our view without height is nothing we can apply multiple attributes at once as follows: ```swift myView.easy.layout( Width(200), Height(120) ) ``` In the previous example, two attributes have been applied and therefore two constraints created and added: a width constraint with `constant = 200` and a height constraint with `constant = 120`. ### Constants Without really knowing it, we have just created an **EasyPeasy** `Constant` struct containing the constant, multipler and the relation of a `NSLayoutConstraint`. #### Relations **EasyPeasy** provides an easy way of creating constants with different `NSLayoutRelations`: * `.Equal`: it is created like in our previous example `Width(200)`. * `.GreaterThanOrEqual`: it is created as easy as this `Width(>=200)` and it means that our view has a width greater than or equal to 200px. * `.LessThanOrEqual`: it is created as follows `Width(<=200)`. #### Multipliers There is a custom operator that eases the creation of a `NSLayoutConstraint` multiplier. You can use it like this `Width(*2)` and means that the width of our view is two times *something*, we will mention later how to establish the relationship with that *something*. In addition, you can combine `multipliers` with `Equal`, `.GreaterThanOrEqual` and `LessThanOrEqual` relations. i.e. `Width(>=10.0*0.5)` creates a `NSLayoutConstraint` with `value = 10.0`, `relation = .GreaterThanOrEqual` and `multiplier = 0.5`, whereas `Width(==10.0*0.5)` creates a `NSLayoutConstraint` with `value = 10.0`, `relation = .Equal` and `multiplier = 0.5`. ### Attributes **EasyPeasy** provides as many `Attribute` classes as attributes `NSLayoutConstraint` have, plus something that we have called `CompoundAttributes` (we will explain these attributes later). #### DimensionAttributes There are just two dimension attributes `Width` and `Height`. You can create an *Auto Layout* relationship between your view `DimensionAttribute` and another view by using the method `func like(view: UIView) -> Self`. Example: ```swift contentLabel.easy.layout(Width().like(headerView)) ``` That line of code will create a constraint that sets a width for `contentLabel` equal to the `headerView` width. #### PositionAttributes The table below shows the different position attributes available. Because they behave like the `NSLayoutConstraint` attributes, you can find a complete description of them in the [Apple docs](https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/#//apple_ref/c/tdef/NSLayoutRelation). Attribute | Attribute | Attribute | Attribute --- | --- | --- | --- Left | Right | Top | Bottom Leading | Trailing | CenterX | CenterY LeftMargin | RightMargin | TopMargin | BottomMargin LeadingMargin | TrailingMargin | CenterXWithinMargins | CenterYWithinMargins FirstBaseline | LastBaseline | -- | -- As well as the **DimensionAttributes** have the `like:` method to establish *Auto Layout* relationships, you can use a similar method to do the same with **PositionAttributes**. This method is: ```swift func to(view: UIView, _ attribute: ReferenceAttribute? = nil) -> Self ``` The example below positions `contentLabel` 10px under `headerView` with the same left margin as `headerView`. ```swift contentLabel.easy.layout( Top(10).to(headerView), Left().to(headerView, .Left) ) ``` #### CompoundAttributes These attributes are the ones that create multiple `DimensionAttributes` or `PositionAttributes` under the hood. For example, the `Size` attribute will create a `Width` and a `Height` attributes with their width and height `NSLayoutConstraints` respectively. These are the `CompoundAttributes` available: * `Size`: As mentioned before this attribute will apply a `Width` and a `Height` attribute to the view. It can be initialized in many ways and depending on that the result may change. These are some examples: ```swift // Apply width = 0 and height = 0 constraints view.easy.layout(Size()) // Apply width = referenceView.width and height = referenceView.height constraints view.easy.layout(Size().like(referenceView)) // Apply width = 100 and height = 100 constraints view.easy.layout(Size(100)) // Apply width = 200 and height = 100 constraints view.easy.layout(Size(CGSize(width: 200, height: 100))) ``` * `Edges`: This attribute creates `Left`, `Right`, `Top` and `Bottom` attributes at once. Examples: ```swift // Apply left = 0, right = 0, top = 0 and bottom = 0 constraints to its superview view.easy.layout(Edges()) // Apply left = 10, right = 10, top = 10 and bottom = 10 constraints to its superview view.easy.layout(Edges(10)) // Apply left = 10, right = 10, top = 5 and bottom = 5 constraints to its superview view.easy.layout(Edges(UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10))) ``` * `Center`: It creates `CenterX` and `CenterY` attributes. Examples: ```swift // Apply centerX = 0 and centerY = 0 constraints to its superview view.easy.layout(Center()) // Apply centerX = 10 and centerY = 10 constraints to its superview view.easy.layout(Center(10)) // Apply centerX = 0 and centerY = 50 constraints to its superview view.easy.layout(Center(CGPoint(x: 0, y: 50))) ``` * `Margins`: This attribute creates `LeftMargin`, `RightMargin`, `TopMargin` and `BottomMargin` attributes at once. Examples: ```swift // Apply leftMargin = 0, rightMargin = 0, topMargin = 0 and bottomMargin = 0 constraints to its superview view.easy.layout(Margins()) // Apply leftMargin = 10, rightMargin = 10, topMargin = 10 and bottomMargin = 10 constraints to its superview view.easy.layout(Margins(10)) // Apply leftMargin = 10, rightMargin = 10, topMargin = 5 and bottomMargin = 5 constraints to its superview view.easy.layout(Margins(UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10))) ``` * `CenterWithinMargins`: It creates `CenterXWithinMargins` and `CenterYWithinMargins` attributes. Examples: ```swift // Apply centerXWithinMargins = 0 and centerYWithinMargins = 0 constraints to its superview view.easy.layout(CenterWithinMargins()) // Apply centerXWithinMargins = 10 and centerYWithinMargins = 10 constraints to its superview view.easy.layout(CenterWithinMargins(10)) // Apply centerXWithinMargins = 0 and centerYWithinMargins = 50 constraints to its superview view.easy.layout(CenterWithinMargins(CGPoint(x: 0, y: 50))) ``` ### Priorities The `Priority` enum does the same function as `UILayoutPriority` and it's shaped by five cases: * `low`: it creates an *Auto Layout* priority with `Float` value `1`. * `medium`: it creates an *Auto Layout* priority with `Float` value `500`. * `high`: it creates an *Auto Layout* priority with `Float` value `750`. * `required`: it creates an *Auto Layout* priority with `Float` value `1000`. * `custom`: it specifies the *Auto Layout* priority defined by the developer in the case associated value `value`. Example: `.custom(value: 650.0)`. In order to apply any of these priorities to an `Attribute`, the method `.with(priority: Priority)` must be used. The following example gives an `UILayoutPriority` of `500` to the `Top` `Attribute` applied to `view`: ```swift view.easy.layout(Top(>=50).with(.medium)) ``` You can also apply a `Priority` to an array of `Attributes` (this operation will override the priorities previously applied to an `Attribute`). ```swift view.easy.layout([ Width(200), Height(200) ].with(.medium)) ``` ### Conditions One of the peculiarities of **EasyPeasy** is the usage of `Conditions` or closures that evaluate whether a constraint should be applied or not to the view. The method `when(condition: Condition)` sets the `Condition` closure to an `Attribute`. There is plenty of use cases, the example below shows how to apply different constraints depending on a custom variable: ```swift var isCenterAligned = true ... view.easy.layout( Top(10), Bottom(10), Width(250), Left(10).when { !isCenterAligned }, CenterX(0).when { isCenterAligned } ) ``` #### Condition re-evaluation These `Condition` closures can be re-evaluated during the lifecycle of a view, to do so you just need to call the convenience method `easy.reload()`. ```swift view.easy.reload() ``` Bare in mind that these `Condition` closures are stored in properties therefore you need to capture those variables you access within the closure. For example: ```swift descriptionLabel.easy.layout( Height(100).when { [weak self] in return self?.expandDescriptionLabel ?? false } ) ``` You can also apply a `Condition` to an array of `Attributes` (this operation will override the `Conditions` previously applied to an `Attribute`). ```swift view.easy.layout([ Width(200), Height(240) ].when { isFirstItem }) view.easy.layout([ Width(120), Height(140) ].when { !isFirstItem }) ``` #### ContextualConditions This iOS only feature is a variant of the `Condition` closures that receive no parameters and return a boolean value. Instead, a `Context` struct is passed as parameter providing some extra information based on the `UITraitCollection` of the `UIView` the `Attributes` are going to be applied to. The properties available on this `Context` struct are: * `isPad`: true if the current device is iPad. * `isPhone`: true if the current device is iPhone. * `isHorizontalVerticalCompact`: true if both horizontal and vertical size classes are `.Compact`. * `isHorizontalCompact`: true if the horizontal size class is `.Compact`. * `isVerticalCompact`: true if the vertical size class is `.Compact`. * `isHorizontalVerticalRegular`: true if both horizontal and vertical size classes are `.Regular`. * `isHorizontalRegular`: true if the horizontal size class is `.Regular`. * `isVerticalRegular`: true if the vertical size class is `.Regular`. This is an example of `ContextualConditions` applied to an array of `Attributes`: ```swift view.easy.layout([ Size(250), Center(0) ].when { $0.isHorizontalRegular }) view.easy.layout([ Top(0), Left(0), Right(0), Height(250) ].when { $0.isHorizontalCompact }) ``` ##### ContextualCondition re-evaluation As we have seen before, you can re-evaluate a `Condition` closure by calling the `easy.reload()` convenience method. This also applies to `ContextualConditions`, therefore if you want your constraints to be updated upon a change on your view `UITraitCollection` then you need to call the `easy.reload()` method within `traitCollectionDidChange(_:)`. Alternatively, **EasyPeasy** can do this step for you automatically. This is disabled by default as it requires method swizzling; to enable it simply **compile the framework** adding the compiler flags `-D EASY_RELOAD`. ### UILayoutGuides Since the version *v.0.2.3* (and for iOS 9 projects and above) **EasyPeasy** integrates `UILayoutGuides` support. #### Applying constraints Applying a constraint to an `UILayoutGuide` is as easy as we have discussed in the previous sections, just apply the **EasyPeasy** attributes you want using the `easy.layout(_:)` method. ```swift func viewDidLoad() { super.viewDidLoad() let layoutGuide = UILayoutGuide() self.view.addLayoutGuide(layoutGuide) layoutGuide.easy.layout( Top(10), Left(10), Right(10), Height(100).when { Device() == .iPad }, Height(60).when { Device() == .iPhone } ) } ``` As you can see, all the different attributes and goodies **EasyPeasy** provides for `UIViews` are also applicable to `UILayoutGuides`. #### Connecting UILayoutGuides and UIViews As mentioned in the [Attributes](#attributes) section you can create constraint relationships between an `UIView` attribute and other `UIViews` attributes using the methods `to(_:_)` and `like(_:_)`. Now you can take advantage of those methods to create a relationship between your `UIView` attributes and an `UILayoutGuide`. ```swift let layoutGuide = UILayoutGuide() let separatorView: UIView let label: UILabel func setupLabel() { self.label.easy.layout( Top(10).to(self.layoutGuide), CenterX(0), Size(60) ) self.separatorView.easy.layout( Width(0).like(self.layoutGuide), Height(2), Top(10).to(self.label), CenterX(0).to(self.label) ) } ``` ### Lastly Finally but not less important in this section we will explain how to interact with `Attributes` once they have been applied to an `UIView` using the `easy.layout(_:)` method. #### Updating constraints We briefly mentioned in the introductory section that **EasyPeasy** solves most of the constraint conflicts and it's true. Usually, in order to update a constraint or the constant of a constraint you have to keep a reference to your `NSLayoutConstraint` and update the constant when needed. With **EasyPeasy** you just need to apply another `Attribute` to your `UIView` of the same or different type. In the example below we have two methods, the one in which we setup our constraints `viewDidLoad()` and a method in which we want to update the `Top` attribute of our `headerView`. ```swift func viewDidLoad() { super.viewDidLoad() headerView.easy.layout( Top(0), Left(0), Right(0), Height(60) ) } func didTapButton(sender: UIButton?) { headerView.easy.layout(Top(100)) } ``` That's it! we have updated our `Top` constraint without caring about keeping references or installing/uninstalling new constraints. However, there is some cases in which **EasyPeasy** cannot prevent a conflict (at least for now). This is when multiple constraints cannot be satisfied, i.e. existing a `Left` and `Right` constraints it's also applied a `Width` constraint (all of them with the same priority). But **EasyPeasy** is smart enough to prevent conflicts, i.e. when replacing a `Left` and `Right` attributes with a `CenterX` attribute. #### Clearing constraints **EasyPeasy** provides a method extending `UIView` that clears all the constraints installed in an `UIView` by the framework. This method is `func easy.clear()`. ```swift view.easy.clear() ``` #### Animating constraints Animating constraints with **EasyPeasy** is very straightforward, just apply one or more `Attributes` to your view within an animation block and you are ready to go, without worrying about constraint conflicts. Example: ```swift UIView.animateWithDuration(0.3) { view.easy.layout(Top(10)) view.layoutIfNeeded() } ``` ## Example projects Don't forget to clone the repository and run the iOS and OS X example projects to see **EasyPeasy** in action. <h3 align="center"> <table width="50%"> <tr> <td width="50%"> <img src="/README/demo_ios.gif" alt="Demo iOS" /> </td> <td width="50%"> <img src="/README/demo_macos.gif" alt="Demo macOS" /> </td> </tr> </table> </h3> *Note:* the messages in the demo app aren't real and the appearance of those *Twitter* accounts no more than a tribute to some kickass developers :) ## EasyPeasy playground Alternatively, you can play with **EasyPeasy** cloning the *Playground* project available [here](https://github.com/nakiostudio/EasyPeasy-Playground). <h3 align="center"> <img src="/README/playground.gif" alt="Playground" /> </h3> ## Autogenerated documentation **EasyPeasy** is a well documented framework and therefore all the documented classes and methods are available in [Cocoadocs](http://cocoadocs.org/docsets/EasyPeasy). ## Author Carlos Vidal - [@nakiostudio](https://twitter.com/nakiostudio) ## License EasyPeasy is available under the MIT license. See the LICENSE file for more info.
183
๐Ÿ‘ฉโ€๐ŸŽจ Elegant Attributed String composition in Swift sauce
<p align="center" > <img src="banner.png" width=300px alt="SwiftLocation" title="SwiftLocation"> </p> <p align="center"><strong> Elegant Attributed String composition in Swift sauce</strong></p> SwiftRichString is a lightweight library which allows to create and manipulate attributed strings easily both in iOS, macOS, tvOS and even watchOS. It provides convenient way to store styles you can reuse in your app's UI elements, allows complex tag-based strings rendering and also includes integration with Interface Builder. ## Main Features | | Features Highlights | |--- |--------------------------------------------------------------------------------- | | ๐Ÿฆ„ | Easy styling and typography managment with coincise declarative syntax | | ๐Ÿž | Attach local images (lazy/static) and remote images inside text | | ๐Ÿงฌ | Fast & high customizable XML/HTML tagged string rendering | | ๐ŸŒŸ | Apply text transforms within styles | | ๐Ÿ“ | Native support for iOS 11 Dynamic Type | | ๐Ÿ–‡ | Support for Swift 5.1's function builder to compose strings | | โฑ | Compact code base with no external dependencies. | | ๐Ÿฆ | Fully made in Swift 5 from Swift โฅ lovers | ### Easy Styling ```swift let style = Style { $0.font = SystemFonts.AmericanTypewriter.font(size: 25) // just pass a string, one of the SystemFonts or an UIFont $0.color = "#0433FF" // you can use UIColor or HEX string! $0.underline = (.patternDot, UIColor.red) $0.alignment = .center } let attributedText = "Hello World!".set(style: style) // et voilร ! ``` ### XML/HTML tag based rendering SwiftRichString allows you to render complex strings by parsing text's tags: each style will be identified by an unique name (used inside the tag) and you can create a `StyleXML` (was `StyleGroup`) which allows you to encapsulate all of them and reuse as you need (clearly you can register it globally). ```swift // Create your own styles let normal = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) } let bold = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.red $0.backColor = UIColor.yellow } let italic = normal.byAdding { $0.traitVariants = .italic } let myGroup = StyleXML(base: normal, ["bold": bold, "italic": italic]) let str = "Hello <bold>Daniele!</bold>. You're ready to <italic>play with us!</italic>" self.label?.attributedText = str.set(style: myGroup) ``` That's the result! <img src="Documentation_Assests/image_2.png" alt="" width=400px/> ## Documentation - [Introduction to `Style`, `StyleXML` & `StyleRegEx`](#styleStyleXML) - [String & Attributed String concatenation](#concatenation) - [Apply styles to `String` & `Attributed String`](#manualstyling) - [Fonts & Colors in `Style`](#fontscolors) - [Derivating a `Style`](#derivatingstyle) - [Support Dynamic Type](#dynamictype) - [Render XML tagged strings](#customizexmlstrings) - [Customize XML rendering: react to tag's attributes and unknown tags](#xmlstrings) - [Custom text transforms](#texttransforms) - [Local & Remote Images inside text](#images) - [The `StyleManager`](#stylemanager) - [Register globally available styles](#globalregister) - [Defer style creation on demand](#defer) - [Assign style using Interface Builder](#ib) - [All properties of `Style`](#props) Other info: - [Requirements](#requirements) - [Installation](#installation) - [Contributing](#contributing) - [Copyright](#copyright) <a name="styleStyleXML"/> ## Introduction to `Style`, `StyleXML`, `StyleRegEx` The main concept behind SwiftRichString is the use of `StyleProtocol` as generic container of the attributes you can apply to both `String` and `NSMutableAttributedString`. Concrete classes derivated by `StyleProtocol` are: `Style`, `StyleXML` and `StyleRegEx`. Each of these classes can be used as source for styles you can apply to a string, substring or attributed string. ### `Style`: apply style to strings or attributed strings A `Style` is a class which encapsulate all the attributes you can apply to a string. The vast majority of the attributes of both AppKit/UIKit are currently available via type-safe properties by this class. Creating a `Style` instance is pretty simple; using a builder pattern approach the init class require a callback where the self instance is passed and allows you to configure your properties by keeping the code clean and readable: ```swift let style = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.green // ... set any other attribute } let attrString = "Some text".set(style: style) // attributed string ``` ### `StyleXML`: Apply styles for tag-based complex string `Style` instances are anonymous; if you want to use a style instance to render a tag-based plain string you need to include it inside a `StyleXML`. You can consider a `StyleXML` as a container of `Styles` (but, in fact, thanks to the conformance to a common `StyleProtocol`'s protocol your group may contains other sub-groups too). ```swift let bodyStyle: Style = ... let h1Style: Style = ... let h2Style: Style = ... let group = StyleXML(base: bodyStyle, ["h1": h1Style, "h2": h2Style]) let attrString = "Some <h1>text</h1>, <h2>welcome here</h2>".set(style: group) ``` The following code defines a group where: - we have defined a base style. Base style is the style applied to the entire string and can be used to provide a base ground of styles you want to apply to the string. - we have defined two other styles named `h1` and `h2`; these styles are applied to the source string when parser encounter some text enclosed by these tags. ### `StyleRegEx`: Apply styles via regular expressions `StyleRegEx` allows you to define a style which is applied when certain regular expression is matched inside the target string/attributed string. ```swift let emailPattern = "([A-Za-z0-9_\\-\\.\\+])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)" let style = StyleRegEx(pattern: emailPattern) { $0.color = UIColor.red $0.backColor = UIColor.yellow } let attrString = "My email is [email protected] and my website is http://www.danielemargutti.com".(style: style!) ``` The result is this: <img src="Documentation_Assests/image_4.png" alt="" width=500px/> <a name="concatenation"/> ## String & Attributed String concatenation SwiftRichString allows you to simplify string concatenation by providing custom `+` operator between `String`,`AttributedString` (typealias of `NSMutableAttributedString`) and `Style`. This a an example: ```swift let body: Style = Style { ... } let big: Style = Style { ... } let attributed: AttributedString = "hello ".set(style: body) // the following code produce an attributed string by // concatenating an attributed string and two plain string // (one styled and another plain). let attStr = attributed + "\(username)!".set(style:big) + ". You are welcome!" ``` You can also use `+` operator to add a style to a plain or attributed string: ```swift // This produce an attributed string concatenating a plain // string with an attributed string created via + operator // between a plain string and a style let attStr = "Hello" + ("\(username)" + big) ``` Finally you can concatente strings using function builders: ```swift let bold = Style { ... } let italic = Style { ... } let attributedString = AttributedString.composing { "hello".set(style: bold) "world".set(style: italic) } ``` <a name="manualstyling"/> ## Apply styles to `String` & `Attributed String` Both `String` and `Attributed String` (aka `NSMutableAttributedString`) has a come convenience methods you can use to create an manipulate attributed text easily via code: ### Strings Instance Methods - `set(style: String, range: NSRange? = nil)`: apply a globally registered style to the string (or a substring) by producing an attributed string. - `set(styles: [String], range: NSRange? = nil)`: apply an ordered sequence of globally registered styles to the string (or a substring) by producing an attributed string. - `set(style: StyleProtocol, range: NSRange? = nil)`: apply an instance of `Style` or `StyleXML` (to render tag-based text) to the string (or a substring) by producting an attributed string. - `set(styles: [StyleProtocol], range: NSRange? = nil)`: apply a sequence of `Style`/`StyleXML` instance in order to produce a single attributes collection which will be applied to the string (or substring) to produce an attributed string. Some examples: ```swift // apply a globally registered style named MyStyle to the entire string let a1: AttributedString = "Hello world".set(style: "MyStyle") // apply a style group to the entire string // commonStyle will be applied to the entire string as base style // styleH1 and styleH2 will be applied only for text inside that tags. let styleH1: Style = ... let styleH2: Style = ... let StyleXML = StyleXML(base: commonStyle, ["h1" : styleH1, "h2" : styleH2]) let a2: AttributedString = "Hello <h1>world</h1>, <h2>welcome here</h2>".set(style: StyleXML) // Apply a style defined via closure to a portion of the string let a3 = "Hello Guys!".set(Style({ $0.font = SystemFonts.Helvetica_Bold.font(size: 20) }), range: NSMakeRange(0,4)) ``` ### AttributedString Instance Methods Similar methods are also available to attributed strings. There are three categories of methods: - `set` methods replace any existing attributes already set on target. - `add` add attributes defined by style/styles list to the target - `remove` remove attributes defined from the receiver string. Each of this method alter the receiver instance of the attributed string and also return the same instance in output (so chaining is allowed). **Add** - `add(style: String, range: NSRange? = nil)`: add to existing style of string/substring a globally registered style with given name. - `add(styles: [String], range: NSRange? = nil)`: add to the existing style of string/substring a style which is the sum of ordered sequences of globally registered styles with given names. - `add(style: StyleProtocol, range: NSRange? = nil)`: append passed style instance to string/substring by altering the receiver attributed string. - `add(styles: [StyleProtocol], range: NSRange? = nil)`: append passed styles ordered sequence to string/substring by altering the receiver attributed string. **Set** - `set(style: String, range: NSRange? = nil)`: replace any existing style inside string/substring with the attributes defined inside the globally registered style with given name. - `set(styles: [String], range: NSRange? = nil)`: replace any existing style inside string/substring with the attributes merge of the ordered sequences of globally registered style with given names. - `set(style: StyleProtocol, range: NSRange? = nil)`: replace any existing style inside string/substring with the attributes of the passed style instance. - `set(styles: [StyleProtocol], range: NSRange? = nil)`: replace any existing style inside string/substring with the attributes of the passed ordered sequence of styles. **Remove** - `removeAttributes(_ keys: [NSAttributedStringKey], range: NSRange)`: remove attributes specified by passed keys from string/substring. - `remove(_ style: StyleProtocol)`: remove attributes specified by the style from string/substring. Example: ```swift let a = "hello".set(style: styleA) let b = "world!".set(style: styleB) let ab = (a + b).add(styles: [coupondStyleA,coupondStyleB]).remove([.foregroundColor,.font]) ``` <a name="fontscolors"/> ## Fonts & Colors in `Style` All colors and fonts you can set for a `Style` are wrapped by `FontConvertible` and `ColorConvertible` protocols. SwiftRichString obviously implements these protocols for `UIColor`/`NSColor`, `UIFont`/`NSFont` but also for `String`. For Fonts this mean you can assign a font by providing directly its PostScript name and it will be translated automatically to a valid instance: ```swift let firaLight: UIFont = "FiraCode-Light".font(ofSize: 14) ... ... let style = Style { $0.font = "Jura-Bold" $0.size = 24 ... } ``` On UIKit you can also use the `SystemFonts` enum to pick from a type-safe auto-complete list of all available iOS fonts: ```swift let font1 = SystemFonts.Helvetica_Light.font(size: 15) let font2 = SystemFonts.Avenir_Black.font(size: 24) ``` For Color this mean you can create valid color instance from HEX strings: ```swift let color: UIColor = "#0433FF".color ... ... let style = Style { $0.color = "#0433FF" ... } ``` Clearly you can still pass instances of both colors/fonts. <a name="derivatingstyle"/> ## Derivating a `Style` Sometimes you may need to infer properties of a new style from an existing one. In this case you can use `byAdding()` function of `Style` to produce a new style with all the properties of the receiver and the chance to configure additional/replacing attributes. ```swift let initialStyle = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) $0.alignment = right } // The following style contains all the attributes of initialStyle // but also override the alignment and add a different foreground color. let subStyle = bold.byAdding { $0.alignment = center $0.color = UIColor.red } ``` <a name="dynamictype"/> ### Conforming to `Dynamic Type` To support your fonts/text to dynammically scale based on the users preffered content size, you can implement style's `dynamicText` property. UIFontMetrics properties are wrapped inside `DynamicText` class. ```swift let style = Style { $0.font = UIFont.boldSystemFont(ofSize: 16.0) $0.dynamicText = DynamicText { $0.style = .body $0.maximumSize = 35.0 $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } ``` <a name="xmlstrings"/> ## Render XML/HTML tagged strings SwiftRichString is also able to parse and render xml tagged strings to produce a valid `NSAttributedString` instance. This is particularly useful when you receive dynamic strings from remote services and you need to produce a rendered string easily. In order to render an XML string you need to create a compisition of all styles you are planning to render in a single `StyleXML` instance and apply it to your source string as just you made for a single `Style`. For example: ```swift // The base style is applied to the entire string let baseStyle = Style { $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize * 1.15) $0.lineSpacing = 1 $0.kerning = Kerning.adobe(-20) } let boldStyle = Style { $0.font = UIFont.boldSystemFont(ofSize: self.baseFontSize) $0.dynamicText = DynamicText { $0.style = .body $0.maximumSize = 35.0 $0.traitCollection = UITraitCollection(userInterfaceIdiom: .phone) } } let italicStyle = Style { $0.font = UIFont.italicSystemFont(ofSize: self.baseFontSize) } // A group container includes all the style defined. let groupStyle = StyleXML.init(base: baseStyle, ["b" : boldStyle, "i": italicStyle]) // We can render our string let bodyHTML = "Hello <b>world!</b>, my name is <i>Daniele</i>" self.textView?.attributedText = bodyHTML.set(style: group) ``` <a name="customizexmlstrings"/> ## Customize XML rendering: react to tag's attributes and unknown tags You can also add custom attributes to your tags and render it as you prefer: you need to provide a croncrete implementation of `XMLDynamicAttributesResolver` protocol and assign it to the `StyleXML`'s `.xmlAttributesResolver` property. The protocol will receive two kind of events: - `applyDynamicAttributes(to attributedString: inout AttributedString, xmlStyle: XMLDynamicStyle)` is received when parser encounter an existing style with custom attributes. Style is applied and event is called so you can make further customizations. - `func styleForUnknownXMLTag(_ tag: String, to attributedString: inout AttributedString, attributes: [String: String]?)` is received when a unknown (not defined in `StyleXML`'s styles) tag is received. You can decide to ignore or perform customizations. The following example is used to override text color for when used for any known tag: ```swift // First define our own resolver for attributes open class MyXMLDynamicAttributesResolver: XMLDynamicAttributesResolver { public func applyDynamicAttributes(to attributedString: inout AttributedString, xmlStyle: XMLDynamicStyle) { let finalStyleToApply = Style() xmlStyle.enumerateAttributes { key, value in switch key { case "color": // color support finalStyleToApply.color = Color(hexString: value) default: break } } attributedString.add(style: finalStyleToApply) } } // Then set it to our's StyleXML instance before rendering text. let groupStyle = StyleXML.init(base: baseStyle, ["b" : boldStyle, "i": italicStyle]) groupStyle.xmlAttributesResolver = MyXMLDynamicAttributesResolver() ``` The following example define the behaviour for a non known tag called `rainbow`. Specifically it alter the string by setting a custom color for each letter of the source string. ```swift open class MyXMLDynamicAttributesResolver: XMLDynamicAttributesResolver { public override func styleForUnknownXMLTag(_ tag: String, to attributedString: inout AttributedString, attributes: [String : String]?) { super.styleForUnknownXMLTag(tag, to: &attributedString, attributes: attributes) if tag == "rainbow" { let colors = UIColor.randomColors(attributedString.length) for i in 0..<attributedString.length { attributedString.add(style: Style({ $0.color = colors[i] }), range: NSMakeRange(i, 1)) } } } } } ``` You will receive all read tag attributes inside the `attributes` parameter. You can alter attributes or the entire string received as `inout` parameter in `attributedString` property. A default resolver is also provided by the library and used by default: `StandardXMLAttributesResolver`. It will support both `color` attribute in tags and `<a href>` tag with url linking. ```swift let sourceHTML = "My <b color=\"#db13f2\">webpage</b> is really <b>cool</b>. Take a look <a href=\"http://danielemargutti.com\">here</a>" let styleBase = Style({ $0.font = UIFont.boldSystemFont(ofSize: 15) }) let styleBold = Style({ $0.font = UIFont.boldSystemFont(ofSize: 20) $0.color = UIColor.blue }) let groupStyle = StyleXML.init(base: styleBase, ["b" : styleBold]) self.textView?.attributedText = sourceHTML.set(style: groupStyle) ``` The result is this: <img src="Documentation_Assests/image_5.png" alt="" width=500px/> where the `b` tag's blue color was overriden by the color tag attributes and the link in 'here' is clickable. <a name="texttransforms"/> ## Custom Text Transforms Sometimes you want to apply custom text transforms to your string; for example you may want to make some text with a given style uppercased with current locale. In order to provide custom text transform in `Style` instances just set one or more `TextTransform` to your `Style`'s `.textTransforms` property: ```swift let allRedAndUppercaseStyle = Style({ $0.font = UIFont.boldSystemFont(ofSize: 16.0) $0.color = UIColor.red $0.textTransforms = [ .uppercaseWithLocale(Locale.current) ] }) let text = "test".set(style: allRedAndUppercaseStyle) // will become red and uppercased (TEST) ``` While `TextTransform` is an enum with a predefined set of transform you can also provide your own function which have a `String` as source and another `String` as destination: ```swift let markdownBold = Style({ $0.font = UIFont.boldSystemFont(ofSize: 16.0) $0.color = UIColor.red $0.textTransforms = [ .custom({ return "**\($0)**" }) ] }) ``` All text transforms are applied in the same ordered you set in `textTransform` property. <a name="images"/> ## Local & Remote Images inside text SwiftRichString supports local and remote attached images along with attributed text. You can create an attributed string with an image with a single line: ```swift // You can specify the bounds of the image, both for size and the location respecting the base line of the text. let localTextAndImage = AttributedString(image: UIImage(named: "rocket")!, bounds: CGRect(x: 0, y: -20, width: 25, height: 25)) // You can also load a remote image. If you not specify bounds size is the original size of the image. let remoteTextAndImage = AttributedString(imageURL: "http://...") // You can now compose it with other attributed or simple string let finalString = "...".set(style: myStyle) + remoteTextAndImage + " some other text" ``` Images can also be loaded by rending an XML string by using the `img` tag (with `named` tag for local resource and `url` for remote url). `rect` parameter is optional and allows you to specify resize and relocation of the resource. ```swift let taggedText = """ Some text and this image: <img named="rocket" rect="0,-50,30,30"/> This other is loaded from remote URL: <img url="https://www.macitynet.it/wp-content/uploads/2018/05/video_ApplePark_magg18.jpg"/> """ self.textView?.attributedText = taggedText.set(style: ...) ``` This is the result: <img src="Documentation_Assests/image_6.png" alt="" width=100px/> Sometimes you may want to provide these images lazily. In order to do it just provide a custom implementation of the `imageProvider` callback in `StyleXML` instance: ```swift let xmlText = "- <img named=\"check\" background=\"#0000\"/> has done!" let xmlStyle = StyleXML(base: { /// some attributes for base style }) // This method is called when a new `img` tag is found. It's your chance to // return a custom image. If you return `nil` (or you don't implement this method) // image is searched inside any bundled `xcasset` file. xmlStyle.imageProvider = { (imageName, attributes) in switch imageName { case "check": // create & return your own image default: // ... } } self.textView?.attributedText = xmlText.set(style: x) ``` <a name="stylemanager"/> ## The `StyleManager` <a name="globalregister"/> ## Register globally available styles Styles can be created as you need or registered globally to be used once you need. This second approach is strongly suggested because allows you to theme your app as you need and also avoid duplication of the code. To register a `Style` or a `StyleXML` globally you need to assign an unique identifier to it and call `register()` function via `Styles` shortcut (which is equal to call `StylesManager.shared`). In order to keep your code type-safer you can use a non-instantiable struct to keep the name of your styles, then use it to register style: ```swift // Define a struct with your styles names public struct StyleNames { public static let body: String = "body" public static let h1: String = "h1" public static let h2: String = "h2" private init { } } ``` Then you can: ```swift let bodyStyle: Style = ... Styles.register(StyleNames.body, bodyStyle) ``` Now you can use it everywhere inside the app; you can apply it to a text just using its name: ```swift let text = "hello world".set(StyleNames.body) ``` or you can assign `body` string to the `styledText` via Interface Builder designable property. <a name="defer"/> ## Defer style creation on demand Sometimes you may need to return a particular style used only in small portion of your app; while you can still set it directly you can also defer its creation in `StylesManager`. By implementing `onDeferStyle()` callback you have an option to create a new style once required: you will receive the identifier of the style. ```swift Styles.onDeferStyle = { name in if name == "MyStyle" { let normal = Style { $0.font = SystemFonts.Helvetica_Light.font(size: 15) } let bold = Style { $0.font = SystemFonts.Helvetica_Bold.font(size: 20) $0.color = UIColor.red $0.backColor = UIColor.yellow } let italic = normal.byAdding { $0.traitVariants = .italic } return (StyleXML(base: normal, ["bold": bold, "italic": italic]), true) } return (nil,false) } ``` The following code return a valid style for `myStyle` identifier and cache it; if you don't want to cache it just return `false` along with style instance. Now you can use your style to render, for example, a tag based text into an `UILabel`: just set the name of the style to use. <img src="Documentation_Assests/image_3.png" alt="" width=400px> <a name="ib"/> ## Assign style using Interface Builder SwiftRichString can be used also via Interface Builder. - `UILabel` - `UITextView` - `UITextField` has three additional properties: - `styleName: String` (available via IB): you can set it to render the text already set via Interface Builder with a style registered globally before the parent view of the UI control is loaded. - `style: StyleProtocol`: you can set it to render the text of the control with an instance of style instance. - `styledText: String`: use this property, instead of `attributedText` to set a new text for the control and render it with already set style. You can continue to use `attributedText` and set the value using `.set()` functions of `String`/`AttributedString`. Assigned style can be a `Style`, `StyleXML` or `StyleRegEx`: - if style is a `Style` the entire text of the control is set with the attributes defined by the style. - if style is a `StyleXML` a base attribute is set (if `base` is valid) and other attributes are applied once each tag is found. - if style is a `StyleRegEx` a base attribute is set (if `base` is valid) and the attribute is applied only for matches of the specified pattern. Typically you will set the style of a label via `Style Name` (`styleName`) property in IB and update the content of the control by setting the `styledText`: ```swift // use `styleName` set value to update a text with the style self.label?.styledText = "Another text to render" // text is rendered using specified `styleName` value. ``` Otherwise you can set values manually: ```swift // manually set the an attributed string self.label?.attributedText = (self.label?.text ?? "").set(myStyle) // manually set the style via instance self.label?.style = myStyle self.label?.styledText = "Updated text" ``` <a name="props"/> ## Properties available via `Style` class The following properties are available: | PROPERTY | TYPE | DESCRIPTION | |-------------------------------|---------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------| | size | `CGFloat` | font size in points | | font | `FontConvertible` | font used in text | | color | `ColorConvertible` | foreground color of the text | | backColor | `ColorConvertible` | background color of the text | | shadow | `NSShadow` | shadow effect of the text | | underline | `(NSUnderlineStyle?,ColorConvertible?)` | underline style and color (if color is nil foreground is used) | | strikethrough | `(NSUnderlineStyle?,ColorConvertible?)` | strikethrough style and color (if color is nil foreground is used) | | baselineOffset | `Float` | characterโ€™s offset from the baseline, in point | | paragraph | `NSMutableParagraphStyle` | paragraph attributes | | lineSpacing | `CGFloat` | distance in points between the bottom of one line fragment and the top of the next | | paragraphSpacingBefore | `CGFloat` | distance between the paragraphโ€™s top and the beginning of its text content | | paragraphSpacingAfter | `CGFloat` | space (measured in points) added at the end of the paragraph | | alignment | `NSTextAlignment` | text alignment of the receiver | | firstLineHeadIndent | `CGFloat` | distance (in points) from the leading margin of a text container to the beginning of the paragraphโ€™s first line. | | headIndent | `CGFloat` | The distance (in points) from the leading margin of a text container to the beginning of lines other than the first. | | tailIndent | `CGFloat` | this value is the distance from the leading margin, If 0 or negative, itโ€™s the distance from the trailing margin. | | lineBreakMode | `LineBreak` | mode that should be used to break lines | | minimumLineHeight | `CGFloat` | minimum height in points that any line in the receiver will occupy regardless of the font size or size of any attached graphic | | maximumLineHeight | `CGFloat` | maximum height in points that any line in the receiver will occupy regardless of the font size or size of any attached graphic | | baseWritingDirection | `NSWritingDirection` | initial writing direction used to determine the actual writing direction for text | | lineHeightMultiple | `CGFloat` | natural line height of the receiver is multiplied by this factor (if positive) before being constrained by minimum and maximum line height | | hyphenationFactor | `Float` | threshold controlling when hyphenation is attempted | | ligatures | `Ligatures` | Ligatures cause specific character combinations to be rendered using a single custom glyph that corresponds to those characters | | speaksPunctuation | `Bool` | Enable spoken of all punctuation in the text | | speakingLanguage | `String` | The language to use when speaking a string (value is a BCP 47 language code string). | | speakingPitch | `Double` | Pitch to apply to spoken content | | speakingPronunciation | `String` | | | shouldQueueSpeechAnnouncement | `Bool` | Spoken text is queued behind, or interrupts, existing spoken content | | headingLevel | `HeadingLevel` | Specify the heading level of the text | | numberCase | `NumberCase` | "Configuration for the number case, also known as ""figure style""" | | numberSpacing | `NumberSpacing` | "Configuration for number spacing, also known as ""figure spacing""" | | fractions | `Fractions` | Configuration for displyaing a fraction | | superscript | `Bool` | Superscript (superior) glpyh variants are used, as in footnotes_. | | `subscript` | `Bool` | Subscript (inferior) glyph variants are used: v_. | | ordinals | `Bool` | Ordinal glyph variants are used, as in the common typesetting of 4th. | | scientificInferiors | `Bool` | Scientific inferior glyph variants are used: H_O | | smallCaps | `Set<SmallCaps>` | Configure small caps behavior. | | stylisticAlternates | `StylisticAlternates` | Different stylistic alternates available for customizing a font. | | contextualAlternates | `ContextualAlternates` | Different contextual alternates available for customizing a font. | | kerning | `Kerning` | Tracking to apply. | | traitVariants | `TraitVariant` | Describe trait variants to apply to the font | <a name="requirements"/> ## Requirements * Swift 5.1+ * iOS 8.0+ * macOS 11.0+ * watchOS 2.0+ * tvOS 11.0+ <a name="installation"/> ## Installation ### CocoaPods [CocoaPods](https://cocoapods.org/) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile: ```ruby pod 'SwiftRichString' ``` ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the swift compiler. It is in early development, but Alamofire does support its use on supported platforms. Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift. ```swift dependencies: [ .package(url: "https://github.com/malcommac/SwiftRichString.git", from: "3.5.0") ] ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate SwiftRichString into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "malcommac/SwiftRichString" ``` Run `carthage` to build the framework and drag the built `SwiftRichString.framework` into your Xcode project. <a name="contributing" /> ## Contributing Issues and pull requests are welcome! Contributors are expected to abide by the [Contributor Covenant Code of Conduct](https://github.com/malcommac/SwiftRichString/blob/master/CONTRIBUTING.md). ## Copyright SwiftRichString is available under the MIT license. See the LICENSE file for more info. Daniele Margutti: [[email protected]](mailto:[email protected]), [@danielemargutti](https://twitter.com/danielemargutti)
184
coobjc provides coroutine support for Objective-C and Swift. We added await methodใ€generator and actor model like C#ใ€Javascript and Kotlin. For convenience, we added coroutine categories for some Foundation and UIKit API in cokit framework like NSFileManager, JSON, NSData, UIImage etc. We also add tuple support in coobjc.
<p align="center" > <img src="coobjc_icon.png" alt="coobjc" title="coobjc"> </p> This library provides coroutine support for Objective-C and Swift. We added await methodใ€generator and actor model like C#ใ€Javascript and Kotlin. For convenience, we added coroutine categories for some Foundation and UIKit API in [cokit framework](cokit/README.md) like NSFileManager, JSON, NSData, UIImage etc. We also add tuple support in coobjc. [cooobjc ไธญๆ–‡ๆ–‡ๆกฃ](README_cn.md) ## 0x0 iOS Asynchronous programming problem Block-based asynchronous programming callback is currently the most widely used asynchronous programming method for iOS. The GCD library provided by iOS system makes asynchronous development very simple and convenient, but there are many disadvantages based on this programming method๏ผš * get into Callback hell Sequence of simple operations is unnaturally composed in the nested blocks. This "Callback hell" makes it difficult to keep track of code that is running, and the stack of closures leads to many second order effects. * Handling errors becomes difficult and very verbose * Conditional execution is hard and error-prone * forget to call the completion block * Because completion handlers are awkward, too many APIs are defined synchronously This is hard to quantify, but the authors believe that the awkwardness of defining and using asynchronous APIs (using completion handlers) has led to many APIs being defined with apparently synchronous behavior, even when they can block. This can lead to problematic performance and responsiveness problems in UI applications - e.g. spinning cursor. It can also lead to the definition of APIs that cannot be used when asynchrony is critical to achieve scale, e.g. on the server. * Multi-threaded crashes that are difficult to locate * Locks and semaphore abuse caused by blocking ## 0x1 Solution These problem have been faced in many systems and many languages, and the abstraction of coroutines is a standard way to address them. Without delving too much into theory, coroutines are an extension of basic functions that allow a function to return a value or be suspended. They can be used to implement generators, asynchronous models, and other capabilities - there is a large body of work on the theory, implementation, and optimization of them. Kotlin is a static programming language supported by JetBrains that supports modern multi-platform applications. It has been quite hot in the developer community for the past two years. In the Kotlin language, async/await based on coroutine, generator/yield and other asynchronous technologies have become syntactic standard, Kotlin coroutine related introduction, you can refer to๏ผš[https://www.kotlincn.net/docs/reference/coroutines/basics.html](https://www.kotlincn.net/docs/reference/coroutines/basics.html) ## 0x2 Coroutine > **Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions, event loops, iterators, infinite lists and pipes** The concept of coroutine has been proposed in the 1960s. It is widely used in the server. It is extremely suitable for use in high concurrency scenarios. It can greatly reduce the number of threads in a single machine and improve the connection and processing capabilities of a single machine. In the meantime, iOS currently does not support the use of coroutines๏ผˆThat's why we want to support it.๏ผ‰ ## 0x3 coobjc framework coobjc is a coroutine development framework that can be used on the iOS by the Alibaba Taobao-Mobile architecture team. Currently it supports the use of Objective-C and Swift. We use the assembly and C language for development, and the upper layer provides the interface between Objective-C and Swift. Currently, It's open source here under Apache open source license. ### 0x31 Install * cocoapods for objective-c:ย  pod 'coobjc' * cocoapods for swift: pod 'coswift' * cocoapods for cokit: pod 'cokit' * source code: All the code is in the ./coobjc directory ### 0x32 Documents * Read the [Coroutine framework design](docs/arch_design.md) document. * Read the [coobjc Objective-C Guide](docs/usage.md) document. * Read the [coobjc Swift Guide](docs/usage_swift.md) document. * Read the [cokit framework](cokit/README.md) document, learn how to use the wrapper api of System Interface. * We have provided [coobjcBaseExample](Examples/coobjcBaseExample) demos for coobjc, [coSwiftDemo](Examples/coSwiftDemo) for coswift, [coKitExamples](cokit/Examples/coKitExamples) for cokit ### 0x33 Features #### async/await * create coroutine Create a coroutine using the co_launch method ```objc co_launch(^{ ... }); ``` The coroutine created by co_launch is scheduled by default in the current thread. * await asynchronous method In the coroutine we use the await method to wait for the asynchronous method to execute, get the asynchronous execution result ```objc - (void)viewDidLoad { ... co_launch(^{ // async downloadDataFromUrl NSData *data = await(downloadDataFromUrl(url)); // async transform data to image UIImage *image = await(imageFromData(data)); // set image to imageView self.imageView.image = image; }); } ``` The above code turns the code that originally needs dispatch_async twice into sequential execution, and the code is more concise. * error handling In the coroutine, all our methods are directly returning the value, and no error is returned. Our error in the execution process is obtained by co_getError(). For example, we have the following interface to obtain data from the network. When the promise will reject: error ```objc - (COPromise*)co_GET:(NSString*)url parameters:(NSDictionary*)parameters{ COPromise *promise = [COPromise promise]; [self GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [promise fulfill:responseObject]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [promise reject:error]; }]; return promise; } ``` Then we can use the method in the coroutine๏ผš ```objc co_launch(^{ id response = await([self co_GET:feedModel.feedUrl parameters:nil]); if(co_getError()){ //handle error message } ... }); ``` #### Generator * create generator We use co_sequence to create the generator ```objc COCoroutine *co1 = co_sequence(^{ int index = 0; while(co_isActive()){ yield_val(@(index)); index++; } }); ``` In other coroutines, we can call the next method to get the data in the generator. ```objc co_launch(^{ for(int i = 0; i < 10; i++){ val = [[co1 next] intValue]; } }); ``` * use case The generator can be used in many scenarios, such as message queues, batch download files, bulk load caches, etc.: ```objc int unreadMessageCount = 10; NSString *userId = @"xxx"; COSequence *messageSequence = co_sequence_onqueue(background_queue, ^{ //thread execution in the background while(1){ yield(queryOneNewMessageForUserWithId(userId)); } }); //Main thread update UI co_launch(^{ for(int i = 0; i < unreadMessageCount; i++){ if(!isQuitCurrentView()){ displayMessage([messageSequence next]); } } }); ``` Through the generator, we can load the data from the traditional producer--notifying the consumer model, turning the consumer into the data-->telling the producer to load the pattern, avoiding the need to use many shared variables for the state in multi-threaded computing. Synchronization eliminates the use of locks in certain scenarios. #### Actor > **_The concept of Actor comes from Erlang. In AKKA, an Actor can be thought of as a container for storing state, behavior, Mailbox, and child Actor and Supervisor policies. Actors do not communicate directly, but use Mail to communicate with each other._** * create actor We can use co_actor_onqueue to create an actor in the specified thread. ```objc COActor *actor = co_actor_onqueue(q, ^(COActorChan *channel) { ... //Define the state variable of the actor for(COActorMessage *message in channel){ ...//handle message } }); ``` * send a message to the actor The actor's send method can send a message to the actor ```objc COActor *actor = co_actor_onqueue(q, ^(COActorChan *channel) { ... //Define the state variable of the actor for(COActorMessage *message in channel){ ...//handle message } }); // send a message to the actor [actor send:@"sadf"]; [actor send:@(1)]; ``` #### tuple * create tuple we provide co_tuple method to create tuple ```objc COTuple *tup = co_tuple(nil, @10, @"abc"); NSAssert(tup[0] == nil, @"tup[0] is wrong"); NSAssert([tup[1] intValue] == 10, @"tup[1] is wrong"); NSAssert([tup[2] isEqualToString:@"abc"], @"tup[2] is wrong"); ``` you can store any value in tuple * unpack tuple we provide co_unpack method to unpack tuple ```objc id val0; NSNumber *number = nil; NSString *str = nil; co_unpack(&val0, &number, &str) = co_tuple(nil, @10, @"abc"); NSAssert(val0 == nil, @"val0 is wrong"); NSAssert([number intValue] == 10, @"number is wrong"); NSAssert([str isEqualToString:@"abc"], @"str is wrong"); co_unpack(&val0, &number, &str) = co_tuple(nil, @10, @"abc", @10, @"abc"); NSAssert(val0 == nil, @"val0 is wrong"); NSAssert([number intValue] == 10, @"number is wrong"); NSAssert([str isEqualToString:@"abc"], @"str is wrong"); co_unpack(&val0, &number, &str, &number, &str) = co_tuple(nil, @10, @"abc"); NSAssert(val0 == nil, @"val0 is wrong"); NSAssert([number intValue] == 10, @"number is wrong"); NSAssert([str isEqualToString:@"abc"], @"str is wrong"); NSString *str1; co_unpack(nil, nil, &str1) = co_tuple(nil, @10, @"abc"); NSAssert([str1 isEqualToString:@"abc"], @"str1 is wrong"); ``` * use tuple in coroutine first create a promise that resolve tuple value ```objc COPromise<COTuple*>* cotest_loadContentFromFile(NSString *filePath){ return [COPromise promise:^(COPromiseFullfill _Nonnull resolve, COPromiseReject _Nonnull reject) { if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSData *data = [[NSData alloc] initWithContentsOfFile:filePath]; resolve(co_tuple(filePath, data, nil)); } else{ NSError *error = [NSError errorWithDomain:@"fileNotFound" code:-1 userInfo:nil]; resolve(co_tuple(filePath, nil, error)); } }]; } ``` then you can fetch the value like this: ```objc co_launch(^{ NSString *tmpFilePath = nil; NSData *data = nil; NSError *error = nil; co_unpack(&tmpFilePath, &data, &error) = await(cotest_loadContentFromFile(filePath)); XCTAssert([tmpFilePath isEqualToString:filePath], @"file path is wrong"); XCTAssert(data.length > 0, @"data is wrong"); XCTAssert(error == nil, @"error is wrong"); }); ``` use tuple you can get multiple values from await return #### Actual case using coobjc Let's take the code of the Feeds stream update in the GCDFetchFeed open source project as an example to demonstrate the actual usage scenarios and advantages of the coroutine. The following is the original implementation of not using coroutine๏ผš ```objc - (RACSignal *)fetchAllFeedWithModelArray:(NSMutableArray *)modelArray { @weakify(self); return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) { @strongify(self); //Create a parallel queue dispatch_queue_t fetchFeedQueue = dispatch_queue_create("com.starming.fetchfeed.fetchfeed", DISPATCH_QUEUE_CONCURRENT); dispatch_group_t group = dispatch_group_create(); self.feeds = modelArray; for (int i = 0; i < modelArray.count; i++) { dispatch_group_enter(group); SMFeedModel *feedModel = modelArray[i]; feedModel.isSync = NO; [self GET:feedModel.feedUrl parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { dispatch_async(fetchFeedQueue, ^{ @strongify(self); //parse feed self.feeds[i] = [self.feedStore updateFeedModelWithData:responseObject preModel:feedModel]; //save to db SMDB *db = [SMDB shareInstance]; @weakify(db); [[db insertWithFeedModel:self.feeds[i]] subscribeNext:^(NSNumber *x) { @strongify(db); SMFeedModel *model = (SMFeedModel *)self.feeds[i]; model.fid = [x integerValue]; if (model.imageUrl.length > 0) { NSString *fidStr = [x stringValue]; db.feedIcons[fidStr] = model.imageUrl; } //sendNext [subscriber sendNext:@(i)]; //Notification single completion dispatch_group_leave(group); }]; });//end dispatch async } failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Error: %@", error); dispatch_async(fetchFeedQueue, ^{ @strongify(self); [[[SMDB shareInstance] insertWithFeedModel:self.feeds[i]] subscribeNext:^(NSNumber *x) { SMFeedModel *model = (SMFeedModel *)self.feeds[i]; model.fid = [x integerValue]; dispatch_group_leave(group); }]; });//end dispatch async }]; }//end for //Execution event after all is completed dispatch_group_notify(group, dispatch_get_main_queue(), ^{ [subscriber sendCompleted]; }); return nil; }]; } ``` The following is the call to the above method in viewDidLoad: ```objc [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; self.fetchingCount = 0; @weakify(self); [[[[[[SMNetManager shareInstance] fetchAllFeedWithModelArray:self.feeds] map:^id(NSNumber *value) { @strongify(self); NSUInteger index = [value integerValue]; self.feeds[index] = [SMNetManager shareInstance].feeds[index]; return self.feeds[index]; }] doCompleted:^{ @strongify(self); NSLog(@"fetch complete"); self.tbHeaderLabel.text = @""; self.tableView.tableHeaderView = [[UIView alloc] init]; self.fetchingCount = 0; [self.tableView.mj_header endRefreshing]; [self.tableView reloadData]; if ([SMFeedStore defaultFeeds].count > self.feeds.count) { self.feeds = [SMFeedStore defaultFeeds]; [self fetchAllFeeds]; } [self cacheFeedItems]; }] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(SMFeedModel *feedModel) { @strongify(self); self.tableView.tableHeaderView = self.tbHeaderView; self.fetchingCount += 1; self.tbHeaderLabel.text = [NSString stringWithFormat:@"ๆญฃๅœจ่Žทๅ–%@...(%lu/%lu)",feedModel.title,(unsigned long)self.fetchingCount,(unsigned long)self.feeds.count]; feedModel.isSync = YES; [self.tableView reloadData]; }]; ``` The above code is relatively poor in terms of readability and simplicity. Let's take a look at the code after using the coroutine transformation: ```objc - (SMFeedModel*)co_fetchFeedModelWithUrl:(SMFeedModel*)feedModel{ feedModel.isSync = NO; id response = await([self co_GET:feedModel.feedUrl parameters:nil]); if (response) { SMFeedModel *resultModel = await([self co_updateFeedModelWithData:response preModel:feedModel]); int fid = [[SMDB shareInstance] co_insertWithFeedModel:resultModel]; resultModel.fid = fid; if (resultModel.imageUrl.length > 0) { NSString *fidStr = [@(fid) stringValue]; [SMDB shareInstance].feedIcons[fidStr] = resultModel.imageUrl; } return resultModel; } int fid = [[SMDB shareInstance] co_insertWithFeedModel:feedModel]; feedModel.fid = fid; return nil; } ``` Here is the place in viewDidLoad that uses the coroutine to call the interface: ```objc co_launch(^{ for (NSUInteger index = 0; index < self.feeds.count; index++) { SMFeedModel *model = self.feeds[index]; self.tableView.tableHeaderView = self.tbHeaderView; self.tbHeaderLabel.text = [NSString stringWithFormat:@"ๆญฃๅœจ่Žทๅ–%@...(%lu/%lu)",model.title,(unsigned long)(index + 1),(unsigned long)self.feeds.count]; model.isSync = YES; SMFeedModel *resultMode = [[SMNetManager shareInstance] co_fetchFeedModelWithUrl:model]; if (resultMode) { self.feeds[index] = resultMode; [self.tableView reloadData]; } } self.tbHeaderLabel.text = @""; self.tableView.tableHeaderView = [[UIView alloc] init]; self.fetchingCount = 0; [self.tableView.mj_header endRefreshing]; [self.tableView reloadData]; [self cacheFeedItems]; }); ``` The code after the coroutine transformation has become easier to understand and less error-prone. #### Swift coobjc fully supports Swift through top-level encapsulation, enabling us to enjoy the coroutine ahead of time in Swift. Because Swift has richer and more advanced syntax support, coobjc is more elegant in Swift, for example: ```swift func test() { co_launch {//create coroutine //fetch data asynchronous let resultStr = try await(channel: co_fetchSomething()) print("result: \(resultStr)") } co_launch {//create coroutine //fetch data asynchronous let result = try await(promise: co_fetchSomethingAsynchronous()) switch result { case .fulfilled(let data): print("data: \(String(describing: data))") break case .rejected(let error): print("error: \(error)") } } } ``` ## 0x4 Advantages of the coroutine * Concise * Less concept: there are only a few operators, compared to dozens of operators in response, it can't be simpler. * The principle is simple: the implementation principle of the coroutine is very simple, the entire coroutine library has only a few thousand lines of code * Easy to use * Simple to use: it is easier to use than GCD, with few interfaces * Easy to retrofit: existing code can be corouted with only a few changes, and we have a large number of coroutine interfaces for the system library. * Clear * Synchronous write asynchronous logic: Synchronous sequential way of writing code is the most acceptable way for humans, which can greatly reduce the probability of error * High readability: Code written in coroutine mode is much more readable than block nested code * High performance * Faster scheduling performance: The coroutine itself does not need to switch between kernel-level threads, scheduling performance is fast, Even if you create tens of thousands of coroutines, there is no pressure. * Reduce app block: The use of coroutines to help reduce the abuse of locks and semaphores, and to reduce the number of stalls and jams from the root cause by encapsulating the coroutine interfaces such as IOs that cause blocking, and improve the overall performance of the application. ## 0x5 Communication * If youย **need help**, useย [Stack Overflow](http://stackoverflow.com/questions/tagged/coobjc). (Tag 'coobjc') * If you'd like toย **ask a general question**, useย [Stack Overflow](http://stackoverflow.com/questions/tagged/coobjc). * If youย **found a bug**,ย _and can provide steps to reliably reproduce it_, open an issue. * If youย **have a feature request**, open an issue. * If youย **want to contribute**, submit a pull request. * If you are interested in **joining Alibaba Taobao-Mobile architecture team**, please send your resume to [junzhan](mailto:[email protected]) ## 0x6 Unit Tests coobjc includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. You can find coobjc's unit tests in Examples/coobjcBaseExample/coobjcBaseExampleTests. You can find cokit's unit tests in cokit/Examples/coKitExamples/coKitExamplesTests. ## 0x7 Credits coobjc couldn't exist without: * [Promises](https://github.com/google/promises) - Google's Objective-C and Swift Promises framework. * [libtask](https://swtch.com/libtask/) - A simple coroutine library. * [movies](https://github.com/KMindeguia/movies) - a ios demo app, we use the code in coobjc examples * [v2ex](https://github.com/singro/v2ex) - An iOS client for v2ex.com, we use the code in coobjc examples * [tuples](https://github.com/atg/tuples) - Objective-C tuples. * [fishhook](https://github.com/facebook/fishhook) - Rebinding symbols in Mach-O binaries * [Sol](https://github.com/comyar/Sol) - Solยฐ beautifully displays weather information so you can plan your day accordingly. Check the weather in your current location or any city around the world. Implemented in Objective-C. * [Swift](https://github.com/apple/swift) - The Swift Programming Language * [libdispatch](https://github.com/apple/swift-corelibs-libdispatch) - The libdispatch Project, (a.k.a. Grand Central Dispatch), for concurrency on multicore hardware * [objc4](https://opensource.apple.com/source/objc4/objc4-750.1/) - apple objc framework * https://blog.csdn.net/qq910894904/article/details/41911175 * http://www.voidcn.com/article/p-fwlohnnc-gc.html * https://blog.csdn.net/shenlei19911210/article/details/61194617 ## 0x8 Authors * [pengyutang125](https://github.com/pengyutang125) * [NianJi](https://github.com/NianJi) * [intheway](https://github.com/intheway) * [ValiantCat](https://github.com/ValiantCat) * [jmpews](https://github.com/jmpews) ## 0x9 Contributing * [Contributing](./CONTRIBUTING.md) ## 0xA License coobjc is released under the Apache 2.0 license. Seeย [LICENSE](LICENSE)ย for details.
185
The smartest and most beautiful (POSIX compliant) Command line framework for Swift ๐Ÿค–
null
186
Localization/I18n: Incrementally update/translate your Strings files from .swift, .h, .m(m), .storyboard or .xib files.
<p align="center"> <img src="https://raw.githubusercontent.com/FlineDev/BartyCrouch/main/Logo.png" width=600> </p> <p align="center"> <a href="https://github.com/FlineDev/BartyCrouch/actions?query=workflow%3ACI+branch%3Amain"> <img src="https://github.com/FlineDev/BartyCrouch/workflows/CI/badge.svg?branch=main" alt="CI Status"> </a> <a href="https://www.codacy.com/gh/FlineDev/BartyCrouch"> <img src="https://api.codacy.com/project/badge/Grade/7b34ad9193c2438aa32aa29a0490451f"/> </a> <a href="https://www.codacy.com/gh/FlineDev/BartyCrouch"> <img src="https://api.codacy.com/project/badge/Coverage/7b34ad9193c2438aa32aa29a0490451f"/> </a> <a href="https://github.com/FlineDev/BartyCrouch/releases"> <img src="https://img.shields.io/badge/Version-4.14.0-blue.svg" alt="Version: 4.14.0"> </a> <img src="https://img.shields.io/badge/Swift-5.7-FFAC45.svg" alt="Swift: 5.7"> <a href="https://github.com/FlineDev/BartyCrouch/blob/main/LICENSE.md"> <img src="https://img.shields.io/badge/License-MIT-lightgrey.svg" alt="License: MIT"> </a> <br /> <a href="https://paypal.me/Dschee/5EUR"> <img src="https://img.shields.io/badge/PayPal-Donate-orange.svg" alt="PayPal: Donate"> </a> <a href="https://github.com/sponsors/Jeehut"> <img src="https://img.shields.io/badge/GitHub-Become a sponsor-orange.svg" alt="GitHub: Become a sponsor"> </a> <a href="https://patreon.com/Jeehut"> <img src="https://img.shields.io/badge/Patreon-Become a patron-orange.svg" alt="Patreon: Become a patron"> </a> </p> <p align="center"> <a href="#installation">Installation</a> โ€ข <a href="#configuration">Configuration</a> โ€ข <a href="#usage">Usage</a> โ€ข <a href="#build-script">Build Script</a> โ€ข <a href="#donation">Donation</a> โ€ข <a href="#migration-guides">Migration Guides</a> โ€ข <a href="https://github.com/FlineDev/BartyCrouch/issues">Issues</a> โ€ข <a href="#contributing">Contributing</a> โ€ข <a href="#license">License</a> </p> > :sparkles: **Important Notice** :sparkles: > > There's [**now a new Mac app called RemafoX**](https://remafox.app?source=github.com.BartyCrouch) which is the _successor_ to BartyCrouch. It improves upon several aspects of BartyCrouch, such as having **no flaky dependencies**, adding **pluralization** support, **smart** machine translation, a built-in SwiftUI-compatible **enum generator**, built-in **step-by-step instructions** for easier setup, **detailed explanations** of all config options, and even [**a set of video guides**](https://www.youtube.com/watch?v=ObGIiWARjmw&list=PLvkAveYAfY4TLPtPd5jnqMwpAzY_pdxs5) for things like setup, key naming best practices and team onboarding. Get it for free [here](https://apps.apple.com/app/apple-store/id1605635026?pt=549314&ct=github.com.BartyCrouch&mt=8). > > Note that RemafoX is being **actively worked on**, you can even [vote for or request new features here](https://github.com/FlineDev/RemafoX/issues?q=is%3Aissue+label%3A%22Feature+Request%22+sort%3Areactions-%2B1-desc). > In comparison, BartyCrouch is kept up-to-date mostly by the community. # BartyCrouch BartyCrouch **incrementally updates** your Strings files from your Code *and* from Interface Builder files. "Incrementally" means that BartyCrouch will by default **keep** both your already **translated values** and even your altered comments. Additionally you can also use BartyCrouch for **machine translating** from one language to 60+ other languages. Using BartyCrouch is as easy as **running a few simple commands** from the command line what can even be **automated using a [build script](#build-script)** within your project. Checkout [this blog post](https://jeehut.medium.com/localization-in-swift-like-a-pro-48164203afe2?sk=da26d918390db21261b7ead4837286fc) to learn how you can effectively use BartyCrouch in your projects. ## Requirements - Xcode 14+ & Swift 5.7+ - Xcode Command Line Tools (see [here](http://stackoverflow.com/a/9329325/3451975) for installation instructions) ## Getting Started ### Installation <details> <summary>Via <a href="https://brew.sh/">Homebrew</a></summary> To install Bartycrouch the first time, simply run the command: ```bash brew install bartycrouch ``` To **update** to the newest version of BartyCrouch when you have an old version already installed run: ```bash brew upgrade bartycrouch ``` </details> <details> <summary>Via <a href="https://github.com/yonaskolb/Mint">Mint</a></summary> To **install** or update to the latest version of BartyCrouch simply run this command: ```bash mint install FlineDev/BartyCrouch ``` </details> ### Configuration To configure BartyCrouch for your project, first create a configuration file within your projects root directory. BartyCrouch can do this for you: ``` bartycrouch init ``` Now you should have a file named `.bartycrouch.toml` with the following contents: ```toml [update] tasks = ["interfaces", "code", "transform", "normalize"] [update.interfaces] paths = ["."] subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"] defaultToBase = false ignoreEmptyStrings = false unstripped = false ignoreKeys = ["#bartycrouch-ignore!", "#bc-ignore!", "#i!"] [update.code] codePaths = ["."] subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"] localizablePaths = ["."] defaultToKeys = false additive = true unstripped = false ignoreKeys = ["#bartycrouch-ignore!", "#bc-ignore!", "#i!"] [update.transform] codePaths = ["."] subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"] localizablePaths = ["."] transformer = "foundation" supportedLanguageEnumPath = "." typeName = "BartyCrouch" translateMethodName = "translate" [update.normalize] paths = ["."] subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"] sourceLocale = "en" harmonizeWithSource = true sortByKeys = true [lint] paths = ["."] subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"] duplicateKeys = true emptyValues = true ``` This is the default configuration of BartyCrouch and should work for most projects as is. In order to use BartyCrouch to its extent, it is recommended though to consider making the following changes: 1. To speed it up significantly, provide more specific paths for any key containing `path` if possible (especially in the `update.transform` section, e.g. `["App/Sources"]` for `codePaths` or `["App/Supporting Files"]` for `supportedLanguageEnumPaths`). 2. Remove the `code` task if your project is Swift-only and you use the new [`transform` update task](#localization-workflow-via-transform). 3. If you are using [SwiftGen](https://github.com/SwiftGen/SwiftGen#strings) with the `structured-swift4` template, you will probably want to use the `transform` task and change its `transformer` option to `swiftgenStructured`. 4. If you decided to use the `transform` task, create a new file in your project (e.g. under `SupportingFiles`) named `BartyCrouch.swift` and copy the following code: ```swift // This file is required in order for the `transform` task of the translation helper tool BartyCrouch to work. // See here for more details: https://github.com/FlineDev/BartyCrouch import Foundation enum BartyCrouch { enum SupportedLanguage: String { // TODO: remove unsupported languages from the following cases list & add any missing languages case arabic = "ar" case chineseSimplified = "zh-Hans" case chineseTraditional = "zh-Hant" case english = "en" case french = "fr" case german = "de" case hindi = "hi" case italian = "it" case japanese = "ja" case korean = "ko" case malay = "ms" case portuguese = "pt-BR" case russian = "ru" case spanish = "es" case turkish = "tr" } static func translate(key: String, translations: [SupportedLanguage: String], comment: String? = nil) -> String { let typeName = String(describing: BartyCrouch.self) let methodName = #function print( "Warning: [BartyCrouch]", "Untransformed \(typeName).\(methodName) method call found with key '\(key)' and base translations '\(translations)'.", "Please ensure that BartyCrouch is installed and configured correctly." ) // fall back in case something goes wrong with BartyCrouch transformation return "BC: TRANSFORMATION FAILED!" } } ``` 5. If you don't develop in English as the first localized language, you should update the `sourceLocale` of the `normalize` task. 6. If you want to use the machine translation feature of BartyCrouch, add `translate` to the tasks list at the top and copy the following section into the configuration file with `secret` replaced by your [Microsoft Translator Text API Subscription Key](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/translator-text-how-to-signup#authentication-key): ```toml [update.translate] paths = "." translator = "microsoftTranslator" secret = "<#Subscription Key#>" sourceLocale = "en" ``` ## Usage Before using BartyCrouch please **make sure you have committed your code**. Also, we highly recommend using the **build script method** described [below](#build-script). --- `bartycrouch` accepts one of the following sub commands: - **`update`:** Updates your `.strings` file contents according to your configuration. - **`lint`:** Checks your `.strings` file contents for empty values & duplicate keys. Also the following command line options can be provided: - **`-v`, `--verbose`**: Prints more detailed information about the executed command. - **`-x`, `--xcode-output`**: Prints warnings & errors in Xcode compatible format. - **`-w`, `--fail-on-warnings`**: Returns a failed status code if any warning is encountered. - **`-p`, `--path`**: Specifies a different path than current to run BartyCrouch from there. ### `update` subcommand The update subcommand can be run with one or multiple of the following tasks: - `interfaces`: Updates `.strings` files of Storyboards & XIBs. - `code`: Updates `Localizable.strings` file from `NSLocalizedString` entries in code. - `transform`: A mode where BartyCrouch replaces a specific method call to provide translations in multiple languages in a single line. Only supports Swift files. - `translate`: Updates missing translations in other languages than the source language. - `normalize`: Sorts & cleans up `.strings` files. In order to configure which tasks are executed, edit this section in the config file: ```toml [update] tasks = ["interfaces", "code", "transform", "normalize"] ``` <details><summary>Options for <code>interfaces</code></summary> - `paths`: The directory / directories to search for Storyboards & XIB files. - `subpathsToIgnore`: The subpaths to be ignored inside the directories found via the `paths` option. - `defaultToBase`: Add Base translation as value to new keys. - `ignoreEmptyStrings`: Doesn't add views with empty values. - `unstripped`: Keeps whitespaces at beginning & end of Strings files. - `ignoreKeys`: Keys (e.g. in the comment) indicating that specific translation entries should be ignored when generating String files. Useful to ignore strings that are gonna be translated in code. </details> <details><summary>Options for <code>code</code></summary> - `codePaths`: The directory / directories to search for Swift code files. - `subpathsToIgnore`: The subpaths to be ignored inside the directories found via the `paths` option. - `localizablePaths`: The enclosing path(s) containing the localized `Localizable.strings` files. - `defaultToKeys`: Add new keys both as key and value. - `additive`: Prevents cleaning up keys not found in code. - `customFunction`: Use alternative name to search for strings to localize, in addition to `NSLocalizedString`, and `CFCopyLocalizedString`. Defaults to `LocalizedStringResource`. - `customLocalizableName`: Use alternative name for `Localizable.strings`. - `unstripped`: Keeps whitespaces at beginning & end of Strings files. - `plistArguments`: Use a plist file to store all the code files for the ExtractLocStrings tool. (Recommended for large projects.) - `ignoreKeys`: Keys (e.g. in the comment) indicating that specific translation entries should be ignored when generating String files. - `overrideComments`: Always overrides the comment with the keys new translation, useful for IB files. </details> <details><summary>Options for <code>transform</code></summary> - `codePaths`: The directory / directories to search for Swift code files. - `subpathsToIgnore`: The subpaths to be ignored inside the directories found via the `paths` option. - `localizablePaths`: The enclosing path(s) containing the localized `Localizable.strings` files. - `transformer`: Specifies the replacement code. Use `foundation` for `NSLocalizedString` or `swiftgenStructured` for `L10n` entries. - `supportedLanguageEnumPath`: The enclosing path containing the `SupportedLanguage` enum. - `typeName`: The name of the type enclosing the `SupportedLanguage` enum and translate method. - `translateMethodName`: The name of the translate method to be replaced. - `customLocalizableName`: Use alternative name for `Localizable.strings`. - `separateWithEmptyLine`: Set to `false` if you don't want to have empty lines between Strings entries. Defaults to `true. </details> <details><summary>Options for <code>translate</code></summary> - `paths`: The directory / directories to search for Strings files. - `subpathsToIgnore`: The subpaths to be ignored inside the directories found via the `paths` option. - `translator`: Specifies the translation API. Use `microsoftTranslator` or `deepL`. - `secret`: Your [Microsoft Translator Text API Subscription Key](https://docs.microsoft.com/en-us/azure/cognitive-services/translator/translator-text-how-to-signup#authentication-key) or [Authentication Key for DeepL API](https://www.deepl.com/pro-account/plan). - `sourceLocale`: The source language to translate from. - `separateWithEmptyLine`: Set to `false` if you don't want to have empty lines between Strings entries. Defaults to `true. </details> <details><summary>Options for <code>normalize</code></summary> - `paths`: The directory / directories to search for Strings files. - `subpathsToIgnore`: The subpaths to be ignored inside the directories found via the `paths` option. - `sourceLocale`: The source language to harmonize keys of other languages with. - `harmonizeWithSource`: Synchronizes keys with source language. - `sortByKeys`: Alphabetically sorts translations by their keys. - `separateWithEmptyLine`: Set to `false` if you don't want to have empty lines between Strings entries. Defaults to `true. </details> ### `lint` subcommand The lint subcommand was designed to analyze a project for typical translation issues. The current checks include: - `duplicateKeys`: Finds duplicate keys within the same file. - `emptyValues`: Finds empty values for any language. Note that the `lint` command can be used both on CI and within Xcode via the build script method: - In Xcode the `-x` or `--xcode-output` command line argument should be used to get warnings which point you directly to the found issue. - When running on the CI you should specify the `-w` or `--fail-on-warnings` argument to make sure BartyCrouch fails if any warnings are encountered. ### Localization Workflow via `transform` When the `transform` update task is configured (see recommended step 4 in the [Configuration](#configuration) section above) and you are using the [build script method](#build-script), you can use the following simplified process for writing localized code during development: 1. Instead of `NSLocalizedString` calls you can use `BartyCrouch.translate` and specify a key, translations (if any) and optionally a comment. For example: ```swift self.title = BartyCrouch.translate(key: "onboarding.first-page.header-title", translations: [.english: "Welcome!"]) ``` 2. Once you build your app, BartyCrouch will automatically add the new translation key to all your `Localizable.strings` files and add the provided translations as values for the provided languages. 3. Additionally, during the same build BartyCrouch will automatically replace the above call to `BartyCrouch.translate` with the proper translation call, depending on your `transformer` option setting. The resulting code depends on your `transformer` option setting: When set to `foundation`, the above code will transform to: ```swift self.title = NSLocalizedString("onboarding.first-page.header-title", comment: "") ``` When set to `swiftgenStructured` it will transform to: ```swift self.title = L10n.Onboarding.FirstPage.headerTitle ``` **Advantages of `transform` over the `code` task:** * You can provide translations for keys without switching to the Strings files. * In case you use SwiftGen, you don't need to replace calls to `NSLocalizedString` with `L10n` calls manually after running BartyCrouch. * Can be combined with the machine translation feature to provide a source language translation in code and let BartyCrouch translate it to all supported languages in a single line & without ever leaving the code. **Disadvantages of `transform` over the `code` task:** * Only works for Swift Code. No support for Objective-C. (You can use both methods simultaneously though.) * Xcode will mark the freshly transformed code as errors (but build will succeed anyways) until next build. * Not as fast as `code` since [SwiftSyntax](https://github.com/apple/swift-syntax) currently isn't [particularly fast](https://www.jpsim.com/evaluating-swiftsyntax-for-use-in-swiftlint/). (But this should improve over time!) NOTE: As of version 4.x of BartyCrouch *formatted* localized Strings are not supported by this automatic feature. ### Localizing strings of `LocalizableStringResource` type (AppIntents, ...) Historically, Apple platforms used `CFCopyLocalizedString`, and `NSLocalizedString` macros and their variants, to mark strings used in code to be localized, and to load their localized versions during runtime from `Localizable.strings` file. Since introduction of the AppIntents framework, the localized strings in code can also be typed as `LocalizedStringResource`, and are no longer marked explicitly. Let's examine this snippet of AppIntents code: ``` struct ExportAllTransactionsIntent: AppIntent { static var title: LocalizedStringResource = "Export all transactions" static var description = IntentDescription("Exports your transaction history as CSV data.") } ``` In the example above, both the `"Export all transactions"`, and `"Exports your transaction history as CSV data."` are actually `StaticString` instances that will be converted during compilation into `LocalizedStringResource` instances, and will lookup their respective localizations during runtime from `Localized.strings` file the same way as when using `NSLocalizedString` in the past. The only exception being that such strings are not marked explicitly, and require swift compiler to parse and extract such strings for localization. This is what Xcode does from version 13 when using `Product -> Export Localizations...` option. In order to continue translating these strings with `bartycrouch` it is required to mark them explicitely with `LocalizedStringResource(_: String, comment: String)` call, and specify `customFunction="LocalizedStringResource"` in `code` task options. The example AppIntents code that can be localized with `bartycrouch` will look like this: ``` struct ExportAllTransactionsIntent: AppIntent { static var title = LocalizedStringResource("Export all transactions", comment: "") static var description = IntentDescription(LocalizedStringResource("Exports your transaction history as CSV data.", comment: "")) } ``` Note that you must use the full form of `LocalizedStringResource(_: StaticString, comment: StaticString)` for the `bartycrouch`, or more specifically for the `extractLocStrings` (see `xcrun extractLocStrings`) to properly parse the strings. ### Build Script In order to truly profit from BartyCrouch's ability to update & lint your `.strings` files you can make it a natural part of your development workflow within Xcode. In order to do this select your target, choose the `Build Phases` tab and click the + button on the top left corner of that pane. Select `New Run Script Phase` and copy the following into the text box below the `Shell: /bin/sh` of your new run script phase: ```shell export PATH="$PATH:/opt/homebrew/bin" if which bartycrouch > /dev/null; then bartycrouch update -x bartycrouch lint -x else echo "warning: BartyCrouch not installed, download it from https://github.com/FlineDev/BartyCrouch" fi ``` <img src="Images/Build-Script-Example.png"> Next, make sure the BartyCrouch script runs before the steps `Compiling Sources` (and `SwiftGen` if used) by moving it per drag & drop, for example right after `Target Dependencies`. Now BartyCrouch will be run on each build and you won't need to call it manually ever (again). Additionally, all your co-workers who don't have BartyCrouch installed will see a warning with a hint on how to install it. *Note: Please make sure you commit your code using source control regularly when using the build script method.* --- ### Exclude specific Views / NSLocalizedStrings from Localization Sometimes you may want to **ignore some specific views** containing localizable texts e.g. because **their values are going to be set programmatically**. For these cases you can simply include `#bartycrouch-ignore!` or the shorthand `#bc-ignore!` into your value within your base localized Storyboard/XIB file. Alternatively you can add `#bc-ignore!` into the field "Comment For Localizer" box in the utilities pane. This will tell BartyCrouch to ignore this specific view when updating your `.strings` files. Here's an example of how a base localized view in a XIB file with partly ignored strings might look like: <img src="Images/Exclusion-Example.png"> Here's an example with the alternative comment variant: <div style="float:left;"> <img src="Images/IB-Comment-Exclusion-Example1.png" width="255px" height="437px"> <img src="Images/IB-Comment-Exclusion-Example2.png" width="254px" height="140px"> </div> You can also use `#bc-ignore!` in your `NSLocalizedString` macros comment part to ignore them so they are not added to your `Localizable.strings`. This might be helpful when you are using a `.stringsdict` file to handle pluralization (see [docs](https://developer.apple.com/library/ios/documentation/MacOSX/Conceptual/BPInternational/StringsdictFileFormat/StringsdictFileFormat.html)). For example you can do something like this: ```swift func updateTimeLabel(minutes: Int) { String.localizedStringWithFormat(NSLocalizedString("%d minute(s) ago", comment: "pluralized and localized minutes #bc-ignore!"), minutes) } ``` The `%d minute(s) ago` key will be taken from Localizable.stringsdict file, not from Localizable.strings, that's why it should be ignored by BartyCrouch. ## Donation BartyCrouch was brought to you by [Cihat Gรผndรผz](https://github.com/Jeehut) in his free time. If you want to thank me and support the development of this project, please **make a small donation on [PayPal](https://paypal.me/Dschee/5EUR)**. In case you also like my other [open source contributions](https://github.com/FlineDev) and [articles](https://medium.com/@Jeehut), please consider motivating me by **becoming a sponsor on [GitHub](https://github.com/sponsors/Jeehut)** or a **patron on [Patreon](https://www.patreon.com/Jeehut)**. Thank you very much for any donation, it really helps out a lot! ๐Ÿ’ฏ ## Migration Guides See the file [MIGRATION_GUIDES.md](https://github.com/FlineDev/BartyCrouch/blob/main/MIGRATION_GUIDES.md). ## Contributing Contributions are welcome. Feel free to open an issue on GitHub with your ideas or implement an idea yourself and post a pull request. If you want to contribute code, please try to follow the same syntax and semantic in your **commit messages** (see rationale [here](http://chris.beams.io/posts/git-commit/)). Also, please make sure to add an entry to the `CHANGELOG.md` file which explains your change. In order for the tests to run build issues, you need to run โ€“ also add an an API key in the new file to run the translations tests, too: ```shell cp Tests/BartyCrouchTranslatorTests/Secrets/secrets.json.sample Tests/BartyCrouchTranslatorTests/Secrets/secrets.json ``` After Release Checklist: 1. Run `make portable_zip` to generate `.build/release/portable_bartycrouch.zip` 2. Create new release with text from new `CHANGELOG.md` section & attach `portable_bartycrouch.zip` as binary 3. Run `pod trunk push` to make a new release known to CocoaPods 4. Update `tag` and `revision` in `Formula/bartycrouch.rb`, commit & push change 5. Run `brew bump-formula-pr bartycrouch --tag=<tag> --revision=<revision>` ## License This library is released under the [MIT License](http://opensource.org/licenses/MIT). See LICENSE for details.
187
:books: ๅ…่ดน็š„่ฎก็ฎ—ๆœบ็ผ–็จ‹็ฑปไธญๆ–‡ไนฆ็ฑ๏ผŒๆฌข่ฟŽๆŠ•็จฟ
ๅ…่ดน็š„็ผ–็จ‹ไธญๆ–‡ไนฆ็ฑ็ดขๅผ• ============================ [![](https://img.shields.io/github/issues/justjavac/free-programming-books-zh_CN.svg)](https://github.com/justjavac/free-programming-books-zh_CN/issues) [![](https://img.shields.io/github/forks/justjavac/free-programming-books-zh_CN.svg)](https://github.com/justjavac/free-programming-books-zh_CN/network) [![](https://img.shields.io/github/stars/justjavac/free-programming-books-zh_CN.svg)](https://github.com/justjavac/free-programming-books-zh_CN/stargazers) [![](https://travis-ci.org/justjavac/free-programming-books-zh_CN.svg?branch=master)](https://travis-ci.org/justjavac/free-programming-books-zh_CN) [![](https://img.shields.io/github/release/justjavac/free-programming-books-zh_CN.svg)](https://github.com/justjavac/free-programming-books-zh_CN/releases) ๅ…่ดน็š„็ผ–็จ‹ไธญๆ–‡ไนฆ็ฑ็ดขๅผ•๏ผŒๆฌข่ฟŽๆŠ•็จฟใ€‚ - ๅ›ฝๅค–็จ‹ๅบๅ‘˜ๅœจ [stackoverflow](http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read/1713%231713) ๆŽจ่็š„็จ‹ๅบๅ‘˜ๅฟ…่ฏปไนฆ็ฑ๏ผŒ[ไธญๆ–‡็‰ˆ](http://justjavac.com/other/2012/05/15/qualified-programmer-should-read-what-books.html "ไธ€ไธชๅˆๆ ผ็š„็จ‹ๅบๅ‘˜ๅบ”่ฏฅ่ฏป่ฟ‡ๅ“ชไบ›ไนฆ")ใ€‚ - [stackoverflow](http://stackoverflow.com/questions/38210/what-non-programming-books-should-programmers-read) ไธŠ็š„็จ‹ๅบๅ‘˜ๅบ”่ฏฅ้˜…่ฏป็š„้ž็ผ–็จ‹็ฑปไนฆ็ฑๆœ‰ๅ“ชไบ›๏ผŸ [ไธญๆ–‡็‰ˆ](what-non-programming-books-should-programmers-read.md) - [github](https://github.com/vhf/free-programming-books) ไธŠ็š„ไธ€ไธชๆต่กŒ็š„็ผ–็จ‹ไนฆ็ฑ็ดขๅผ• [ไธญๆ–‡็‰ˆ](https://github.com/vhf/free-programming-books/blob/master/free-programming-books-zh.md) ๅฆ‚ๆžœ่ฟ™ไธชไป“ๅบ“ๅฏนไฝ ๆœ‰ๅธฎๅŠฉ๏ผŒๆฌข่ฟŽ starใ€‚ๅฆ‚ๆžœ่ฟ™ไธชไป“ๅบ“ๅธฎไฝ ๆๅ‡ไบ†ๆŠ€่ƒฝๆ‰พๅˆฐไบ†ๅทฅไฝœ๏ผŒๅฏไปฅ่ฏทๆˆ‘ๅ–ๆฏๅ’–ๅ•ก๏ผš <p align="center"><img src="https://dl.deno.js.cn/buy-me-a-coffee-wechat.png" width="320" height="320" alt="" /></p> ## ๅ‚ไธŽไบคๆต ๆฌข่ฟŽๅคงๅฎถๅฐ†็่—ๅทฒไน…็š„็ปๅ…ธๅ…่ดนไนฆ็ฑๅ…ฑไบซๅ‡บๆฅ๏ผŒๆ‚จๅฏไปฅ๏ผš * ไฝฟ็”จ [Pull Request](https://github.com/justjavac/free-programming-books-zh_CN/pulls) ๆไบค ๅฆ‚ๆžœไฝ ๅ‘็Žฐไบ†ไธ่ƒฝ่ฎฟ้—ฎ็š„้“พๆŽฅ๏ผŒไนŸๅฏไปฅๆ PR๏ผŒๅœจๆ— ๆณ•่ฎฟ้—ฎ้“พๆŽฅ็š„ๅŽ้ขๅขžๅŠ  `:worried:`ใ€‚ ่ดก็Œฎ่€…ๅๅ•: https://github.com/justjavac/free-programming-books-zh_CN/graphs/contributors ## ็›ฎๅฝ• * ่ฏญ่จ€ๆ— ๅ…ณ็ฑป * [ๆ“ไฝœ็ณป็ปŸ](#ๆ“ไฝœ็ณป็ปŸ) * [ๆ™บ่ƒฝ็ณป็ปŸ](#ๆ™บ่ƒฝ็ณป็ปŸ) * [ๅˆ†ๅธƒๅผ็ณป็ปŸ](#ๅˆ†ๅธƒๅผ็ณป็ปŸ) * [็ผ–่ฏ‘ๅŽŸ็†](#็ผ–่ฏ‘ๅŽŸ็†) * [ๅ‡ฝๆ•ฐๅผๆฆ‚ๅฟต](#ๅ‡ฝๆ•ฐๅผๆฆ‚ๅฟต) * [่ฎก็ฎ—ๆœบๅ›พๅฝขๅญฆ](#่ฎก็ฎ—ๆœบๅ›พๅฝขๅญฆ) * [WEBๆœๅŠกๅ™จ](#webๆœๅŠกๅ™จ) * [็‰ˆๆœฌๆŽงๅˆถ](#็‰ˆๆœฌๆŽงๅˆถ) * [็ผ–่พ‘ๅ™จ](#็ผ–่พ‘ๅ™จ) * [NoSQL](#nosql) * [PostgreSQL](#postgresql) * [MySQL](#mysql) * [็ฎก็†ๅ’Œ็›‘ๆŽง](#็ฎก็†ๅ’Œ็›‘ๆŽง) * [้กน็›ฎ็›ธๅ…ณ](#้กน็›ฎ็›ธๅ…ณ) * [่ฎพ่ฎกๆจกๅผ](#่ฎพ่ฎกๆจกๅผ) * [Web](#web) * [ๅคงๆ•ฐๆฎ](#ๅคงๆ•ฐๆฎ) * [็ผ–็จ‹่‰บๆœฏ](#็ผ–็จ‹่‰บๆœฏ) * [ๆธธๆˆๅผ•ๆ“Ž](#ๆธธๆˆๅผ•ๆ“Ž) * [็ฎ—ๆณ•](#็ฎ—ๆณ•) * [ๅ…ถๅฎƒ](#ๅ…ถๅฎƒ) * ่ฏญ่จ€็›ธๅ…ณ็ฑป * [Android](#android) * [APP](#app) * [AWK](#awk) * [C/C++](#cc) * [C#](#c) * [Clojure](#clojure) * [CSS/HTML](#csshtml) * [Dart](#dart) * [Elixir](#elixir) * [Erlang](#erlang) * [Fortran](#fortran) * [Go](#go) * [Groovy](#groovy) * [Haskell](#haskell) * [iOS](#ios) * [Java](#java) * [JavaScript](#javascript) * [Kotlin](#kotlin) * [LaTeX](#latex) * [LISP](#lisp) * [Lua](#lua) * [OCaml](#OCaml) * [Perl](#perl) * [PHP](#php) * [Prolog](#prolog) * [Python](#python) * [R](#r) * [Ruby](#ruby) * [Rust](#rust) * [Scala](#scala) * [Shell](#shell) * [Swift](#swift) * [่ฏปไนฆ็ฌ”่ฎฐๅŠๅ…ถๅฎƒ](#่ฏปไนฆ็ฌ”่ฎฐๅŠๅ…ถๅฎƒ) * [ๆต‹่ฏ•็›ธๅ…ณ](#ๆต‹่ฏ•็›ธๅ…ณ) ## ็ฝฎ้กถ - [[็ฌ”่ฎฐ]ๅ‰็ซฏๅทฅ็จ‹ๅธˆ็š„ๅ…ฅ้—จไธŽ่ฟ›้˜ถ](https://shenbao.github.io/2017/04/22/justjavac-live/) :100: - [[ๅ…จๆ–‡]ๅฆ‚ไฝ•ๆญฃ็กฎ็š„ๅญฆไน  Node.js](https://github.com/i5ting/How-to-learn-node-correctly) :100: ## ๆ“ไฝœ็ณป็ปŸ * [ๅผ€ๆบไธ–็•Œๆ—…่กŒๆ‰‹ๅ†Œ](http://i.linuxtoy.org/docs/guide/index.html) * [้ธŸๅ“ฅ็š„Linux็งๆˆฟ่œ](http://linux.vbird.org/) * [The Linux Command Line](http://billie66.github.io/TLCL/index.html) (ไธญ่‹ฑๆ–‡็‰ˆ) * [Linux ่ฎพๅค‡้ฉฑๅŠจ](http://oss.org.cn/kernel-book/ldd3/index.html) (็ฌฌไธ‰็‰ˆ):worried: * [ๆทฑๅ…ฅๅˆ†ๆžLinuxๅ†…ๆ ธๆบ็ ](http://www.kerneltravel.net/kernel-book/%E6%B7%B1%E5%85%A5%E5%88%86%E6%9E%90Linux%E5%86%85%E6%A0%B8%E6%BA%90%E7%A0%81.html) :worried: * [UNIX TOOLBOX](http://cb.vu/unixtoolbox_zh_CN.xhtml) * [Dockerไธญๆ–‡ๆŒ‡ๅ—](https://github.com/widuu/chinese_docker) * [Docker โ€”โ€” ไปŽๅ…ฅ้—จๅˆฐๅฎž่ทต](https://github.com/yeasy/docker_practice) * [Dockerๅ…ฅ้—จๅฎžๆˆ˜](http://yuedu.baidu.com/ebook/d817967416fc700abb68fca1) * [Docker Cheat Sheet](https://github.com/wsargent/docker-cheat-sheet/tree/master/zh-cn#docker-cheat-sheet) * [FreeRADIUSๆ–ฐๆ‰‹ๅ…ฅ้—จ](http://freeradius.akagi201.org) :worried: * [Mac ๅผ€ๅ‘้…็ฝฎๆ‰‹ๅ†Œ](https://aaaaaashu.gitbooks.io/mac-dev-setup/content/) * [FreeBSD ไฝฟ็”จๆ‰‹ๅ†Œ](https://www.freebsd.org/doc/zh_CN/books/handbook/index.html) * [Linux ๅ‘ฝไปค่กŒ(ไธญๆ–‡็‰ˆ)](http://billie66.github.io/TLCL/book/) * [Linux ๆž„ๅปบๆŒ‡ๅ—](http://works.jinbuguo.com/lfs/lfs62/index.html) * [Linuxๅทฅๅ…ทๅฟซ้€Ÿๆ•™็จ‹](https://github.com/me115/linuxtools_rst) * [Linux Documentation (ไธญๆ–‡็‰ˆ)](https://www.gitbook.com/book/tinylab/linux-doc/details) * [ๅตŒๅ…ฅๅผ Linux ็Ÿฅ่ฏ†ๅบ“ (eLinux.org ไธญๆ–‡็‰ˆ)](https://www.gitbook.com/book/tinylab/elinux/details) * [็†่งฃLinux่ฟ›็จ‹](https://github.com/tobegit3hub/understand_linux_process) * [ๅ‘ฝไปค่กŒ็š„่‰บๆœฏ](https://github.com/jlevy/the-art-of-command-line/blob/master/README-zh.md) * [SystemTapๆ–ฐๆ‰‹ๆŒ‡ๅ—](https://spacewander.gitbooks.io/systemtapbeginnersguide_zh/content/index.html) * [ๆ“ไฝœ็ณป็ปŸๆ€่€ƒ](https://github.com/wizardforcel/think-os-zh) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๆ™บ่ƒฝ็ณป็ปŸ * [ไธ€ๆญฅๆญฅๆญๅปบ็‰ฉ่”็ฝ‘็ณป็ปŸ](https://github.com/phodal/designiot) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๅˆ†ๅธƒๅผ็ณป็ปŸ * [่ตฐๅ‘ๅˆ†ๅธƒๅผ](http://dcaoyuan.github.io/papers/pdfs/Scalability.pdf) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็ผ–่ฏ‘ๅŽŸ็† * [ใ€Š่ฎก็ฎ—ๆœบ็จ‹ๅบ็š„็ป“ๆž„ๅ’Œ่งฃ้‡Šใ€‹ๅ…ฌๅผ€่ฏพ ็ฟป่ฏ‘้กน็›ฎ](https://github.com/DeathKing/Learning-SICP) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๅ‡ฝๆ•ฐๅผๆฆ‚ๅฟต * [ๅ‚ป็“œๅ‡ฝๆ•ฐ็ผ–็จ‹](https://github.com/justinyhuang/Functional-Programming-For-The-Rest-of-Us-Cn) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ่ฎก็ฎ—ๆœบๅ›พๅฝขๅญฆ * [OpenGL ๆ•™็จ‹](https://github.com/zilongshanren/opengl-tutorials) * [WebGL่‡ชๅญฆ็ฝ‘](http://html5.iii.org.tw/course/webgl/) :worried: * [ใ€ŠReal-Time Rendering 3rdใ€‹ๆ็‚ผๆ€ป็ป“](https://github.com/QianMo/Real-Time-Rendering-3rd-Summary-Ebook) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## WEBๆœๅŠกๅ™จ * [Nginxๅผ€ๅ‘ไปŽๅ…ฅ้—จๅˆฐ็ฒพ้€š](http://tengine.taobao.org/book/index.html) (ๆท˜ๅฎๅ›ข้˜Ÿๅ‡บๅ“) * [Nginxๆ•™็จ‹ไปŽๅ…ฅ้—จๅˆฐ็ฒพ้€š](http://www.ttlsa.com/nginx/nginx-stu-pdf/)(PDF็‰ˆๆœฌ๏ผŒ่ฟ็ปด็”Ÿๅญ˜ๆ—ถ้—ดๅ‡บๅ“) * [OpenRestyๆœ€ไฝณๅฎž่ทต](https://www.gitbook.com/book/moonbingbing/openresty-best-practices/details) * [Apache ไธญๆ–‡ๆ‰‹ๅ†Œ](http://works.jinbuguo.com/apache/menu22/index.html) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็‰ˆๆœฌๆŽงๅˆถ * [Learn Git - complete book in Chinese](https://www.git-tower.com/learn/git/ebook/cn/command-line/) * [Git Cheat Sheet](https://www.git-tower.com/blog/git-cheat-sheet-cn) * [Gitๆ•™็จ‹](http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000) ๏ผˆๆœฌๆ–‡็”ฑ [ๅป–้›ชๅณฐ](http://www.liaoxuefeng.com) ๅˆ›ไฝœ๏ผŒๅฆ‚ๆžœ่ง‰ๅพ—ๆœฌๆ•™็จ‹ๅฏนๆ‚จๆœ‰ๅธฎๅŠฉ๏ผŒๅฏไปฅๅŽป [iTunes](https://itunes.apple.com/cn/app/git-jiao-cheng/id876420437) ่ดญไนฐ๏ผ‰ * [git - ็ฎ€ๆ˜“ๆŒ‡ๅ—](http://rogerdudler.github.io/git-guide/index.zh.html) * [็Œดๅญ้ƒฝ่ƒฝๆ‡‚็š„GITๅ…ฅ้—จ](http://backlogtool.com/git-guide/cn/) * [Git ๅ‚่€ƒๆ‰‹ๅ†Œ](http://gitref.justjavac.com) * [Pro Git](http://git-scm.com/book/zh/v2) * [Pro Git ไธญๆ–‡็‰ˆ](https://www.gitbook.com/book/0532/progit/details) (ๆ•ด็†ๅœจgitbookไธŠ) * [Git Magic](http://www-cs-students.stanford.edu/~blynn/gitmagic/intl/zh_cn/) * [GotGitHub](http://www.worldhello.net/gotgithub/index.html) * [GitๆƒๅจๆŒ‡ๅ—](http://www.worldhello.net/gotgit/) * [Git Community Book ไธญๆ–‡็‰ˆ](http://gitbook.liuhui998.com/index.html) * [Mercurial ไฝฟ็”จๆ•™็จ‹](https://www.mercurial-scm.org/wiki/ChineseTutorial) * [HgInit (ไธญๆ–‡็‰ˆ)](http://bucunzai.net/hginit/) * [ๆฒ‰ๆตธๅผๅญฆ Git](http://igit.linuxtoy.org) * [Git-Cheat-Sheet](https://github.com/flyhigher139/Git-Cheat-Sheet) ๏ผˆๆ„Ÿ่ฐข @flyhigher139 ็ฟป่ฏ‘ไบ†ไธญๆ–‡็‰ˆ๏ผ‰ * [GitHub็ง˜็ฑ](https://snowdream86.gitbooks.io/github-cheat-sheet/content/zh/index.html) * [GitHubๅธฎๅŠฉๆ–‡ๆกฃ](https://github.com/waylau/github-help) * [git-flow ๅค‡ๅฟ˜ๆธ…ๅ•](http://danielkummer.github.io/git-flow-cheatsheet/index.zh_CN.html) * [svn ๆ‰‹ๅ†Œ](http://svnbook.red-bean.com/nightly/zh/index.html) * [GitHubๆผซๆธธๆŒ‡ๅ—](https://github.com/phodal/github-roam) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็ผ–่พ‘ๅ™จ * [exvim--vim ๆ”น่‰ฏๆˆIDE้กน็›ฎ](http://exvim.github.io/docs-zh/intro/) * [็ฌจๆ–นๆณ•ๅญฆVimscript ไธญ่ฏ‘ๆœฌ](http://learnvimscriptthehardway.onefloweroneworld.com/) :worried: * [Vimไธญๆ–‡ๆ–‡ๆกฃ](https://github.com/vimcn/vimcdoc) * [21ๅคฉๅญฆไผšEmacs](http://book.emacs-china.org/) * [ไธ€ๅนดๆˆไธบEmacs้ซ˜ๆ‰‹ (ๅƒ็ฅžไธ€ๆ ทไฝฟ็”จ็ผ–่พ‘ๅ™จ)](https://github.com/redguardtoo/mastering-emacs-in-one-year-guide/blob/master/guide-zh.org) * [ๆ‰€้œ€ๅณๆ‰€่Žท๏ผšๅƒ IDE ไธ€ๆ ทไฝฟ็”จ vim](https://github.com/yangyangwithgnu/use_vim_as_ide) * [vim ๅฎžๆ“ๆ•™็จ‹](https://github.com/dofy/learn-vim) * [Atom้ฃž่กŒๆ‰‹ๅ†Œไธญๆ–‡็‰ˆ](https://github.com/wizardforcel/atom-flight-manual-zh-cn) * [Markdownยท็ฎ€ๅ•็š„ไธ–็•Œ](https://github.com/wizardforcel/markdown-simple-world) * [ไธ€ๅนดๆˆไธบ Emacs ้ซ˜ๆ‰‹](https://github.com/redguardtoo/mastering-emacs-in-one-year-guide/blob/master/guide-zh.org) * [Emacs ็”Ÿๅญ˜ๆŒ‡ๅ—](http://lifegoo.pluskid.org/upload/blog/152/Survive.in.Emacs.pdf) * [Atomๅฎ˜ๆ–นๆ‰‹ๅ†Œ](https://atom-china.org/t/atom/62) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## NoSQL * [NoSQLๆ•ฐๆฎๅบ“็ฌ”่ฐˆ](http://old.sebug.net/paper/databases/nosql/Nosql.html) * [Redis ่ฎพ่ฎกไธŽๅฎž็Žฐ](http://redisbook.com/) * [Redis ๅ‘ฝไปคๅ‚่€ƒ](http://redisdoc.com/) * [ๅธฆๆœ‰่ฏฆ็ป†ๆณจ้‡Š็š„ Redis 3.0 ไปฃ็ ](https://github.com/huangz1990/redis-3.0-annotated) * [ๅธฆๆœ‰่ฏฆ็ป†ๆณจ้‡Š็š„ Redis 2.6 ไปฃ็ ](https://github.com/huangz1990/annotated_redis_source) * [The Little MongoDB Book](https://github.com/justinyhuang/the-little-mongodb-book-cn/blob/master/mongodb.md) * [The Little Redis Book](https://github.com/JasonLai256/the-little-redis-book/blob/master/cn/redis.md) * [Neo4j ็ฎ€ไฝ“ไธญๆ–‡ๆ‰‹ๅ†Œ v1.8](http://docs.neo4j.org.cn/) * [Neo4j .rb ไธญๆ–‡่ณ‡ๆบ](http://neo4j.tw/) * [Disque ไฝฟ็”จๆ•™็จ‹](http://disquebook.com) * [Apache Spark ่ฎพ่ฎกไธŽๅฎž็Žฐ](https://github.com/JerryLead/SparkInternals/tree/master/markdown) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## PostgreSQL * [PostgreSQL 8.2.3 ไธญๆ–‡ๆ–‡ๆกฃ](http://works.jinbuguo.com/postgresql/menu823/index.html) * [PostgreSQL 9.3.1 ไธญๆ–‡ๆ–‡ๆกฃ](http://www.postgres.cn/docs/9.3/index.html) * [PostgreSQL 9.5.3 ไธญๆ–‡ๆ–‡ๆกฃ](http://www.postgres.cn/docs/9.5/index.html) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## MySQL * [MySQL็ดขๅผ•่ƒŒๅŽ็š„ๆ•ฐๆฎ็ป“ๆž„ๅŠ็ฎ—ๆณ•ๅŽŸ็†](http://blog.codinglabs.org/articles/theory-of-mysql-index.html) * [21ๅˆ†้’ŸMySQLๅ…ฅ้—จๆ•™็จ‹](http://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็ฎก็†ๅ’Œ็›‘ๆŽง * [ELKstack ไธญๆ–‡ๆŒ‡ๅ—](http://kibana.logstash.es) * [Mastering Elasticsearch(ไธญๆ–‡็‰ˆ)](http://udn.yyuap.com/doc/mastering-elasticsearch/) * [ElasticSearch ๆƒๅจๆŒ‡ๅ—](https://www.gitbook.com/book/fuxiaopang/learnelasticsearch/details) * [Elasticsearch ๆƒๅจๆŒ‡ๅ—๏ผˆไธญๆ–‡็‰ˆ๏ผ‰](http://es.xiaoleilu.com) * [Logstash ๆœ€ไฝณๅฎž่ทต](https://github.com/chenryn/logstash-best-practice-cn) * [Puppet 2.7 Cookbook ไธญๆ–‡็‰ˆ](http://bbs.konotes.org/workdoc/puppet-27/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ้กน็›ฎ็›ธๅ…ณ * [ๆŒ็ปญ้›†ๆˆ๏ผˆ็ฌฌไบŒ็‰ˆ๏ผ‰](http://article.yeeyan.org/view/2251/94882) (่ฏ‘่จ€็ฝ‘) * [่ฎฉๅผ€ๅ‘่‡ชๅŠจๅŒ–็ณปๅˆ—ไธ“ๆ ](http://www.ibm.com/developerworks/cn/java/j-ap/) * [่ฟฝๆฑ‚ไปฃ็ ่ดจ้‡](http://www.ibm.com/developerworks/cn/java/j-cq/) * [selenium ไธญๆ–‡ๆ–‡ๆกฃ](https://github.com/fool2fish/selenium-doc) * [Selenium Webdriver ็ฎ€ๆ˜“ๆ•™็จ‹](http://it-ebooks.flygon.net/selenium-simple-tutorial/) * [Joel่ฐˆ่ฝฏไปถ](http://local.joelonsoftware.com/wiki/Chinese_\(Simplified\)) * [็ด„่€ณ่ซ‡่ปŸ้ซ”(Joel on Software)](http://local.joelonsoftware.com/wiki/%E9%A6%96%E9%A0%81) * [Gradle 2 ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/Gradle-2-User-Guide) * [Gradle ไธญๆ–‡ไฝฟ็”จๆ–‡ๆกฃ](http://yuedu.baidu.com/ebook/f23af265998fcc22bcd10da2) * [็ผ–็ ่ง„่Œƒ](https://github.com/ecomfe/spec) * [ๅผ€ๆบ่ฝฏไปถๆžถๆž„](http://www.ituring.com.cn/book/1143) * [GNU make ๆŒ‡ๅ—](http://docs.huihoo.com/gnu/linux/gmake.html) * [GNU make ไธญๆ–‡ๆ‰‹ๅ†Œ](http://www.yayu.org/book/gnu_make/) * [The Twelve-Factor App](http://12factor.net/zh_cn/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ่ฎพ่ฎกๆจกๅผ * [ๅ›พ่ฏด่ฎพ่ฎกๆจกๅผ](https://github.com/me115/design_patterns) * [ๅฒไธŠๆœ€ๅ…จ่ฎพ่ฎกๆจกๅผๅฏผๅญฆ็›ฎๅฝ•](http://blog.csdn.net/lovelion/article/details/17517213) * [design pattern ๅŒ…ๆ•™ไธๅŒ…ไผš](https://github.com/AlfredTheBest/Design-Pattern) * [่ฎพ่ฎกๆจกๅผ Java ็‰ˆ](https://quanke.gitbooks.io/design-pattern-java/content/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Web * [ๅ…ณไบŽๆต่งˆๅ™จๅ’Œ็ฝ‘็ปœ็š„ 20 ้กน้กป็Ÿฅ](http://www.20thingsilearned.com/zh-CN/home) * [ๆต่งˆๅ™จๅผ€ๅ‘ๅทฅๅ…ท็š„็ง˜ๅฏ†](http://jinlong.github.io/2013/08/29/devtoolsecrets/) * [Chrome ๅผ€ๅ‘่€…ๅทฅๅ…ทไธญๆ–‡ๆ‰‹ๅ†Œ](https://github.com/CN-Chrome-DevTools/CN-Chrome-DevTools) * [Chromeๆ‰ฉๅฑ•ๅผ€ๅ‘ๆ–‡ๆกฃ](http://open.chrome.360.cn/extension_dev/overview.html) * [Gruntไธญๆ–‡ๆ–‡ๆกฃ](http://www.gruntjs.net/) * [gulpไธญๆ–‡ๆ–‡ๆกฃ](http://www.gulpjs.com.cn/docs/) * [Gulp ๅ…ฅ้—จๆŒ‡ๅ—](https://github.com/nimojs/gulp-book) * [็งปๅŠจWebๅ‰็ซฏ็Ÿฅ่ฏ†ๅบ“](https://github.com/AlloyTeam/Mars) * [ๆญฃๅˆ™่กจ่พพๅผ30ๅˆ†้’Ÿๅ…ฅ้—จๆ•™็จ‹](http://deerchao.net/tutorials/regex/regex.htm) * [ๅ‰็ซฏๅผ€ๅ‘ไฝ“็ณปๅปบ่ฎพๆ—ฅ่ฎฐ](https://github.com/fouber/blog/issues/2) * [็งปๅŠจๅ‰็ซฏๅผ€ๅ‘ๆ”ถ่—ๅคน](https://github.com/hoosin/mobile-web-favorites) * [JSON้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md) * [HTTP ๆŽฅๅฃ่ฎพ่ฎกๆŒ‡ๅŒ—](https://github.com/bolasblack/http-api-guide) * [ๅ‰็ซฏ่ต„ๆบๅˆ†ไบซ๏ผˆไธ€๏ผ‰](https://github.com/hacke2/hacke2.github.io/issues/1) * [ๅ‰็ซฏ่ต„ๆบๅˆ†ไบซ๏ผˆไบŒ๏ผ‰](https://github.com/hacke2/hacke2.github.io/issues/3) * [ๅ‰็ซฏไปฃ็ ่ง„่Œƒ ๅŠ ๆœ€ไฝณๅฎž่ทต](http://coderlmn.github.io/code-standards/) * [ๅ‰็ซฏๅผ€ๅ‘่€…ๆ‰‹ๅ†Œ](https://www.gitbook.com/book/dwqs/frontenddevhandbook/details) * [ๅ‰็ซฏๅทฅ็จ‹ๅธˆๆ‰‹ๅ†Œ](https://www.gitbook.com/book/leohxj/front-end-database/details) * [w3schoolๆ•™็จ‹ๆ•ด็†](https://github.com/wizardforcel/w3school) * [Wireshark็”จๆˆทๆ‰‹ๅ†Œ](http://man.lupaworld.com/content/network/wireshark/index.html) * [ไธ€็ซ™ๅผๅญฆไน Wireshark](https://community.emc.com/thread/194901) * [HTTP ไธ‹ๅˆ่Œถ](https://ccbikai.gitbooks.io/http-book/content/) * [HTTP/2.0 ไธญๆ–‡็ฟป่ฏ‘](http://yuedu.baidu.com/ebook/478d1a62376baf1ffc4fad99?pn=1) * [RFC 7540 - HTTP/2 ไธญๆ–‡็ฟป่ฏ‘็‰ˆ](https://github.com/abbshr/rfc7540-translation-zh_cn) * [http2่ฎฒ่งฃ](https://www.gitbook.com/book/ye11ow/http2-explained/details) * [3 Web Designs in 3 Weeks](https://www.gitbook.com/book/juntao/3-web-designs-in-3-weeks/details) * [็ซ™็‚นๅฏ้ ๆ€งๅทฅ็จ‹](https://github.com/hellorocky/Site-Reliability-Engineering) * [Webๅฎ‰ๅ…จๅญฆไน ็ฌ”่ฎฐ](https://websec.readthedocs.io) * [Serverless ๆžถๆž„ๅบ”็”จๅผ€ๅ‘ๆŒ‡ๅ—](https://github.com/phodal/serverless) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๅคงๆ•ฐๆฎ * [ๅคงๆ•ฐๆฎ/ๆ•ฐๆฎๆŒ–ๆŽ˜/ๆŽจ่็ณป็ปŸ/ๆœบๅ™จๅญฆไน ็›ธๅ…ณ่ต„ๆบ](https://github.com/Flowerowl/Big-Data-Resources) * [้ขๅ‘็จ‹ๅบๅ‘˜็š„ๆ•ฐๆฎๆŒ–ๆŽ˜ๆŒ‡ๅ—](https://github.com/egrcc/guidetodatamining) * [ๅคงๅž‹้›†็พคไธŠ็š„ๅฟซ้€Ÿๅ’Œ้€š็”จๆ•ฐๆฎๅค„็†ๆžถๆž„](https://code.csdn.net/CODE_Translation/spark_matei_phd) * [ๆ•ฐๆฎๆŒ–ๆŽ˜ไธญ็ปๅ…ธ็š„็ฎ—ๆณ•ๅฎž็Žฐๅ’Œ่ฏฆ็ป†็š„ๆณจ้‡Š](https://github.com/linyiqun/DataMiningAlgorithm) * [Spark ็ผ–็จ‹ๆŒ‡ๅ—็ฎ€ไฝ“ไธญๆ–‡็‰ˆ](https://aiyanbo.gitbooks.io/spark-programming-guide-zh-cn/content/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็ผ–็จ‹่‰บๆœฏ * [็จ‹ๅบๅ‘˜็ผ–็จ‹่‰บๆœฏ](https://github.com/julycoding/The-Art-Of-Programming-by-July) * [ๆฏไธช็จ‹ๅบๅ‘˜้ƒฝๅบ”่ฏฅไบ†่งฃ็š„ๅ†…ๅญ˜็Ÿฅ่ฏ†(่ฏ‘)](http://www.oschina.net/translate/what-every-programmer-should-know-about-memory-part1?print)ใ€็ฌฌไธ€้ƒจๅˆ†ใ€‘ * [ๅ–ๆ‚ฆ็š„ๅทฅๅบ๏ผšๅฆ‚ไฝ•็†่งฃๆธธๆˆ](http://read.douban.com/ebook/4972883/) (่ฑ†็“ฃ้˜…่ฏป๏ผŒๅ…่ดนไนฆ็ฑ) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๆธธๆˆๅผ•ๆ“Ž * [ๆธธๆˆๅผ•ๆ“Ž ๆต…ๅ…ฅๆต…ๅ‡บ](https://github.com/ThisisGame/cpp-game-engine-book) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ็ฎ—ๆณ• * [labuladong ็š„็ฎ—ๆณ•ๅฐๆŠ„](https://github.com/labuladong/fucking-algorithm) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ๅ…ถๅฎƒ * [OpenWrtๆ™บ่ƒฝใ€่‡ชๅŠจใ€้€ๆ˜Ž็ฟปๅข™่ทฏ็”ฑๅ™จๆ•™็จ‹](https://www.gitbook.com/book/softwaredownload/openwrt-fanqiang/details) * [SAN ็ฎก็†ๅ…ฅ้—จ็ณปๅˆ—](https://community.emc.com/docs/DOC-16067) * [Sketch ไธญๆ–‡ๆ‰‹ๅ†Œ](http://sketchcn.com/sketch-chinese-user-manual.html#introduce) * [ๆทฑๅ…ฅ็†่งฃๅนถ่กŒ็ผ–็จ‹](http://ifeve.com/perfbook/) * [็จ‹ๅบๅ‘˜็š„่‡ชๆˆ‘ไฟฎๅ…ป](http://www.kancloud.cn/kancloud/a-programmer-prepares) * [Growth: ๅ…จๆ ˆๅขž้•ฟๅทฅ็จ‹ๅธˆๆŒ‡ๅ—](https://github.com/phodal/growth-ebook) * [็ณป็ปŸ้‡ๆž„ไธŽ่ฟ็งปๆŒ‡ๅ—](https://github.com/phodal/migration) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Android * [Android Design(ไธญๆ–‡็‰ˆ)](http://www.apkbus.com/design/index.html) * Google Material Design ๆญฃ้ซ”ไธญๆ–‡็‰ˆ ([่ฏ‘ๆœฌไธ€](https://wcc723.gitbooks.io/google_design_translate/content/style-icons.html) [่ฏ‘ๆœฌไบŒ](https://github.com/1sters/material_design_zh)) * [Material Design ไธญๆ–‡็‰ˆ](http://wiki.jikexueyuan.com/project/material-design/) * [Google Androidๅฎ˜ๆ–นๅŸน่ฎญ่ฏพ็จ‹ไธญๆ–‡็‰ˆ](http://hukai.me/android-training-course-in-chinese/index.html) * [Androidๅญฆไน ไน‹่ทฏ](http://www.stormzhang.com/android/2014/07/07/learn-android-from-rookie/) * [Androidๅผ€ๅ‘ๆŠ€ๆœฏๅ‰็บฟ(android-tech-frontier)](https://github.com/bboyfeiyu/android-tech-frontier) * [Point-of-Android](https://github.com/FX-Max/Point-of-Android) Android ไธ€ไบ›้‡่ฆ็Ÿฅ่ฏ†็‚น่งฃๆžๆ•ด็† * [Android6.0ๆ–ฐ็‰นๆ€ง่ฏฆ่งฃ](http://leanote.com/blog/post/561658f938f41126b2000298) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## APP * [Apache Cordova ๅผ€ๅ‘ๆŒ‡ๅ—](https://github.com/waylau/cordova-dev-guide) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## AWK * [awk็จ‹ๅบ่ฎพ่ฎก่ฏญ่จ€](https://github.com/wuzhouhui/awk) * [awkไธญๆ–‡ๆŒ‡ๅ—](http://awk.readthedocs.org/en/latest/index.html) * [awkๅฎžๆˆ˜ๆŒ‡ๅ—](https://book.saubcy.com/AwkInAction/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## C/C++ * [C/C++ ไธญๆ–‡ๅ‚่€ƒๆ‰‹ๅ†Œ](http://zh.cppreference.com/) (ๆฌข่ฟŽๅคงๅฎถๅ‚ไธŽๅœจ็บฟ็ฟป่ฏ‘ๅ’Œๆ กๅฏน) * [C ่ฏญ่จ€็ผ–็จ‹้€่ง†](https://www.gitbook.com/book/tinylab/cbook/details) * [C++ ๅนถๅ‘็ผ–็จ‹ๆŒ‡ๅ—](https://github.com/forhappy/Cplusplus-Concurrency-In-Practice) * [Linux C็ผ–็จ‹ไธ€็ซ™ๅผๅญฆไน ](http://akaedu.github.io/book/) (ๅฎ‹ๅŠฒๆ‰, ๅŒ—ไบฌไบšๅตŒๆ•™่‚ฒ็ ”็ฉถไธญๅฟƒ) * [CGDBไธญๆ–‡ๆ‰‹ๅ†Œ](https://github.com/leeyiw/cgdb-manual-in-chinese) * [100ไธชgdbๅฐๆŠ€ๅทง](https://github.com/hellogcc/100-gdb-tips/blob/master/src/index.md) * [100ไธชgccๅฐๆŠ€ๅทง](https://github.com/hellogcc/100-gcc-tips/blob/master/src/index.md) * [ZMQ ๆŒ‡ๅ—](https://github.com/anjuke/zguide-cn) * [How to Think Like a Computer Scientist](http://www.ituring.com.cn/book/1203) (ไธญ่‹ฑๆ–‡็‰ˆ) * [่ทŸๆˆ‘ไธ€่ตทๅ†™ Makefile](https://github.com/seisman/how-to-write-makefile) * [GNU makeไธญๆ–‡ๆ‰‹ๅ†Œ](https://free-online-ebooks.appspot.com/tools/gnu-make-cn/) (้œ€็ง‘ๅญฆไธŠ็ฝ‘) ([PDF](https://hacker-yhj.github.io/resources/gun_make.pdf)) * [GNU make ๆŒ‡ๅ—](http://docs.huihoo.com/gnu/linux/gmake.html) * [Google C++ ้ฃŽๆ ผๆŒ‡ๅ—](http://zh-google-styleguide.readthedocs.org/en/latest/google-cpp-styleguide/contents/) * [C/C++ Primer](https://github.com/andycai/cprimer) (by @andycai) * [็ฎ€ๅ•ๆ˜“ๆ‡‚็š„C้ญ”ๆณ•](http://www.nowamagic.net/librarys/books/contents/c) * [C++ FAQ LITE(ไธญๆ–‡็‰ˆ)](http://www.sunistudio.com/cppfaq/) * [C++ Primer 5th Answers](https://github.com/Mooophy/Cpp-Primer) * [C++ ๅนถๅ‘็ผ–็จ‹(ๅŸบไบŽC++11)](https://www.gitbook.com/book/chenxiaowei/cpp_concurrency_in_action/details) * [QT ๆ•™็จ‹](http://www.kuqin.com/qtdocument/tutorial.html) * [DevBean็š„ใ€ŠQtๅญฆไน ไน‹่ทฏ2ใ€‹(Qt5)](http://www.devbean.net/category/qt-study-road-2/) * [ไธญๆ–‡็‰ˆใ€ŠQmlBookใ€‹](https://github.com/cwc1987/QmlBook-In-Chinese) * [C++ Template ่ฟ›้˜ถๆŒ‡ๅ—](https://github.com/wuye9036/CppTemplateTutorial) * [libuvไธญๆ–‡ๆ•™็จ‹](https://github.com/luohaha/Chinese-uvbook) * [Boost ๅบ“ไธญๆ–‡ๆ•™็จ‹](http://zh.highscore.de/cpp/boost/) * [็ฌจๅŠžๆณ•ๅญฆC](https://github.com/wizardforcel/lcthw-zh) * [้ซ˜้€ŸไธŠๆ‰‹ C++11/14/17](https://github.com/changkun/modern-cpp-tutorial) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## C&#35; * [Microsoft Docs C# ๅฎ˜ๆ–นๆ–‡ๆกฃ](https://docs.microsoft.com/zh-cn/dotnet/csharp/) * [ASP.NET MVC 5 ๅ…ฅ้—จๆŒ‡ๅ—](http://www.cnblogs.com/powertoolsteam/p/aspnetmvc5-tutorials-grapecity.html) * [่ถ…ๅ…จ้ข็š„ .NET GDI+ ๅ›พๅฝขๅ›พๅƒ็ผ–็จ‹ๆ•™็จ‹](http://www.cnblogs.com/geeksss/p/4162318.html) * [.NETๆŽงไปถๅผ€ๅ‘ๅŸบ็ก€](https://github.com/JackWangCUMT/customcontrol) * [.NETๅผ€ๅ‘่ฆ็‚น็ฒพ่ฎฒ๏ผˆๅˆ็จฟ๏ผ‰](https://github.com/sherlockchou86/-free-ebook-.NET-) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Clojure * [Clojureๅ…ฅ้—จๆ•™็จ‹](https://wizardforcel.gitbooks.io/clojure-fpftj/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) <h2 id="csshtml">CSS/HTML</h2> * [ๅญฆไน CSSๅธƒๅฑ€](http://zh.learnlayout.com/) * [้€š็”จ CSS ็ฌ”่ฎฐใ€ๅปบ่ฎฎไธŽๆŒ‡ๅฏผ](https://github.com/chadluo/CSS-Guidelines/blob/master/README.md) * [CSSๅ‚่€ƒๆ‰‹ๅ†Œ](http://css.doyoe.com/) * [Emmet ๆ–‡ๆกฃ](http://yanxyz.github.io/emmet-docs/) * [ๅ‰็ซฏไปฃ็ ่ง„่Œƒ](http://alloyteam.github.io/CodeGuide/) (่…พ่ฎฏ AlloyTeam ๅ›ข้˜Ÿ) * [HTMLๅ’ŒCSS็ผ–็ ่ง„่Œƒ](http://codeguide.bootcss.com/) * [Sass Guidelines ไธญๆ–‡](http://sass-guidelin.es/zh/) * [CSS3 Tutorial ใ€ŠCSS3 ๆ•™็จ‹ใ€‹](https://github.com/waylau/css3-tutorial) * [MDN HTML ไธญๆ–‡ๆ–‡ๆกฃ](https://developer.mozilla.org/zh-CN/docs/Web/HTML) * [MDN CSS ไธญๆ–‡ๆ–‡ๆกฃ](https://developer.mozilla.org/zh-CN/docs/Web/CSS) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Dart * [Dart ่ฏญ่จ€ๅฏผ่งˆ](http://dart.lidian.info/wiki/Language_Tour) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Elixir * [Elixir็ผ–็จ‹ๅ…ฅ้—จ](https://github.com/straightdave/programming_elixir) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Erlang * [21ๅคฉๅญฆ้€šErlang](http://xn--21erlang-p00o82pmp3o.github.io/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Fortran * [Fortran77ๅ’Œ90/95็ผ–็จ‹ๅ…ฅ้—จ](http://micro.ustc.edu.cn/Fortran/ZJDing/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Go * [Go็ผ–็จ‹ๅŸบ็ก€](https://github.com/Unknwon/go-fundamental-programming) * [Goๅ…ฅ้—จๆŒ‡ๅ—](https://github.com/Unknwon/the-way-to-go_ZH_CN) * [ๅญฆไน Go่ฏญ่จ€](http://mikespook.com/learning-go/) * [Go Web ็ผ–็จ‹](https://github.com/astaxie/build-web-application-with-golang) (ๆญคไนฆๅทฒ็ปๅ‡บ็‰ˆ๏ผŒๅธŒๆœ›ๅผ€ๅ‘่€…ไปฌๅŽป่ดญไนฐ๏ผŒๆ”ฏๆŒไฝœ่€…็š„ๅˆ›ไฝœ) * [Goๅฎžๆˆ˜ๅผ€ๅ‘](https://github.com/astaxie/Go-in-Action) (ๅฝ“ๆˆ‘ๆ”ถๅฝ•ๆญค้กน็›ฎๆ—ถ๏ผŒไฝœ่€…ๅทฒ็ปๅ†™ๅฎŒ็ฌฌไธ‰็ซ ๏ผŒๅฆ‚ๆžœ่ฏปๅฎŒๅ‰้ข็ซ ่Š‚่ง‰ๅพ—ๆœ‰ๅธฎๅŠฉ๏ผŒๅฏไปฅ็ป™ไฝœ่€…[ๆ่ต ](https://me.alipay.com/astaxie)๏ผŒไปฅ้ผ“ๅŠฑไฝœ่€…็š„็ปง็ปญๅˆ›ไฝœ) * [Network programming with Go ไธญๆ–‡็ฟป่ฏ‘็‰ˆๆœฌ](https://github.com/astaxie/NPWG_zh) * [Effective Go](http://www.hellogcc.org/effective_go.html) * [Go ่ฏญ่จ€ๆ ‡ๅ‡†ๅบ“](https://github.com/polaris1119/The-Golang-Standard-Library-by-Example) * [Golangๆ ‡ๅ‡†ๅบ“ๆ–‡ๆกฃ](http://godoc.ml/) * [Revel ๆก†ๆžถๆ‰‹ๅ†Œ](http://gorevel.cn/docs/manual/index.html) * [Java็จ‹ๅบๅ‘˜็š„Golangๅ…ฅ้—จๆŒ‡ๅ—](http://blog.csdn.net/dc_726/article/details/46565241) * [Goๅ‘ฝไปคๆ•™็จ‹](https://github.com/hyper-carrot/go_command_tutorial) * [Go่ฏญ่จ€ๅšๅฎขๅฎž่ทต](https://github.com/achun/Go-Blog-In-Action) * [Go ๅฎ˜ๆ–นๆ–‡ๆกฃ็ฟป่ฏ‘](https://github.com/golang-china/golangdoc.translations) * [ๆทฑๅ…ฅ่งฃๆžGo](https://github.com/tiancaiamao/go-internals) * [Go่ฏญ่จ€ๅœฃ็ป(ไธญๆ–‡็‰ˆ)](https://bitbucket.org/golang-china/gopl-zh/wiki/Home) ([GitBook](https://www.gitbook.com/book/wizardforcel/gopl-zh/details)) * [golang runtimeๆบ็ ๅˆ†ๆž](https://github.com/sheepbao/golang_runtime_reading) * [Go่ฏญ่จ€ๅฎžๆˆ˜: ็ผ–ๅ†™ๅฏ็ปดๆŠคGo่ฏญ่จ€ไปฃ็ ๅปบ่ฎฎ](https://github.com/llitfkitfk/go-best-practice) * [Golang ็ณปๅˆ—ๆ•™็จ‹(่ฏ‘)](https://github.com/Tinywan/golang-tutorial) * [Go RPC ๅผ€ๅ‘ๆŒ‡ๅ—](https://github.com/smallnest/go-rpc-programming-guide)[GitBook](https://smallnest.gitbooks.io/go-rpc-programming-guide/) * [Go่ฏญ่จ€้ซ˜็บง็ผ–็จ‹](https://books.studygolang.com/advanced-go-programming-book/) * [Go2็ผ–็จ‹ๆŒ‡ๅ—](https://chai2010.cn/go2-book/) * [Go่ฏญ่จ€่ฎพ่ฎกๆจกๅผ](https://github.com/senghoo/golang-design-pattern) * [Go่ฏญ่จ€ๅ››ๅไบŒ็ซ ็ป](https://github.com/ffhelicopter/Go42) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Groovy * [ๅฎžๆˆ˜ Groovy ็ณปๅˆ—](http://www.ibm.com/developerworks/cn/java/j-pg/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Haskell * [Real World Haskell ไธญๆ–‡็‰ˆ](http://rwh.readthedocs.org/en/latest/) * [Haskell่ถฃๅญฆๆŒ‡ๅ—](https://learnyoua.haskell.sg/content/zh-cn/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## iOS * [iOSๅผ€ๅ‘60ๅˆ†้’Ÿๅ…ฅ้—จ](https://github.com/qinjx/30min_guides/blob/master/ios.md) * [iOS7ไบบๆœบ็•Œ้ขๆŒ‡ๅ—](http://isux.tencent.com/ios-human-interface-guidelines-ui-design-basics-ios7.html) * [Google Objective-C Style Guide ไธญๆ–‡็‰ˆ](http://zh-google-styleguide.readthedocs.org/en/latest/google-objc-styleguide/) * [iPhone 6 ๅฑๅน•ๆญ็ง˜](http://wileam.com/iphone-6-screen-cn/) * [Apple Watchๅผ€ๅ‘ๅˆๆŽข](http://nilsun.github.io/apple-watch/) * [้ฉฌไธŠ็€ๆ‰‹ๅผ€ๅ‘ iOS ๅบ”็”จ็จ‹ๅบ](https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOSCh/index.html) * [็ฝ‘ๆ˜“ๆ–ฏๅฆ็ฆๅคงๅญฆๅ…ฌๅผ€่ฏพ๏ผšiOS 7ๅบ”็”จๅผ€ๅ‘ๅญ—ๅน•ๆ–‡ไปถ](https://github.com/jkyin/Subtitle) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Java * [Apache Shiro ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/apache-shiro-1.2.x-reference) * [Jersey 2.x ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/Jersey-2.x-User-Guide) * [Spring Framework 4.xๅ‚่€ƒๆ–‡ๆกฃ](https://github.com/waylau/spring-framework-4-reference) * [Spring Bootๅ‚่€ƒๆŒ‡ๅ—](https://github.com/qibaoguang/Spring-Boot-Reference-Guide) (็ฟป่ฏ‘ไธญ) * [MyBatisไธญๆ–‡ๆ–‡ๆกฃ](http://mybatis.org/mybatis-3/zh/index.html) * [MyBatis Generator ไธญๆ–‡ๆ–‡ๆกฃ](http://mbg.cndocs.tk/) * [็”จjerseyๆž„ๅปบRESTๆœๅŠก](https://github.com/waylau/RestDemo) * [Activiti 5.x ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/activiti-5.x-user-guide) * [Google Java็ผ–็จ‹้ฃŽๆ ผๆŒ‡ๅ—](https://hawstein.com/2014/01/20/google-java-style/) * [Netty 4.x ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/netty-4-user-guide) * [Netty ๅฎžๆˆ˜(็ฒพ้ซ“)](https://github.com/waylau/essential-netty-in-action) * [REST ๅฎžๆˆ˜](https://github.com/waylau/rest-in-action) * [Java ็ผ–็ ่ง„่Œƒ](https://github.com/waylau/java-code-conventions) * [Apache MINA 2 ็”จๆˆทๆŒ‡ๅ—](https://github.com/waylau/apache-mina-2.x-user-guide) * [H2 Database ๆ•™็จ‹](https://github.com/waylau/h2-database-doc) * [Java Servlet 3.1 ่ง„่Œƒ](https://github.com/waylau/servlet-3.1-specification) * [JSSE ๅ‚่€ƒๆŒ‡ๅ—](https://github.com/waylau/jsse-reference-guide) * [Javaๅผ€ๆบๅฎž็ŽฐๅŠๆœ€ไฝณๅฎž่ทต](https://github.com/biezhi/jb) * [Java ็ผ–็จ‹่ฆ็‚น](https://github.com/waylau/essential-java) * [Think Java](http://www.ituring.com.cn/minibook/69) * [Java 8 ็ฎ€ๆ˜Žๆ•™็จ‹](https://github.com/wizardforcel/modern-java-zh) * [On Java 8 ไธญๆ–‡็‰ˆ](https://github.com/LingCoder/OnJava8) (็ฟป่ฏ‘ไธญ) * [Effective Java ็ฌฌ3็‰ˆไธญๆ–‡็‰ˆ](https://github.com/sjsdfg/effective-java-3rd-chinese) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## JavaScript * [็Žฐไปฃ Javascript ๆ•™็จ‹](https://zh.javascript.info/) * [Google JavaScript ไปฃ็ ้ฃŽๆ ผๆŒ‡ๅ—](http://bq69.com/blog/articles/script/868/google-javascript-style-guide.html) * [Google JSON ้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/darcyliu/google-styleguide/blob/master/JSONStyleGuide.md) * [Airbnb JavaScript ่ง„่Œƒ](https://github.com/adamlu/javascript-style-guide) * [JavaScript ๆ ‡ๅ‡†ๅ‚่€ƒๆ•™็จ‹๏ผˆalpha๏ผ‰](http://javascript.ruanyifeng.com/) * [Javascript็ผ–็จ‹ๆŒ‡ๅ—](http://pij.robinqu.me/) ([ๆบ็ ](https://github.com/RobinQu/Programing-In-Javascript)) * [javascript ็š„ 12 ไธชๆ€ช็™–](https://github.com/justjavac/12-javascript-quirks) * [JavaScript ็ง˜ๅฏ†่Šฑๅ›ญ](http://bonsaiden.github.io/JavaScript-Garden/zh/) * [JavaScriptๆ ธๅฟƒๆฆ‚ๅฟตๅŠๅฎž่ทต](http://icodeit.org/jsccp/) (PDF) (ๆญคไนฆๅทฒ็”ฑไบบๆฐ‘้‚ฎ็”ตๅ‡บ็‰ˆ็คพๅ‡บ็‰ˆๅ‘่กŒ๏ผŒไฝ†ไฝœ่€…ไพ็„ถๅ…่ดนๆไพ›PDF็‰ˆๆœฌ๏ผŒๅธŒๆœ›ๅผ€ๅ‘่€…ไปฌๅŽป่ดญไนฐ๏ผŒๆ”ฏๆŒไฝœ่€…) * [ใ€ŠJavaScript ๆจกๅผใ€‹](https://github.com/jayli/javascript-patterns) โ€œJavaScript patternsโ€ไธญ่ฏ‘ๆœฌ * [JavaScript่ฏญ่จ€็ฒพ็ฒน](https://github.com/qibaoguang/Study-Step-by-Step/blob/master/%E8%AF%BB%E4%B9%A6%E7%AC%94%E8%AE%B0/javascript_the_good_parts.md) * [ๅ‘ฝๅๅ‡ฝๆ•ฐ่กจ่พพๅผๆŽข็ง˜](http://justjavac.com/named-function-expressions-demystified.html) (ๆณจ:ๅŽŸๆ–‡็”ฑ[ไธบไน‹ๆผซ็ฌ”](http://www.cn-cuckoo.com)็ฟป่ฏ‘๏ผŒๅŽŸๅง‹ๅœฐๅ€ๆ— ๆณ•ๆ‰“ๅผ€๏ผŒๆ‰€ไปฅๆญคๅค„ๅœฐๅ€ไธบๆˆ‘ๅšๅฎขไธŠ็š„ๅค‡ไปฝ) * [ๅญฆ็”จ JavaScript ่ฎพ่ฎกๆจกๅผ](http://www.oschina.net/translate/learning-javascript-design-patterns) (ๅผ€ๆบไธญๅ›ฝ) * [ๆทฑๅ…ฅ็†่งฃJavaScript็ณปๅˆ—](http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html) * [ECMAScript 5.1 ไธญๆ–‡็‰ˆ](http://yanhaijing.com/es5) * [ECMAScript 6 ๅ…ฅ้—จ](http://es6.ruanyifeng.com/) (ไฝœ่€…๏ผš้˜ฎไธ€ๅณฐ) * [JavaScript Promise่ฟทไฝ ไนฆ](http://liubin.github.io/promises-book/) * [You-Dont-Know-JS](https://github.com/getify/You-Dont-Know-JS) (ๆทฑๅ…ฅJavaScript่ฏญ่จ€ๆ ธๅฟƒๆœบๅˆถ็š„็ณปๅˆ—ๅ›พไนฆ) * [JavaScript ๆ•™็จ‹](http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000) ๅป–้›ชๅณฐ * [MDN JavaScript ไธญๆ–‡ๆ–‡ๆกฃ](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript) * jQuery * [jQuery ่งฃๆž„](http://www.cn-cuckoo.com/deconstructed/jquery.html) * [็ฎ€ๅ•ๆ˜“ๆ‡‚็š„JQuery้ญ”ๆณ•](http://www.nowamagic.net/librarys/books/contents/jquery) * [How to write jQuery plugin](http://i5ting.github.io/How-to-write-jQuery-plugin/build/jquery.plugin.html) * [You Don't Need jQuery](https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README.zh-CN.md) * [ๅฆ‚ไฝ•ๅฎž็Žฐไธ€ไธช็ฑปjQuery๏ผŸ](https://github.com/MeCKodo/forchange) * Node.js * [Nodeๅ…ฅ้—จ](http://www.nodebeginner.org/index-zh-cn.html) * [ไธƒๅคฉๅญฆไผšNodeJS](http://nqdeng.github.io/7-days-nodejs/) * [Nodejs Wiki Book](https://github.com/nodejs-tw/nodejs-wiki-book) (็นไฝ“ไธญๆ–‡) * [express.js ไธญๆ–‡ๆ–‡ๆกฃ](http://expressjs.jser.us/) * [koa ไธญๆ–‡ๆ–‡ๆกฃ](https://github.com/guo-yu/koa-guide) * [ไธ€่ตทๅญฆkoa](http://base-n.github.io/koa-generator-examples/) * [ไฝฟ็”จ Express + MongoDB ๆญๅปบๅคšไบบๅšๅฎข](https://github.com/nswbmw/N-blog) * [Expressๆก†ๆžถ](http://javascript.ruanyifeng.com/nodejs/express.html) * [Node.js ๅŒ…ๆ•™ไธๅŒ…ไผš](https://github.com/alsotang/node-lessons) * [Learn You The Node.js For Much Win! (ไธญๆ–‡็‰ˆ)](https://www.npmjs.com/package/learnyounode-zh-cn) * [Node debug ไธ‰ๆณ•ไธ‰ไพ‹](http://i5ting.github.io/node-debug-tutorial/) * [nodejsไธญๆ–‡ๆ–‡ๆกฃ](https://www.gitbook.com/book/0532/nodejs/details) * [orm2 ไธญๆ–‡ๆ–‡ๆกฃ](https://github.com/wizardforcel/orm2-doc-zh-cn) * [ไธ€่ตทๅญฆ Node.js](https://github.com/nswbmw/N-blog) * [Nodeๅ…ฅ้—จ๏ผšไธ€ๆœฌๅ…จ้ข็š„Node.jsๆ•™็จ‹](https://www.nodebeginner.org/index-zh-cn.html) * [ไปŽ้›ถๅผ€ๅง‹็š„Nodejs็ณปๅˆ—ๆ–‡็ซ ](http://blog.fens.me/series-nodejs/) * underscore.js * [Underscore.jsไธญๆ–‡ๆ–‡ๆกฃ](http://learningcn.com/underscore/) * backbone.js * [backbone.jsไธญๆ–‡ๆ–‡ๆกฃ](http://www.css88.com/doc/backbone/) * [backbone.jsๅ…ฅ้—จๆ•™็จ‹](http://www.the5fire.com/backbone-js-tutorials-pdf-download.html) (PDF) * [Backbone.jsๅ…ฅ้—จๆ•™็จ‹็ฌฌไบŒ็‰ˆ](https://github.com/the5fire/backbonejs-learning-note) * [Developing Backbone.js Applications(ไธญๆ–‡็‰ˆ)](http://feliving.github.io/developing-backbone-applications/) * AngularJS * [AngularJSๆœ€ไฝณๅฎž่ทตๅ’Œ้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/mgechev/angularjs-style-guide/blob/master/README-zh-cn.md) * [AngularJSไธญ่ฏ‘ๆœฌ](https://github.com/peiransun/angularjs-cn) * [AngularJSๅ…ฅ้—จๆ•™็จ‹](https://github.com/zensh/AngularjsTutorial_cn) * [ๆž„ๅปบ่‡ชๅทฑ็š„AngularJS](https://github.com/xufei/Make-Your-Own-AngularJS/blob/master/01.md) * [ๅœจWindows็Žฏๅขƒไธ‹็”จYeomanๆž„ๅปบAngularJS้กน็›ฎ](http://www.waylau.com/build-angularjs-app-with-yeoman-in-windows/) * Zepto.js * [Zepto.js ไธญๆ–‡ๆ–‡ๆกฃ](http://mweb.baidu.com/zeptoapi/) * Sea.js * [Hello Sea.js](http://island205.github.io/HelloSea.js/) * React.js * [React ๅญฆไน ไน‹้“](https://github.com/the-road-to-learn-react/the-road-to-learn-react-chinese) * [React.js ๅฐไนฆ](https://github.com/huzidaha/react-naive-book) * [React.js ไธญๆ–‡ๆ–‡ๆกฃ](https://doc.react-china.org/) * [React webpack-cookbook](https://github.com/fakefish/react-webpack-cookbook) * [React ๅ…ฅ้—จๆ•™็จ‹](http://fraserxu.me/intro-to-react/) * [React ๅ…ฅ้—จๆ•™็จ‹](https://hulufei.gitbooks.io/react-tutorial/content/) (ไฝœ่€…๏ผšhulufei, ไธŽไธŠ่กŒไธๅŒไฝœ่€…) * [React Native ไธญๆ–‡ๆ–‡ๆกฃ(ๅซๆœ€ๆ–ฐAndroidๅ†…ๅฎน)](http://wiki.jikexueyuan.com/project/react-native/) * [Learn React & Webpack by building the Hacker News front page](https://github.com/theJian/build-a-hn-front-page) * impress.js * [impress.js็š„ไธญๆ–‡ๆ•™็จ‹](https://github.com/kokdemo/impress.js-tutorial-in-Chinese) * CoffeeScript * [CoffeeScript Cookbook](http://island205.com/coffeescript-cookbook.github.com/) * [The Little Book on CoffeeScriptไธญๆ–‡็‰ˆ](http://island205.com/tlboc/) * [CoffeeScript ็ผ–็ ้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/geekplux/coffeescript-style-guide) * TypeScipt * [TypeScript Handbook](https://zhongsp.gitbooks.io/typescript-handbook/content/) * ExtJS * [Ext4.1.0 ไธญๆ–‡ๆ–‡ๆกฃ](http://extjs-doc-cn.github.io/ext4api/) * Meteor * [Discover Meteor](http://zh.discovermeteor.com/) * [Meteor ไธญๆ–‡ๆ–‡ๆกฃ](http://docs.meteorhub.org/#/basic/) * [Angular-Meteor ไธญๆ–‡ๆ•™็จ‹](http://angular.meteorhub.org/) * VueJS * [้€่กŒๅ‰–ๆž Vue.js ๆบ็ ](https://nlrx-wjc.github.io/Learn-Vue-Source-Code/) * [Chromeๆ‰ฉๅฑ•ๅŠๅบ”็”จๅผ€ๅ‘](http://www.ituring.com.cn/minibook/950) ## Kotlin * [Kotlin ๅฎ˜ๆ–นๅ‚่€ƒๆ–‡ๆกฃ ไธญๆ–‡็‰ˆ](https://hltj.gitbooks.io/kotlin-reference-chinese/content/) * [Kotlin ไธญๆ–‡ๆ–‡ๆกฃ](https://huanglizhuo.gitbooks.io/kotlin-in-chinese/) [GitHub](https://github.com/huanglizhuo/kotlin-in-chinese) * [Kotlin ๅ‚่€ƒๆ–‡ๆกฃ](http://www.liying-cn.net/kotlin/docs/reference/) * [ใ€ŠKotlin for android developersใ€‹ไธญๆ–‡็‰ˆ](https://wangjiegulu.gitbooks.io/kotlin-for-android-developers-zh/content/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## LaTeX * [ไธ€ไปฝๅ…ถๅฎžๅพˆ็Ÿญ็š„ LaTeX ๅ…ฅ้—จๆ–‡ๆกฃ](http://liam0205.me/2014/09/08/latex-introduction/) * [ไธ€ไปฝไธๅคช็ฎ€็Ÿญ็š„ LATEX 2ฮต ไป‹็ป](http://www.mohu.org/info/lshort-cn.pdf) ๏ผˆPDF็‰ˆ๏ผ‰ [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## LISP * Common Lisp * [ANSI Common Lisp ไธญๆ–‡็ฟป่ญฏ็‰ˆ](http://acl.readthedocs.org/en/latest/) * [On Lisp ไธญๆ–‡็ฟป่ฏ‘็‰ˆๆœฌ](http://www.ituring.com.cn/minibook/862) * Scheme * [Yet Another Scheme Tutorial Schemeๅ…ฅ้—จๆ•™็จ‹](http://deathking.github.io/yast-cn/) * [Scheme่ฏญ่จ€็ฎ€ๆ˜Žๆ•™็จ‹](http://songjinghe.github.io/TYS-zh-translation/) * Racket * [Racket book](https://github.com/tyrchen/racket-book) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Lua * [Lua็ผ–็จ‹ๅ…ฅ้—จ](https://github.com/andycai/luaprimer) * [Lua 5.1 ๅ‚่€ƒๆ‰‹ๅ†Œ ไธญๆ–‡็ฟป่ฏ‘](http://www.codingnow.com/2000/download/lua_manual.html) * [Lua 5.3 ๅ‚่€ƒๆ‰‹ๅ†Œ ไธญๆ–‡็ฟป่ฏ‘](http://cloudwu.github.io/lua53doc/) * [Luaๆบ็ ๆฌฃ่ต](http://www.codingnow.com/temp/readinglua.pdf) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## OCaml * [Real World OCaml](https://github.com/zforget/translation/tree/master/real_world_ocaml) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Perl * [Modern Perl ไธญๆ–‡็‰ˆ](https://github.com/horus/modern_perl_book) * [Perl ็จ‹ๅบๅ‘˜ๅบ”่ฏฅ็Ÿฅ้“็š„ไบ‹](http://perl.linuxtoy.org/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## PHP * [PHP ๅฎ˜ๆ–นๆ‰‹ๅ†Œ](http://php.net/manual/zh/) * [PHP่ฐƒ่ฏ•ๆŠ€ๆœฏๆ‰‹ๅ†Œ](http://www.laruence.com/2010/06/21/1608.html)(PDF) * PHPไน‹้“๏ผšphp-the-right-way ([@wulijun็‰ˆ](http://wulijun.github.io/php-the-right-way/) [PHPHub็‰ˆ](http://laravel-china.github.io/php-the-right-way/)) * [PHP ๆœ€ไฝณๅฎž่ทต](https://github.com/justjavac/PHP-Best-Practices-zh_CN) * [PHP ๅผ€ๅ‘่€…ๅฎž่ทต](https://ryancao.gitbooks.io/php-developer-prepares/content/) * [ๆทฑๅ…ฅ็†่งฃPHPๅ†…ๆ ธ](https://github.com/reeze/tipi) * [PHPๆ‰ฉๅฑ•ๅผ€ๅ‘ๅŠๅ†…ๆ ธๅบ”็”จ](http://www.walu.cc/phpbook/) * [Laravel5.1 ไธญๆ–‡ๆ–‡ๆกฃ](http://laravel-china.org/docs/5.1) * [Laravel 5.1 LTS ้€ŸๆŸฅ่กจ](https://cs.phphub.org/) * [Symfony2 Cookbook ไธญๆ–‡็‰ˆ](http://wiki.jikexueyuan.com/project/symfony-cookbook/)(็‰ˆๆœฌ 2.7.0 LTS) * [Symfony2ไธญๆ–‡ๆ–‡ๆกฃ](http://symfony-docs-chs.readthedocs.org/en/latest/) (ๆœช่ฏ‘ๅฎŒ) * [YiiBookๅ‡ ๆœฌYiiๆก†ๆžถ็š„ๅœจ็บฟๆ•™็จ‹](http://yiibook.com//doc) * [ๆทฑๅ…ฅ็†่งฃ Yii 2.0](http://www.digpage.com/) * [Yii ๆก†ๆžถไธญๆ–‡ๅฎ˜็ฝ‘](http://www.yiichina.com/) * [็ฎ€ๅ•ๆ˜“ๆ‡‚็š„PHP้ญ”ๆณ•](http://www.nowamagic.net/librarys/books/contents/php) * [swooleๆ–‡ๆกฃๅŠๅ…ฅ้—จๆ•™็จ‹](https://github.com/LinkedDestiny/swoole-doc) * [Composer ไธญๆ–‡็ฝ‘](http://www.phpcomposer.com) * [Slim ไธญๆ–‡ๆ–‡ๆกฃ](http://ww1.minimee.org/php/slim) * [Lumen ไธญๆ–‡ๆ–‡ๆกฃ](http://lumen.laravel-china.org/) * [PHPUnit ไธญๆ–‡ๆ–‡ๆกฃ](https://phpunit.de/manual/current/zh_cn/installation.html) * [PHP-LeetCode](https://github.com/wuqinqiang/leetcode-php) * [ThinkPHP5.1ๅฎŒๅ…จๅผ€ๅ‘ๆ‰‹ๅ†Œ](https://www.kancloud.cn/manual/thinkphp5_1) * [ThinkPHP3.2.3ๅฎŒๅ…จๅผ€ๅ‘ๆ‰‹ๅ†Œ](https://www.kancloud.cn/manual/thinkphp) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Prolog * [็ฌจๅŠžๆณ•ๅญฆProlog](http://fengdidi.github.io/blog/2011/11/15/qian-yan/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Python * [ๅป–้›ชๅณฐ Python 2.7 ไธญๆ–‡ๆ•™็จ‹](http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000) * [ๅป–้›ชๅณฐ Python 3 ไธญๆ–‡ๆ•™็จ‹](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000) * [็ฎ€ๆ˜ŽPythonๆ•™็จ‹](http://www.kuqin.com/abyteofpython_cn/) * [็ฎ€ๆ˜Ž Python ๆ•™็จ‹(Python 3)](https://legacy.gitbook.com/book/lenkimo/byte-of-python-chinese-edition/details) * [้›ถๅŸบ็ก€ๅญฆ Python ็ฌฌไธ€็‰ˆ](http://www.kancloud.cn/kancloud/python-basic) * [้›ถๅŸบ็ก€ๅญฆ Python ็ฌฌไบŒ็‰ˆ](http://www.kancloud.cn/kancloud/starter-learning-python) * [ๅฏ็ˆฑ็š„ Python](http://lovelypython.readthedocs.org/en/latest/) * [Python 2.7 ๅฎ˜ๆ–นๆ•™็จ‹ไธญๆ–‡็‰ˆ](http://www.pythondoc.com/pythontutorial27/index.html) * [Python 3.3 ๅฎ˜ๆ–นๆ•™็จ‹ไธญๆ–‡็‰ˆ](http://www.pythondoc.com/pythontutorial3/index.html) * [Python Cookbook ไธญๆ–‡็‰ˆ](http://www.kancloud.cn/thinkphp/python-cookbook) * [Python3 Cookbook ไธญๆ–‡็‰ˆ](https://github.com/yidao620c/python3-cookbook) * [ๆทฑๅ…ฅ Python](http://www.kuqin.com/docs/diveintopythonzh-cn-5.4b/html/toc/) * [ๆทฑๅ…ฅ Python 3](http://old.sebug.net/paper/books/dive-into-python3/) * [PEP8 Pythonไปฃ็ ้ฃŽๆ ผ่ง„่Œƒ](https://code.google.com/p/zhong-wiki/wiki/PEP8) * [Google Python ้ฃŽๆ ผๆŒ‡ๅ— ไธญๆ–‡็‰ˆ](http://zh-google-styleguide.readthedocs.org/en/latest/google-python-styleguide/) * [Pythonๅ…ฅ้—จๆ•™็จ‹](http://liam0205.me/2013/11/02/Python-tutorial-zh_cn/) ([PDF](http://liam0205.me/attachment/Python/The_Python_Tutorial_zh-cn.pdf)) * [็ฌจๅŠžๆณ•ๅญฆ Python](http://old.sebug.net/paper/books/LearnPythonTheHardWay/) ([PDF](http://liam0205.me/attachment/Python/PyHardWay/Learn_Python_The_Hard_Way_zh-cn.pdf) [EPUB](https://www.gitbook.com/download/epub/book/wizardforcel/lpthw)) * [Python่‡ช็„ถ่ฏญ่จ€ๅค„็†ไธญๆ–‡็‰ˆ](http://pan.baidu.com/s/1qW4pvnY) ๏ผˆๆ„Ÿ่ฐข้™ˆๆถ›ๅŒๅญฆ็š„็ฟป่ฏ‘๏ผŒไนŸ่ฐข่ฐข [@shwley](https://github.com/shwley) ่”็ณปไบ†ไฝœ่€…๏ผ‰ * [Python ็ป˜ๅ›พๅบ“ matplotlib ๅฎ˜ๆ–นๆŒ‡ๅ—ไธญๆ–‡็ฟป่ฏ‘](http://liam0205.me/2014/09/11/matplotlib-tutorial-zh-cn/) * [Scrapy 0.25 ๆ–‡ๆกฃ](http://scrapy-chs.readthedocs.org/zh_CN/latest/) * [ThinkPython](https://github.com/carfly/thinkpython-cn) * [ThinkPython 2ed](https://github.com/bingjin/ThinkPython2-CN) * [Pythonๅฟซ้€Ÿๆ•™็จ‹](http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html) * [Python ๆญฃๅˆ™่กจ่พพๅผๆ“ไฝœๆŒ‡ๅ—](http://wiki.ubuntu.org.cn/Pythonๆญฃๅˆ™่กจ่พพๅผๆ“ไฝœๆŒ‡ๅ—) * [pythonๅˆ็บงๆ•™็จ‹๏ผšๅ…ฅ้—จ่ฏฆ่งฃ](http://www.crifan.com/files/doc/docbook/python_beginner_tutorial/release/html/python_beginner_tutorial.html) * [Twisted ไธŽๅผ‚ๆญฅ็ผ–็จ‹ๅ…ฅ้—จ](https://www.gitbook.com/book/likebeta/twisted-intro-cn/details) * [TextGrocery ไธญๆ–‡ API](http://textgrocery.readthedocs.org/zh/latest/index.html) ( ๅŸบไบŽsvm็ฎ—ๆณ•็š„ไธ€ไธช็Ÿญๆ–‡ๆœฌๅˆ†็ฑป Python ๅบ“ ) * [Requests: HTTP for Humans](http://requests-docs-cn.readthedocs.org/zh_CN/latest/) * [Pillow ไธญๆ–‡ๆ–‡ๆกฃ](http://pillow-cn.readthedocs.org/en/latest/#) * [PyMOTW ไธญๆ–‡็‰ˆ](http://pymotwcn.readthedocs.org/en/latest/index.html) * [Python ๅฎ˜ๆ–นๆ–‡ๆกฃไธญๆ–‡็‰ˆ](http://data.digitser.net/zh-CN/python_index.html) * [Fabric ไธญๆ–‡ๆ–‡ๆกฃ](http://fabric-chs.readthedocs.org) * [Beautiful Soup 4.2.0 ไธญๆ–‡ๆ–‡ๆกฃ](http://beautifulsoup.readthedocs.org/zh_CN/latest/) * [Python ไธญ็š„ Socket ็ผ–็จ‹](https://legacy.gitbook.com/book/keelii/socket-programming-in-python-cn/details) * [็”จPythonๅš็ง‘ๅญฆ่ฎก็ฎ—](https://docs.huihoo.com/scipy/scipy-zh-cn/index.html) * [Sphinx ไธญๆ–‡ๆ–‡ๆกฃ](http://www.pythondoc.com/sphinx/index.html) * [็ฒพ้€š Python ่ฎพ่ฎกๆจกๅผ](https://github.com/cundi/Mastering.Python.Design.Patterns) * [python ๅฎ‰ๅ…จ็ผ–็จ‹ๆ•™็จ‹](https://github.com/smartFlash/pySecurity) * [็จ‹ๅบ่ฎพ่ฎกๆ€ๆƒณไธŽๆ–นๆณ•](https://www.gitbook.com/book/wizardforcel/sjtu-cs902-courseware/details) * [็ŸฅไนŽๅ‘จๅˆŠยท็ผ–็จ‹ๅฐ็™ฝๅญฆPython](https://read.douban.com/ebook/16691849/) * [Scipy ่ฎฒไน‰](https://github.com/cloga/scipy-lecture-notes_cn) * [Python ๅญฆไน ็ฌ”่ฎฐ ๅŸบ็ก€็ฏ‡](http://www.kuqin.com/docs/pythonbasic.html) * [Python ๅญฆไน ็ฌ”่ฎฐ ๆจกๅ—็ฏ‡](http://www.kuqin.com/docs/pythonmodule.html) * [Python ๆ ‡ๅ‡†ๅบ“ ไธญๆ–‡็‰ˆ](http://old.sebug.net/paper/books/python/%E3%80%8APython%E6%A0%87%E5%87%86%E5%BA%93%E3%80%8B%E4%B8%AD%E6%96%87%E7%89%88.pdf) * [Python่ฟ›้˜ถ](https://www.gitbook.com/book/eastlakeside/interpy-zh/details) * [Python ๆ ธๅฟƒ็ผ–็จ‹ ็ฌฌไบŒ็‰ˆ](https://wizardforcel.gitbooks.io/core-python-2e/content/) CPyUG่ฏ‘ * [Pythonๆœ€ไฝณๅฎž่ทตๆŒ‡ๅ—](http://pythonguidecn.readthedocs.io/zh/latest/) * [Python ็ฒพ่ฆๆ•™็จ‹](https://www.gitbook.com/book/wizardforcel/python-essential-tutorial/details) * [Python ้‡ๅŒ–ไบคๆ˜“ๆ•™็จ‹](https://www.gitbook.com/book/wizardforcel/python-quant-uqer/details) * [Python้ป‘้ญ”ๆณ•ๆ‰‹ๅ†Œ](https://magic.iswbm.com/preface.html) * Django * [Django 1.5 ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](http://django-chinese-docs.readthedocs.org/en/latest/) ๆญฃๅœจ็ฟป่ฏ‘ไธญ * [Django 2.0 ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](https://docs.djangoproject.com/zh-hans/2.0/) * [Django ๆœ€ไฝณๅฎž่ทต](https://github.com/yangyubo/zh-django-best-practices) * [Django 2.1 ๆญๅปบไธชไบบๅšๅฎขๆ•™็จ‹](https://www.dusaiphoto.com/article/detail/2/) ( ็ผ–ๅ†™ไธญ ) * [Djangoๆญๅปบ็ฎ€ๆ˜“ๅšๅฎขๆ•™็จ‹](https://www.gitbook.com/book/andrew-liu/django-blog/details) * [The Django Book ไธญๆ–‡็‰ˆ](http://djangobook.py3k.cn/2.0/) * [Django ่ฎพ่ฎกๆจกๅผไธŽๆœ€ไฝณๅฎž่ทต](https://github.com/cundi/Django-Design-Patterns-and-Best-Practices) * [Django ็ฝ‘็ซ™ๅผ€ๅ‘ Cookbook](https://github.com/cundi/Web.Development.with.Django.Cookbook) * [Django Girls ๅญธ็ฟ’ๆŒ‡ๅ—](https://www.gitbook.com/book/djangogirlstaipei/django-girls-taipei-tutorial/details) * Flask * [Flask ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](http://docs.jinkan.org/docs/flask/) * [Jinja2 ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](http://docs.jinkan.org/docs/jinja2/) * [Werkzeug ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](http://werkzeug-docs-cn.readthedocs.org/zh_CN/latest/) * [Flaskไน‹ๆ—…](http://spacewander.github.io/explore-flask-zh/) * [Flask ๆ‰ฉๅฑ•ๆ–‡ๆกฃๆฑ‡ๆ€ป](https://www.gitbook.com/book/wizardforcel/flask-extension-docs/details) * [Flask ๅคงๅž‹ๆ•™็จ‹](http://www.pythondoc.com/flask-mega-tutorial/index.html) * [SQLAlchemy ไธญๆ–‡ๆ–‡ๆกฃ](http://docs.jinkan.org/docs/flask-sqlalchemy/) * [Flask ๅ…ฅ้—จๆ•™็จ‹](https://read.helloflask.com) * web.py * [web.py 0.3 ๆ–ฐๆ‰‹ๆŒ‡ๅ—](http://webpy.org/tutorial3.zh-cn) * [Web.py Cookbook ็ฎ€ไฝ“ไธญๆ–‡็‰ˆ](http://webpy.org/cookbook/index.zh-cn) * Tornado * [Introduction to Tornado ไธญๆ–‡็ฟป่ฏ‘](http://demo.pythoner.com/itt2zh/index.html) * [Tornadoๆบ็ ่งฃๆž](http://www.nowamagic.net/academy/detail/13321002) * [Tornado 4.3 ๆ–‡ๆกฃไธญๆ–‡็‰ˆ](https://tornado-zh.readthedocs.org/zh/latest/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## R * [R่ฏญ่จ€ๅฟ่€…็ง˜็ฌˆ](https://github.com/yihui/r-ninja) * [R่ฏญ่จ€ๆ•™็จ‹](https://www.math.pku.edu.cn/teachers/lidf/docs/Rbook/html/_Rbook/index.html) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Ruby * [Ruby ้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/JuanitoFatas/ruby-style-guide/blob/master/README-zhCN.md) * [Rails ้ฃŽๆ ผๆŒ‡ๅ—](https://github.com/JuanitoFatas/rails-style-guide/blob/master/README-zhCN.md) * [็ฌจๆ–นๆณ•ๅญธ Ruby](http://lrthw.github.io/) * [Ruby on Rails ๆŒ‡ๅ—](http://guides.ruby-china.org/) * [Ruby on Rails ๅฏฆๆˆฐ่–็ถ“](https://ihower.tw/rails4/index.html) * [Ruby on Rails Tutorial ๅŽŸไนฆ็ฌฌ 3 ็‰ˆ](http://railstutorial-china.org/) (ๆœฌไนฆ็ฝ‘้กต็‰ˆๅ…่ดนๆไพ›๏ผŒ็”ตๅญ็‰ˆไปฅ PDFใ€EPub ๅ’Œ Mobi ๆ ผๅผๆไพ›่ดญไนฐ๏ผŒไป…ๅ”ฎ 9.9 ็พŽๅ…ƒ) * [Rails ๅฎž่ทต](http://rails-practice.com/content/index.html) * [Rails 5 ๅผ€ๅ‘่ฟ›้˜ถ(Beta)](https://www.gitbook.com/book/kelby/rails-beginner-s-guide/details) * [Rails 102](https://www.gitbook.com/book/rocodev/rails-102/details) * [็ผ–ๅ†™Ruby็š„Cๆ‹“ๅฑ•](https://wusuopu.gitbooks.io/write-ruby-extension-with-c/content/) * [Ruby ๆบ็ ่งฃ่ฏป](https://ruby-china.org/topics/22386) * [Rubyไธญ็š„ๅ…ƒ็ผ–็จ‹](http://deathking.github.io/metaprogramming-in-ruby/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Rust * [Rust็ผ–็จ‹่ฏญ่จ€ ไธญๆ–‡็ฟป่ฏ‘](https://kaisery.github.io/trpl-zh-cn/) * [้€š่ฟ‡ไพ‹ๅญๅญฆ Rust ไธญๆ–‡็‰ˆ](https://rustwiki.org/zh-CN/rust-by-example/) * [Rust Primer](https://github.com/rustcc/RustPrimer) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Scala * [Scala่ฏพๅ ‚](http://twitter.github.io/scala_school/zh_cn/index.html) (Twitter็š„Scalaไธญๆ–‡ๆ•™็จ‹) * [Effective Scala](http://twitter.github.io/effectivescala/index-cn.html)(Twitter็š„Scalaๆœ€ไฝณๅฎž่ทต็š„ไธญๆ–‡็ฟป่ฏ‘) * [ScalaๆŒ‡ๅ—](http://zh.scala-tour.com/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Shell * [Shell่„šๆœฌ็ผ–็จ‹30ๅˆ†้’Ÿๅ…ฅ้—จ](https://github.com/qinjx/30min_guides/blob/master/shell.md) * [Bash่„šๆœฌ15ๅˆ†้’Ÿ่ฟ›้˜ถๆ•™็จ‹](http://blog.sae.sina.com.cn/archives/3606) * [Linuxๅทฅๅ…ทๅฟซ้€Ÿๆ•™็จ‹](https://github.com/me115/linuxtools_rst) * [shellๅไธ‰้—ฎ](https://github.com/wzb56/13_questions_of_shell) * [Shell็ผ–็จ‹่Œƒไพ‹](https://www.gitbook.com/book/tinylab/shellbook/details) * [Linuxๅ‘ฝไปคๆœ็ดขๅผ•ๆ“Ž](https://wangchujiang.com/linux-command/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## Swift * [The Swift Programming Language ไธญๆ–‡็‰ˆ](http://numbbbbb.github.io/the-swift-programming-language-in-chinese/) * [Swift ่ฏญ่จ€ๆŒ‡ๅ—](http://dev.swiftguide.cn) * [Stanford ๅ…ฌๅผ€่ฏพ๏ผŒDeveloping iOS 8 Apps with Swift ๅญ—ๅน•็ฟป่ฏ‘ๆ–‡ไปถ](https://github.com/x140yu/Developing_iOS_8_Apps_With_Swift) * [C4iOS - COSMOS](http://c4ios.swift.gg) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ## ่ฏปไนฆ็ฌ”่ฎฐๅŠๅ…ถๅฎƒ * [็ผ–่ฏ‘ๅŽŸ็†๏ผˆ็ดซ้พ™ไนฆ๏ผ‰ไธญๆ–‡็ฌฌ2็‰ˆไน ้ข˜็ญ”ๆกˆ](https://github.com/fool2fish/dragon-book-exercise-answers) * [ๆŠŠใ€Š็ผ–็จ‹็ ็Ž‘ใ€‹่ฏป่–„](http://hawstein.com/2013/08/11/make-thiner-programming-pearls/) * [Effective C++่ฏปไนฆ็ฌ”่ฎฐ](https://github.com/XiaolongJason/ReadingNote/blob/master/Effective%20C%2B%2B/Effective%20C%2B%2B.md) * [Golang ๅญฆไน ็ฌ”่ฎฐใ€Python ๅญฆไน ็ฌ”่ฎฐใ€C ๅญฆไน ็ฌ”่ฎฐ](https://github.com/qyuhen/book) (PDF) * [Jsoup ๅญฆไน ็ฌ”่ฎฐ](https://github.com/code4craft/jsoup-learning) * [ๅญฆไน ็ฌ”่ฎฐ: Vimใ€Pythonใ€memcached](https://github.com/lzjun567/note) * [ๅ›พ็ตๅผ€ๆ”พไนฆ็ฟป่ฏ‘่ฎกๅˆ’--C++ใ€Pythonใ€Java็ญ‰](http://www.ituring.com.cn/activity/details/2004) * [่’‚ๅง†ยทๅฅฅ่Žฑๅˆฉ้š็ฌ”](http://g.yeeyan.org/books/2095) ๏ผˆ็”ฑ่ฏ‘่จ€็ฝ‘็ฟป่ฏ‘๏ผŒ็”ตๅญ็‰ˆๅ…่ดน๏ผ‰ * [SICP ่งฃ้ข˜้›†](http://sicp.readthedocs.org/en/latest/) * [็ฒพๅฝฉๅšๅฎข้›†ๅˆ](https://github.com/hacke2/hacke2.github.io/issues/2) * [ไธญๆ–‡ๆ–‡ๆกˆๆŽ’็‰ˆๆŒ‡ๅŒ—](https://github.com/sparanoid/chinese-copywriting-guidelines) * [Standard C ่ฏญ่จ€ๆ ‡ๅ‡†ๅ‡ฝๆ•ฐๅบ“้€ŸๆŸฅ (Cheat Sheet)](http://ganquan.info/standard-c/) * [Git Cheatsheet Chs](http://gh.amio.us/git-cheatsheet-chs/) * [GitBook็ฎ€ๆ˜Žๆ•™็จ‹](http://www.chengweiyang.cn/gitbook/index.html) * [ๅˆถ้€ ๅผ€ๆบ่ฝฏไปถ](http://producingoss.com/zh/) * [ๆ้—ฎ็š„ๆ™บๆ…ง](http://www.dianbo.org/9238/stone/tiwendezhihui.htm) * [Markdown ๅ…ฅ้—จๅ‚่€ƒ](https://github.com/LearnShare/Learning-Markdown) * [AsciiDoc็ฎ€ๆ˜ŽๆŒ‡ๅ—](https://github.com/stanzgy/wiki/blob/master/markup/asciidoc-guide.asciidoc) * [่ƒŒๅŒ…้—ฎ้ข˜ไน่ฎฒ](http://love-oriented.com/pack/) * [่€้ฝ็š„ๆŠ€ๆœฏ่ต„ๆ–™](https://github.com/qiwsir/ITArticles) * [ๅ‰็ซฏๆŠ€่ƒฝๆฑ‡ๆ€ป](https://github.com/JacksonTian/fks) * [ๅ€ŸๅŠฉๅผ€ๆบ้กน็›ฎ๏ผŒๅญฆไน ่ฝฏไปถๅผ€ๅ‘](https://github.com/zhuangbiaowei/learn-with-open-source) * [ๅ‰็ซฏๅทฅไฝœ้ข่ฏ•้—ฎ้ข˜](https://github.com/h5bp/Front-end-Developer-Interview-Questions/tree/master/Translations/Chinese) * [leetcode/lintcode้ข˜่งฃ/็ฎ—ๆณ•ๅญฆไน ็ฌ”่ฎฐ](https://www.gitbook.com/book/yuanbin/algorithm/details) * [ๅ‰็ซฏๅผ€ๅ‘็ฌ”่ฎฐๆœฌ](https://github.com/li-xinyang/FEND_Note) * [LeetCode้ข˜่งฃ](https://siddontang.gitbooks.io/leetcode-solution/content/) * [ใ€Šไธๅฏๆ›ฟไปฃ็š„ๅ›ข้˜Ÿ้ข†่ข–ๅŸนๅ…ป่ฎกๅˆ’ใ€‹](https://leader.js.cool/#/) [่ฟ”ๅ›ž็›ฎๅฝ•](#็›ฎๅฝ•) ### ๆต‹่ฏ•็›ธๅ…ณ
188
Gathering all info published, both by Apple and by others, about new framework SwiftUI.
![](Assets/banner_about_swift.jpg) Since past Apple's keynote, where **SwiftUI** was announced, tons of docs, examples, videos and tutorials have appeared. The goal of this repository is to gather all this information having a unique place where looking for info about **SwiftUI**. **SwiftUI** is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. With a declarative Swift syntax thatโ€™s easy to read and natural to write, SwiftUI works seamlessly with new Xcode design tools to keep your code and design perfectly in sync. Automatic support for Dynamic Type, Dark Mode, localization, and accessibility means your first line of **SwiftUI** code is already the most powerful UI code youโ€™ve ever written. [![Twitter](https://img.shields.io/twitter/url/https/github.com/Juanpe/About-SwiftUI.svg?style=social)](https://twitter.com/intent/tweet?text=Wow%20This%20library%20is%20awesome:&url=https%3A%2F%2Fgithub.com%2FJuanpe%2FAbout-SwiftUI) ### Table of contents - [๏ฃฟ by Apple](#-by-apple) - [๐Ÿ“š Documentation](#-documentation) - [๐Ÿ“น WWDC videos](#-wwdc-videos) - [๐Ÿ‘ฉ๐Ÿผโ€๐Ÿซ Tutorials](#-tutorials) - [๐ŸŒŽ by the community](#-by-the-community) - [๐Ÿ“— Books](#-books) - [๐ŸŽ“ Courses](#-courses) - [๐Ÿ”— Websites](#-websites) - [๐Ÿ“ฐ Articles](#-articles) - [๐Ÿค– Unit Testing](#-unit-testing) - [๐Ÿ”จ Xcode Extensions](#-xcode-extensions) - [๐Ÿ“ฆ Repositories](#-repositories) - [Layout ๐ŸŽ›](#layout-) - [๐Ÿ–ฅ Videos](#-videos) - [โค๏ธ Contributing](#๏ธ-contributing) ## ๏ฃฟ by Apple #### ๐Ÿ“š Documentation * **[SwiftUI](https://developer.apple.com/xcode/swiftui/)** * **[Official doc](https://developer.apple.com/documentation/swiftui)** * **Essentials** * **[Introducing SwiftUI](https://developer.apple.com/tutorials/SwiftUI)**. SwiftUI is a modern way to declare user interfaces for any Apple platform. Create beautiful, dynamic apps faster than ever before. * **[App Structure and Behavior](https://developer.apple.com/documentation/swiftui/app-structure-and-behavior)**. Define the entry point and top-level organization of your app. * **User Interface** * **[Views and Controls](https://developer.apple.com/documentation/swiftui/views_and_controls)**. Present your content onscreen and handle user interactions. * **[View Layout and Presentation](https://developer.apple.com/documentation/swiftui/view_layout_and_presentation)**. Combine views in stacks, generate groups and lists of views dynamically, and define view presentations and hierarchy. * **[Drawing and Animation](https://developer.apple.com/documentation/swiftui/drawing_and_animation)**. Enhance your views with colors, shapes, and shadows, and customize animated transitions between view states. * **[Framework Integration](https://developer.apple.com/documentation/swiftui/framework_integration)**. Integrate SwiftUI views into existing apps, and embed AppKit, UIKit, and WatchKit views and controllers into SwiftUI view hierarchies. * **Data and Events** * **[State and Data Flow](https://developer.apple.com/documentation/swiftui/state_and_data_flow)**. Control and respond to the flow of data and changes within your appโ€™s models. * **[Gestures](https://developer.apple.com/documentation/swiftui/gestures)**. Define interactions from taps, clicks, and swipes to fine-grained gestures. * **Previews in Xcode** * **[Previews](https://developer.apple.com/documentation/swiftui/previews)**. Generate dynamic, interactive previews of your custom views. * **Develop Apps with SwiftUI** * **[Develop Apps with SwiftUI](https://developer.apple.com/tutorials/app-dev-training)**. Create apps using SwiftUI and Xcode. Build Scrumdinger, an app that keeps track of daily scrums. #### ๐Ÿ“น WWDC videos - **2๏ธโƒฃ0๏ธโƒฃ2๏ธโƒฃ2๏ธโƒฃ** - **[Hello Swift Charts](https://developer.apple.com/videos/play/wwdc2022/10136/)** - **[The SwiftUI cookbook for navigation](https://developer.apple.com/videos/play/wwdc2022/10054/)** - **[What's new in SwiftUI](https://developer.apple.com/videos/play/wwdc2022/10052/)** - **[Compose custom layouts with SwiftUI](https://developer.apple.com/videos/play/wwdc2022/10056/)** - **[Swift Charts: Raise the bar](https://developer.apple.com/videos/play/wwdc2022/10137/)** - **[SwiftUI on iPad: Add toolbars, titles, and more](https://developer.apple.com/videos/play/wwdc2022/110343/)** - **[SwiftUI on iPad: Organize your interface](https://developer.apple.com/videos/play/wwdc2022/10058/)** - **[Use SwiftUI with AppKit](https://developer.apple.com/videos/play/wwdc2022/10075/)** - **[Use SwiftUI with UIKit](https://developer.apple.com/videos/play/wwdc2022/10072/)** - **[Bring multiple windows to your SwiftUI app](https://developer.apple.com/videos/play/wwdc2022/10061/)** - **[Efficiency awaits: Background tasks in SwiftUI](https://developer.apple.com/videos/play/wwdc2022/10142/)** - **[Adopt Variable Color in SF Symbols](https://developer.apple.com/videos/play/wwdc2022/10185/)** - **2๏ธโƒฃ0๏ธโƒฃ2๏ธโƒฃ1๏ธโƒฃ** - **[Add rich graphics to your SwiftUI app](https://developer.apple.com/videos/play/wwdc2021-10021)** - **[Craft search experiences in SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10176)** - **[Meet async/await in Swift](https://developer.apple.com/videos/play/wwdc2021-10132)** - **[What's new in SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10018)** - **[Demystify SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10022)** - **[Discover concurrency in SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10019)** - **[Explore the SF Symbols 3 app](https://developer.apple.com/videos/play/wwdc2021-10288)** - **[SF Symbols in SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10349)** - **[SwiftUI Accessibility: Beyond the basics](https://developer.apple.com/videos/play/wwdc2021-10119)** - **[Direct and reflect focus in SwiftUI](https://developer.apple.com/videos/play/wwdc2021-10023)** - **[Localize your SwiftUI app](https://developer.apple.com/videos/play/wwdc2021-10220)** - **2๏ธโƒฃ0๏ธโƒฃ2๏ธโƒฃ0๏ธโƒฃ** - **[Build SwiftUI apps for tvOS](https://developer.apple.com/videos/play/wwdc2020/10042/)** - **[Build complications in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10048/)** - **[Introduction to SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10119/)** - **[What's new in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10041/)** - **[App essentials in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10037/)** - **[Visually edit SwiftUI views](https://developer.apple.com/videos/play/wwdc2020/10185/)** - **[Build a SwiftUI view in Swift Playgrounds](https://developer.apple.com/videos/play/wwdc2020/10643/)** - **[Build document-based apps in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10039/)** - **[Stacks, Grids, and Outlines in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10031/)** - **[Build SwiftUI views for widgets](https://developer.apple.com/videos/play/wwdc2020/10033/)** - **[Design great widgets](https://developer.apple.com/videos/play/wwdc2020/10103)** - **[Widget Code-along](https://developer.apple.com/videos/play/wwdc2020/10034/)** - **[Data Essentials in SwiftUI](https://developer.apple.com/videos/play/wwdc2020/10040/)** - **[Structure your app for SwiftUI previews](https://developer.apple.com/videos/play/wwdc2020/10149/)** - **2๏ธโƒฃ0๏ธโƒฃ1๏ธโƒฃ9๏ธโƒฃ** - **[Introducing SwiftUI: Building Your First App](https://developer.apple.com/videos/play/wwdc2019/204/)** - **[SwiftUI Essentials](https://developer.apple.com/videos/play/wwdc2019/216)** ๐ŸŒŸ - **[Data Flow Through SwiftUI](https://developer.apple.com/videos/play/wwdc2019/226)** - **[Building Custom Views with SwiftUI](https://developer.apple.com/videos/play/wwdc2019/237)** ๐ŸŒŸ - **[Integrating SwiftUI](https://developer.apple.com/videos/play/wwdc2019/231)** - **[Accessibility in SwiftUI](https://developer.apple.com/videos/play/wwdc2019/238)** - **[SwiftUI On All Devices](https://developer.apple.com/videos/play/wwdc2019/240)** - **[SwiftUI on watchOS](https://developer.apple.com/videos/play/wwdc2019/219)** - **[Mastering Xcode Previews](https://developer.apple.com/videos/play/wwdc2019/233)** _๐ŸŒŸ most interesting_ #### ๐Ÿ‘ฉ๐Ÿผโ€๐Ÿซ Tutorials * **[Creating and Combining Views](https://developer.apple.com/tutorials/swiftui/creating-and-combining-views)** * **[Working with UI Controls](https://developer.apple.com/tutorials/swiftui/working-with-ui-controls)** * **[Handling User Input](https://developer.apple.com/tutorials/swiftui/handling-user-input)** * **[Building Lists and Navigation](https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation)** * **[Drawing Paths and Shapes](https://developer.apple.com/tutorials/swiftui/drawing-paths-and-shapes)** * **[Animating Views and Transitions](https://developer.apple.com/tutorials/swiftui/animating-views-and-transitions)** * **[Composing Complex Interfaces](https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces)** * **[Interfacing with UIKit](https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit)** ## ๐ŸŒŽ by the community #### ๐Ÿ“— Books * **[Swift UI by Tutorials](https://store.raywenderlich.com/products/swiftui-by-tutorials)** by [Ray wenderlich](https://www.raywenderlich.com/) * **[Combine: Asynchronous Programming with Swift](https://store.raywenderlich.com/products/combine-asynchronous-programming-with-swift)** by [Ray wenderlich](https://www.raywenderlich.com/) * **[Catalyst by Tutorials](https://store.raywenderlich.com/products/catalyst-by-tutorials)** by [Ray wenderlich](https://www.raywenderlich.com/) * **[SwiftUI by Example - Book](https://gumroad.com/l/swiftui)** by [Hacking with Swift](https://twitter.com/twostraws) * **[SwiftUI Views Quick Start (free)](https://www.bigmountainstudio.com/free-swiftui-book)** by [Big Mountain Studio](https://twitter.com/bigmtnstudio) * **[SwiftUI Views Mastery](https://www.bigmountainstudio.com/swiftui-views-book)** by [Big Mountain Studio](https://twitter.com/bigmtnstudio) * **[SwiftUI Animations Mastery](https://www.bigmountainstudio.com/swiftui-animations)** by [Big Mountain Studio](https://twitter.com/bigmtnstudio) * **[Working with Data in SwiftUI](https://www.bigmountainstudio.com/data)** by [Big Mountain Studio](https://twitter.com/bigmtnstudio) * **[Combine Mastery in SwiftUI](https://www.bigmountainstudio.com/combine)** by [Big Mountain Studio](https://twitter.com/bigmtnstudio) * **[Using Combine](https://heckj.github.io/swiftui-notes/)** ([PDF/ePub at Gumroad](https://gum.co/usingcombine) by [Joseph Heck](https://rhonabwy.com/) * **๐Ÿ‡จ๐Ÿ‡ณ[SwiftUIๅฎžๆˆ˜๏ผŒๅธฆไฝ ๅ…ฅ้—จ่‹นๆžœๆœ€ๆ–ฐ็š„UIๅผ€ๅ‘ๆก†ๆžถ - SwiftUI in Action, bring you the latest UI development framework from Apple](https://juejin.im/book/5db6b0fa6fb9a020446c5278)** by [zixiao233](https://juejin.im/user/5daa73b551882508866e973b) * **[Thinking in SwiftUI](https://www.objc.io/books/thinking-in-swiftui/)** by [objc.io](https://www.objc.io) * **[SwiftUI for Absolute Beginners](https://www.amazon.com/SwiftUI-Absolute-Beginners-Program-Controls/dp/1484255151)** by Jayant Varma #### ๐ŸŽ“ Courses * **[Learn SwiftUI](https://designcode.io/swiftui-course)**. by [Meng To](https://twitter.com/mengto) * **[SwiftUI Masterclass 2021 - iOS 14 App Development & Swift 5](https://www.udemy.com/course/swiftui-masterclass-course-ios-development-with-swift/)** . by [Robert Petras](https://www.linkedin.com/in/robertpetras/) * **๐Ÿ‡จ๐Ÿ‡ณ[SwiftUI ไธญๆ–‡ๆ•™็จ‹ - SwiftUI-Tutorials](https://github.com/WillieWangWei/SwiftUI-Tutorials)**. by [WillieWangWei](https://github.com/WillieWangWei) * **[SwiftUI - The Complete Developer Course](https://www.udemy.com/share/102VaMAkofc1pbRHo=/)**. by [Stephen DeStefano](https://www.linkedin.com/in/stephen-destefano-973583193/) * **[CS193p - Developing Apps for iOS](https://cs193p.sites.stanford.edu)**. by [Stanford University](https://www.stanford.edu) #### ๐Ÿ”— Websites * **[SwiftUI Hub - SwiftUI Tutorials & Resources](https://swiftuihub.com)** * **[Fucking SwiftUI - SwiftUI Cheat Sheet](https://fuckingswiftui.com)** * **[Gi Sheet - Ultimate SwiftUI Cheat Sheet on github](https://github.com/giridharan-dev/SwiftUi-GiSheet)** * **[Gosh Darn SwiftUI - SwiftUI Cheat Sheet (work-friendly mirror)](https://goshdarnswiftui.com)** * **[The SwiftUI Lab - When the documentation is missing, we experiment](https://swiftui-lab.com)** * **[SwiftOnTap โ€“ Complete SwiftUI Docs with Examples](https://swiftontap.com)** * **[SwiftUI Examples for Designers](https://swiftui.design/examples)** * **[SwiftUI Tutorials](https://blckbirds.com/swiftui-tutorials/)** #### ๐Ÿ“ฐ Articles * **[SwiftUI by Example](https://www.hackingwithswift.com/quick-start/swiftui)** by [Hacking with Swift](https://twitter.com/twostraws) * **[Get started with SwiftUI](https://www.hackingwithswift.com/articles/194/get-started-with-swiftui)** by [Hacking with Swift](https://twitter.com/twostraws) * **[SwiftUI tips and tricks](https://www.hackingwithswift.com/quick-start/swiftui/swiftui-tips-and-tricks)** by [Hacking with Swift](https://twitter.com/twostraws) * **[Higher-Order-Components in SwiftUI](https://medium.com/@andreivillasana/swiftui-reusable-components-higher-order-components-192c65375c36?postPublishedType=initial)** by [Andrei Villasana](https://www.linkedin.com/in/andrei-villasana-5a06a2119/) * **[SwiftUIโ€™s relationship to UIKit and AppKit](https://wwdcbysundell.com/2019/swiftui-relationship-to-uikit-appkit/)** by [@SwiftBySundell](https://twitter.com/swiftbysundell) * **[Answers to the most common questions about SwiftUI](https://wwdcbysundell.com/2019/swiftui-common-questions/)** by [@SwiftBySundell](https://twitter.com/swiftbysundell) * **[A first look at SwiftUI: Appleโ€™s declarative new UI framework](https://wwdcbysundell.com/2019/swiftui-first-look/)** by [@SwiftBySundell](https://twitter.com/swiftbysundell) * **[Inside SwiftUI's Declarative Syntax's Compiler Magic](https://swiftrocks.com/inside-swiftui-compiler-magic.html)** by [Bruno Rocha](https://twitter.com/rockthebruno) * **[Making real-world app with SwiftUI](https://mecid.github.io/2019/06/05/swiftui-making-real-world-app/)** by [Majid Jabrayilov](https://twitter.com/mecid) * **[SwiftUI Are we saying goodbye to IB(UIStoryboard)?](https://medium.com/@themedo8000/swiftui-are-we-saying-goodbye-to-ib-718035e83b07)** by [Mohammad Sawalha](https://medium.com/@themedo8000) * **[How To Make a Simple Countdown Timer with SwiftUI](https://medium.com/better-programming/make-a-simple-countdown-with-timer-and-swiftui-3ce355b54986)** by [Antoine Barrault](https://twitter.com/_ant_one) * **[Tutorial: How to setup a SwiftUI project](https://medium.com/@martinlasek/swiftui-getting-started-372389fff423)** by [Martin Lasek](https://twitter.com/MartinLasek) * **[What SwiftUI Means for Flutter](https://medium.com/flutter-nyc/what-swiftui-means-for-flutter-6d5898f7adf7)** by [Martin Rybak](https://twitter.com/martin_rybak) * **[Intro to SwiftUI](https://medium.com/@santoshbotre01/intro-to-swiftui-b285808842d5)** by [Santosh Botre](https://medium.com/@santoshbotre01) * **[SF Symbols in iOS 13](https://medium.com/@craiggrummitt/sf-symbols-in-ios-13-55e5febf6db6)** by [craiggrummitt](https://twitter.com/craiggrummitt) * **[Understanding SwiftUI in depth](https://medium.com/techtron/understanding-swiftui-in-depth-58d42614619e)** by [Balraj Singh](https://medium.com/@erbalrajs) * **[A Skeptics view on SwiftUI](https://medium.com/@JillevdWeerd/a-skeptics-view-on-swiftui-cc6636b6fd3b)** by [Jille van der Weerd](https://medium.com/@JillevdWeerd) * **[Optionals in SwiftUI](https://medium.com/q42-engineering/swiftui-optionals-ead04edd439f)** by [Jasper Haggenburg](https://twitter.com/Jpunt) * **[Presenting UIViewControllers in SwiftUI](https://medium.com/@Johannes_Nevels/presenting-uiviewcontrollers-in-swiftui-22388616a24c)** by [Johannes Nevels](https://medium.com/@Johannes_Nevels) * **[SwiftUI for React Native Developers](https://medium.com/@rorogadget/swiftui-for-react-native-developers-2072a21c22fb)** by [Rohan Panchal](https://twitter.com/rorogadget) * **[SwiftUI First Look: Building a Simple Table View App](https://www.appcoda.com/swiftui-first-look/?utm_campaign=AppCoda%20Weekly&utm_medium=email&utm_source=Revue%20newsletter)** by [AppCoda](https://twitter.com/appcodamobile) * **[Will Storyboards still be alive?](https://medium.com/flawless-app-stories/storyboard-or-no-storyboard-d3ce6eda91eb)** by [Nabil Kazi](https://twitter.com/nQaze) * **๐Ÿ‡ซ๐Ÿ‡ท [Quโ€™est-ce que SwiftUI?](https://medium.com/@bachur.nicolas/introduction-%C3%A0-swiftui-bf2423d8b3ed)** by [Nicolas Bachur](https://medium.com/@bachur.nicolas) * **[RxSwift to Appleโ€™s Combine โ€œCheat Sheetโ€](https://medium.com/gett-engineering/rxswift-to-apples-combine-cheat-sheet-e9ce32b14c5b)** by [Shai Mishali](https://twitter.com/freak4pc) * **[First impressions of SwiftUI](https://www.cocoawithlove.com/blog/swiftui.html)** by [Matt Gallagher](https://twitter.com/cocoawithlove) * **[Playing with SwiftUI Buttons](https://alejandromp.com/blog/2019/06/09/playing-with-swiftui-buttons/)** by [Alejandro Martinez](https://twitter.com/alexito4) * **[Jun 9 The Swift 5.1 features that power SwiftUIโ€™s API](https://www.swiftbysundell.com/posts/the-swift-51-features-that-power-swiftuis-api)** by [@SwiftBySundell](https://twitter.com/swiftbysundell) * **[Intro to SwiftUIโ€Šโ€”โ€ŠPart 1](https://medium.com/@suyash.srijan/intro-to-swiftui-part-1-47361a3ffb2e)** by [Suyash Srijan](https://twitter.com/suyashsrijan) * **[How to build a Chat App or Messenger in SwiftUI for iOS Swift](https://medium.com/@halavins/how-to-build-a-chat-app-or-messenger-in-swiftui-for-ios-swift-b46dbe5cc0ab)** by [Nick Halavins](https://twitter.com/AntiLand_com) * **[SwiftUI: Getting Started](https://www.raywenderlich.com/3715234-swiftui-getting-started)** by [Ray wenderlich](https://www.raywenderlich.com/) * **[SwiftUI meets Kotlin Multiplatform!](https://johnoreilly.dev/2019/06/08/swiftui-meetings-kotlin-multiplatform/)** by [johnoreilly.dev](https://www.twitter.com/joreilly) * **[Understanding the SwiftUI Sample](https://ruiper-es.ghost.io/understanding-the-swiftui-sample/)** by [Rui Peres](https://twitter.com/peres) * **๐Ÿ‡จ๐Ÿ‡ณ [SwiftUI - First experience](https://medium.com/ๅฝผๅพ—ๆฝ˜็š„-swift-ios-app-้–‹็™ผๅ•้กŒ่งฃ็ญ”้›†/swiftui-็จ‹ๅผ้–‹็™ผๅˆ้ซ”้ฉ—-aea9122741b1)** by [ๅฝผๅพ—ๆฝ˜็š„ iOS App Neverland](https://medium.com/@apppeterpan) * **[SwiftUI Will Change More Than How We Code](https://www.prolificinteractive.com/2019/06/07/swiftui-will-change-more-than-how-we-code/)** by [Harlan Kellaway](https://github.com/hkellaway) for [Prolific Interactive](https://twitter.com/weareprolific) * **[Whatโ€™s this โ€œsomeโ€ in SwiftUI?](https://medium.com/@PhiJay/whats-this-some-in-swiftui-34e2c126d4c4)** by [Mischa Hildebrand](https://twitter.com/DerHildebrand) * **[SwiftUI vs Interface Builder and storyboards](https://www.hackingwithswift.com/quick-start/swiftui/swiftui-vs-interface-builder-and-storyboards)** by [Hacking with Swift](https://twitter.com/twostraws) * **[SwiftUI Basics: List Fetching](https://medium.com/@matschmidy/swiftui-basics-list-fetching-9b03fb145d85?postPublishedType=initial)** by [Mat Schmid](https://twitter.com/devschmidy) * **[SwiftUI, personal thoughts and Model-View-Presenter](https://www.dcordero.me/posts/swiftui_personal_thoughts_and_mvp.html)** by [David Cordero](https://www.dcordero.me) * **[Cloning Tinder using SwiftUI](https://medium.com/@davidgrdoll/cloning-tinder-swiftui-29faed752be6)** by [David Doll](https://twitter.com/davidgdoll) * **[SwiftUI: Project migration from UIKit](https://nikrodionov.com/project-migration-to-swiftui/)** by [Nik Rodionov](https://twitter.com/n_rodionov) * **[MessageUI, SwiftUI and UIKit integration](https://link.medium.com/posgdRBMWX)** * **[Mastering Table Views (Lists) in SwiftUI](https://www.blckbirds.com/post/login-page-in-swiftui-1)** by [BLACKBIRDS](https://www.instagram.com/_blckbirds/?hl=de) * **[Making a Real World Application With SwiftUI](https://medium.com/better-programming/making-a-real-world-application-with-swiftui-cb40884c1056)** by [Thomas Ricouard](https://twitter.com/dimillian) * **[SwiftUI vs Compose](https://quickbirdstudios.com/blog/swiftui-vs-android-jetpack-compose/)** by [QuickBird Studios](https://quickbirdstudios.com/) * **[Advanced Lists in SwiftUI](https://medium.com/better-programming/meet-greet-advanced-lists-in-swiftui-80ab6f08ca03)** * **[GeometryReader to the Rescue](https://swiftui-lab.com/geometryreader-to-the-rescue/)** by [The SwiftUI Lab](https://swiftui-lab.com) * **[Inspecting the View Tree - View Preferences](https://swiftui-lab.com/communicating-with-the-view-tree-part-1/)** by [The SwiftUI Lab](https://swiftui-lab.com) * **[View Extensions for Better Code Readability](https://swiftui-lab.com/view-extensions-for-better-code-readability/)** by [The SwiftUI Lab](https://swiftui-lab.com) * **[ScrollView โ€“ Pull to Refresh](https://swiftui-lab.com/scrollview-pull-to-refresh/)** by [The SwiftUI Lab](https://swiftui-lab.com) * **[My takeaway from working with SwiftUI](https://medium.com/flawless-app-stories/my-takeaway-from-working-with-swiftui-7a589bbd1555)** by [Abbas T. Khan](https://twitter.com/xtabbas) * **[SwiftUI & Combine: Better Together](https://medium.com/flawless-app-stories/swiftui-plus-combine-equals-love-791ad444a082)** by [Peter Friese](https://www.twitter.com/peterfriese) * **[The Simple Life(cycle) of a SwiftUI View](https://medium.com/flawless-app-stories/the-simple-life-cycle-of-a-swiftui-view-95e2e14848a2)** by [@dbolella](https://twitter.com/dbolella) * **[Modal View in SwiftUI](https://medium.com/@diniska/modal-view-in-swiftui-3f9faf910249#d2d0-46626bb2224d)** by [Denis Chashchin](https://medium.com/@diniska/) * **[SwiftUI Layout System: An In-Depth Look](https://kean.github.io/post/swiftui-layout-system)** by [Alexander Grebenyuk](https://twitter.com/a_grebenyuk) * **[SwiftUI Data Flow](https://troz.net/post/2019/swiftui-data-flow/)** by [Sarah Reichelt](https://twitter.com/trozware) * **[Clean Architecture for SwiftUI](https://nalexn.github.io/clean-architecture-swiftui/?utm_source=aboutswiftui)** by [@nallexn](https://twitter.com/nallexn) * **[Programmatic navigation in SwiftUI project](https://nalexn.github.io/swiftui-deep-linking/?utm_source=aboutswiftui)** by [@nallexn](https://twitter.com/nallexn) * **[8 Amazing SwiftUI Libraries to Use in Your Next Project](https://medium.com/better-programming/8-amazing-swiftui-libraries-to-use-in-your-next-project-52efaf211143)** by [@rudrankriyam](https://twitter.com/rudrankriyam) * **[The Inner Workings of State Properties in SwiftUI](https://medium.com/better-programming/the-inner-workings-of-state-properties-in-swiftui-8409ef39a7bd?source=friends_link&sk=bd2d194a6662b86ed7e5e5a00386a306)** by [Zheng](https://aheze.medium.com/) * **[Say Goodbye to SceneDelegate in SwiftUI](https://medium.com/better-programming/say-goodbye-to-scenedelegate-in-swiftui-444173b23015?source=friends_link&sk=a5b7eba78d824d493b9ccd9566ea3e06)** by [Zheng](https://medium.com/@ahzzheng) * **[Infinite List Scroll with SwiftUI and Combine](https://www.vadimbulavin.com/infinite-list-scroll-swiftui-combine/)** by [Yet Another Swift Blog](https://www.vadimbulavin.com) * **[View Communication Patterns in SwiftUI](https://www.vadimbulavin.com/passing-data-between-swiftui-views/)** by [Yet Another Swift Blog](https://www.vadimbulavin.com) * **[SwiftUI Previews at Scale](https://www.vadimbulavin.com/swiftui-previews-at-scale/)** by [Yet Another Swift Blog](https://www.vadimbulavin.com) * **[Using UIView and UIViewController in SwiftUI](https://www.vadimbulavin.com/using-uikit-uiviewcontroller-and-uiview-in-swiftui/)** by [Yet Another Swift Blog](https://www.vadimbulavin.com) * **[How the SwiftUI View Lifecycle and Identity Work](https://doordash.engineering/2022/05/31/how-the-swiftui-view-lifecycle-and-identity-work/)** by [DoorDash Engineering Blog](https://doordash.engineering) * **[Improving SwiftUI Navigation for the Coordinator Pattern](https://johnpatrickmorgan.github.io/2021/07/03/NStack/)** by [John Patrick Morgan Blog](https://johnpatrickmorgan.github.io/) #### ๐Ÿค– Unit Testing * **[Writing testable code when using SwiftUI](https://www.swiftbysundell.com/articles/writing-testable-code-when-using-swiftui/)** by [@JohnSundell](https://twitter.com/JohnSundell) * **[ViewInspector](https://github.com/nalexn/ViewInspector)** by [@nallexn](https://twitter.com/nallexn) * **[Unit testing SwiftUI views](https://nalexn.github.io/swiftui-unit-testing/?utm_source=aboutswiftui)** by [@nallexn](https://twitter.com/nallexn) #### ๐Ÿ“ฑ UI Testing * **[Testing SwiftUI Views](https://www.vadimbulavin.com/snapshot-testing-swiftui-views/)** by [Yet Another Swift Blog](https://www.vadimbulavin.com) #### ๐Ÿ”จ Xcode Extensions * **[nef](https://github.com/bow-swift/nef-plugin)** - This Xcode extension enables you to make a code selection and export it to a snippets. __Available on Mac App Store__. * **[SwiftUI Recipes](https://github.com/globulus/swiftui-recipes-companion)** - companion app and Xcode extension for adding 70+ community-sourced SwiftUI recipes to your code. __Available on Mac App Store__. #### ๐Ÿ“ฆ Repositories * **[100 Days of SwiftUI & Combine](https://github.com/CypherPoet/100-days-of-swiftui-and-combine)** Repo to follow along with _Hacking with Swift_'s [100 Days of SwiftUI](https://www.hackingwithswift.com/100/swiftui) Challenge. * **[Currency Converter & Calculator](https://github.com/CurrencyConverterCalculator/iosCCC)** A currency application for most of the currencies in the world. You can quickly convert and make mathematical operations between currencies. * **[SwiftSunburstDiagram](https://github.com/lludo/SwiftSunburstDiagram)** A library written with SwiftUI to easily render sunburst diagrams given a tree of objects. * **[SwiftUI](https://github.com/Jinxiansen/SwiftUI)**. `SwiftUI` Framework Learning and Usage Guide. ๐Ÿš€ * **[SwiftUITodo](https://github.com/devxoul/SwiftUITodo)**. An example to-do list app using SwiftUI which is introduced in WWDC19. * **[KeyboardAvoiding](https://github.com/a2/KeyboardAvoiding)**. A SwiftUI view that manages a UIViewController that responds to keyboard events with modified additionalSafeAreaInsets. * **[DispatchStore](https://github.com/alexdrone/DispatchStore)**. Swift package that implements an operation based, multi-store ร -la Flux for SwiftUI. * **[GitHubSearchWithSwiftUI](https://github.com/marty-suzuki/GitHubSearchWithSwiftUI)**. SwiftUI based GitHubSearch example. * **[SwiftUI-MovieDB](https://github.com/alfianlosari/SwiftUI-MovieDB)**. SwiftUI MovieDB prototype app built with Xcode 11 Beta & macOS 10.15 Catalina. * **[WWDCPlayer](https://github.com/YOONMS/WWDCPlayer)**. ๐Ÿค– WWDC19 player using SwiftUI. * **[MyDogs](https://github.com/valvoline/MyDogs)**. A simple SwiftUI example for testing Lists, BindableObject, State management and Network. * **[MovieSwiftUI](https://github.com/Dimillian/MovieSwiftUI)**. SwiftUI & Combine app using MovieDB API. * **[CryptoTickerSwiftUI](https://github.com/Dimillian/CryptoTickerSwiftUI)**. Example project using a websocket API and SwiftUI to displays latest BTC-USD trade. (Latest Bitcoin price) * **[SwiftUIRedux](https://github.com/geekaurora/SwiftUIRedux)**. Comprehensive Redux library for SwiftUI, ensures State consistency across Stores with type-safe pub/sub pattern. * **[SwiftUI-Combine](https://github.com/ra1028/SwiftUI-Combine)**. This is an example project of SwiftUI and Combine using GitHub API. * **[SwiftUITimeTravel](https://github.com/timdonnelly/SwiftUITimeTravel)**. An experimental time traveling state store for SwiftUI. * **[SwiftUI_Jike](https://github.com/miliPolo/SwiftUI_Jike)**. SwiftUI imitation app interface (Build Jike App with SwiftUI). * **[2048](https://github.com/unixzii/SwiftUI-2048)**. A 2048 game writing with SwiftUI. * **[SwiftUI-Landmarks](https://github.com/alexpaul/SwiftUI-Landmarks)**. Introducing SwiftUI. A declarative way to create User Interfaces with Swift. * **[SwiftUI-Flux](https://github.com/ra1028/SwiftUI-Flux)**. ๐Ÿš€ This is a tiny experimental application using SwiftUI with Flux architecture. * **[SwiftUI-by-Examples](https://github.com/artemnovichkov/SwiftUI-by-Examples)**. Examples of new SwiftUI framework. * **[SwiftUICalculator](https://github.com/hotchner/SwiftUICalculator)**. A calculator app using SwiftUI which is introduced in WWDC19. * **[InstaFake-Swift-UI](https://github.com/leavenstee/InstaFake-Swift-UI)**. Swift UI Demo for an instagram copy. * **[SwiftUITheme](https://github.com/bellots/SwiftUITheme)**. A first idea to style SwiftUI Views. * **[Lists_-_Navigation_SwiftUI](https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation)**. Exploration of Apple Developer's SwiftUI tutorial, detailing how to build lists and enable navigation between views with #SwiftUI. * **[injectable](https://github.com/vincent-pradeilles/injectable)**. A micro framework that leverages Swift Property Wrapper to implement the Service Locator pattern. * **[SwiftWebImage](https://github.com/geekaurora/SwiftWebImage)**. ๐Ÿš€SwiftUI image downloader for BindingObject with performant LRU mem/disk cache. * **[NetworkImage.swift](https://gist.github.com/ivanbruel/b2838f62cb281bd974ec9c9c121c6cbe)**. Basic NetworkImage support for SwiftUI via Kingfisher * **[SwiftUI-Combine-todo-example](https://github.com/jamfly/SwiftUI-Combine-todo-example)**. A to-do list app using SwiftUI and combine with restful api. * **[Bindings.swift](https://gist.github.com/AliSoftware/ecb5dfeaa7884fc0ce96178dfdd326f8)**. Re-implementation of @binding and @State (from SwiftUI) myself to better understand it. * **[Contacts.swift](https://gist.github.com/jackhl/632935a2e90e3796e38c2143d5dadc96)** * **[CombineUnsplash](https://github.com/vinhnx/CombineUnsplash)**. Exploring SwiftUI + Combine + Result by using Unsplash API, with detailed code explanation. * **[RemoteImage.swift](https://gist.github.com/alexito4/59436b9ab0489b00fb137a8382f38ea5)**. Rough sketch of SwiftUI RemoteImage using AlamofireImage. * **[CombineFeedback](https://github.com/sergdort/CombineFeedback)**. Unidirectional reactive architecture using new Apple Combine framework. * **[Harvest](https://github.com/inamiy/Harvest)**. ๐ŸŒพ Harvest: Apple's Combine.framework + State Machine, inspired by Redux and Elm. * **[Redux HandlingUserInput](https://github.com/AlexeyDemedetskiy/HandlingUserInput)**. HandlingUserInput tutorial showcasing redux style of state and change management. * **[SwiftUI-Cheat-Sheet](https://github.com/SimpleBoilerplates/SwiftUI-Cheat-Sheet)**. SwiftUI Cheat Sheet. * **[swiftui_shadow_and_border.swift](https://gist.github.com/fitomad/b093e008f98c03e87b9c4ba7627798ff)**. Testing SwiftUI. Adding shadow and corner radius to a View. Strange behavior depending on View background color. * **[SwiftUI-MVVM](https://github.com/kitasuke/SwiftUI-MVVM)**. Sample iOS project built by SwiftUI + MVVM and Combine framework using GitHub API. * **[SwiftUI-Circular.swift](https://gist.github.com/Thomvis/8a78d49a662f708311e0440f1f43a204)**. Rough attempt at creating a container view that lays out its children in a circle. * **[NotesApp.swift](https://gist.github.com/jnewc/35692b2a5985c3c99e847ec56098a451)**. A notes app written in >100 lines of swift using SwiftUI. * **[UnsplashSwiftUI](https://github.com/kaunamohammed/UnsplashSwiftUI)**. `UnsplashSwiftUI` A simple app powered by SwiftUI and Unsplash ๐Ÿš€ * **[AniTime](https://github.com/PangMo5/AniTime)**. Anime schedule, korean subtitle for iOS with SwiftUI + Combine and MVVM architecture * **[Fluxus](https://github.com/johnsusek/fluxus)**. Flux for SwiftUI, inspired by Vuex. * **[ChartView in SwiftUI](https://github.com/AppPear/ChartView)**. Easy to use animated Chartview supporting `Bar and Piecharts` * **[Weather](https://github.com/niazoff/Weather)**. ๐ŸŒค A simple SwiftUI weather app using MVVM. * **[Chat](https://github.com/niazoff/Chat)**. ๐Ÿ’ฌ A basic SwiftUI chat app that leverages the new `URLSessionWebSocketTask`. * **[toBlockingArray for Combine](https://gist.github.com/jrsonline/dd9799929e1aceb5d99e83fc6ac2b43b)**. Acts like RxBlocking, for writing tests using the Combine framework. * **[ImageWithActivityIndicator](https://github.com/AliAdam/ImageWithActivityIndicator)**. SwiftUI view that download and display image from URL and displaying Activity Indicator while loading. [Demo](https://github.com/AliAdam/ImageWithActivityIndicatorDemo) * **[๐ŸŒฏ๐ŸŒฏ Burritos](https://github.com/guillermomuntaner/Burritos)**. A collection of Swift Property Wrappers (formerly "Property Delegates"). * **[Hackery](https://github.com/timshim/Hackery/tree/master)** A HackerNews client made using SwiftUI. * **[SwiftUI-Redux-Todo Example](https://github.com/moflo/SwiftUI-Todo-Redux)** An opinionated React/Redux inspired Todo example. * **[Currency Converter](https://github.com/alexliubj/SwiftUI-Currency-Converter)**. A Currency converter app. * **[bottombar-swiftui](https://github.com/smartvipere75/bottombar-swiftui)**. BottomBar component for SwiftUI * **[DealStack](https://github.com/insidegui/DealStack)**. Simple card stack implemented with SwiftUI * **[SwiftUI-PathAnimations](https://github.com/adellibovi/SwiftUI-PathAnimations)**. Tools for SwiftUI that helps perform Path and Shape animations * **[CombineBookSearch](https://github.com/PPacie/CombineBookSearch)**. SwiftUI + Combine + MVVM architecture. * **[YanxuanHD](https://github.com/hite/YanxuanHD/blob/master/README.md)**, The iPad version of '็ฝ‘ๆ˜“ไธฅ้€‰' iOS app * **[Babylon demo](https://github.com/czajnikowski/Babylon)** MVVM with a project-level separation of layers and a leaf `View` framework. * **[RKCalendar](https://github.com/RaffiKian/RKCalendar)** Simple SwiftUI Calendar / Date Picker. * **[Morphi](https://github.com/phimage/morphi)** Additional `Shape` for SwiftUI. * **โฏ [VideoPlayer](https://github.com/wxxsw/VideoPlayer)**, A video player for SwiftUI. * **[DrawerView-SwiftUI](https://github.com/totoroyyb/DrawerView-SwiftUI)** A drawer view with certain customizability implemented by SwiftUI. * **[SwiftUIX](https://github.com/SwiftUIX/SwiftUIX)** An extension to the standard SwiftUI library. * **[SwiftUI-Router](https://github.com/frzi/SwiftUIRouter)**. A routing system proof-of-concept based on React Router. * **[SwiftUI ColorSlider](https://github.com/workingDog/SwiftUIColorSlider)**. Dynamically select a color from a color gradient slider. * **[โŒจ๏ธ KeyboardObserving](https://github.com/nickffox/KeyboardObserving)** A Combine-based solution for observing and avoiding the keyboard in SwiftUI. * **[โ˜‘ Calculator Checklist](https://github.com/xtabbas/calculator-checklist)** Recreation of calculator-checklist project in SwiftUI. * **[Arrival](https://github.com/ronan18/Arrival-IOS)** BART app writen entirely with SwiftUI * **[SF](https://github.com/zmeriksen/SF)** A Small SFSymbols SwiftUI Enum. * **[Pull to Refresh](https://github.com/AppPear/SwiftUI-PullToRefresh)** SwiftUI pull to refresh for List, NavigationView * **[ConnectFour](https://github.com/vsmithers1087/ConnectFour)** A basic Connect Four game built with SwiftUI * **[Modal View](http://github.com/diniska/modal-view)** A simple and safe way to display Modal views in SwiftUI * **[SwiftUI CompatKit](https://github.com/AmirKamali/SwiftUICompactKit)** ๐Ÿค˜ A framework to add missing UIKit Controls to SwiftUI ๐Ÿค˜ * **[SDWebImageSwiftUI](https://github.com/SDWebImage/SDWebImageSwiftUI)**. SDWebImage integration for SwiftUI. Supports async image loading, caching, as well as animated image playback like GIF, APNG and Animated WebP. * **[FlipClock-SwiftUI](https://github.com/elpassion/FlipClock-SwiftUI)** Flip clock implementation in SwiftUI * **[CountdownFilmClutter-SwiftUI](https://github.com/elpassion/CountdownFilmClutter-SwiftUI)** Old fashioned countdown film clutter in SwiftUI * **๐Ÿ‡น๐Ÿ‡ท[SwiftUI-Presentation](https://github.com/barisuyar/SwiftUI-Presentation)** SwiftUI explained in Turkish and prepared a demo application. * **[Sliders](https://github.com/spacenation/swiftui-sliders)**. Custom sliders and tracks for SwiftUI. * **[๐Ÿ“– Pages](https://github.com/nachonavarro/Pages)** A lightweight, paging view solution for SwiftUI. * **[๐Ÿš€ PartialSheet](https://github.com/AndreaMiotto/PartialSheet)** A SwiftUI modifier to show a Partial Modal Sheet based on his content height. * **[๐Ÿ•’ Clock time picker](https://github.com/workingDog/ClockPicker)**. A clock face with draggable hands to pick the hour and minutes of your date. * **๐Ÿ‡จ๐Ÿ‡ณ [SwiftUI-WeChat](https://github.com/wxxsw/SwiftUI-WeChat)** Learn how to make WeChat with SwiftUI. ๅพฎไฟก 7.0 ๐ŸŸข * **[Weather App with MVVM and CoreML](https://github.com/necatievrenyasar/SwiftUI-WeatherApp)** ๐Ÿš€ This demo is very simple project, which designed to understand SwiftUI. It includes Main screen, DayList screen and detail screen. * **[Verge](https://github.com/muukii/Verge)** A Store-Pattern based data-flow architecture for iOS Application with UIKit / SwiftUI. Inspired by Redux and Vuex. * **[Clean Architecture for SwiftUI](https://github.com/nalexn/clean-architecture-swiftui)** A demo project showcasing the production setup of the SwiftUI app with Clean Architecture. * **[SwiftUI-Introspect](https://github.com/siteline/SwiftUI-Introspect)** Introspect underlying UIKit components from SwiftUI. * **๐Ÿ—ฏ๏ธ [Lazy-Pop-SwiftUI](https://github.com/joehinkle11/Lazy-Pop-SwiftUI)** Modifier that allows swiping on any part of the screen to start an interruptible pop animation to the previous view. * **๐Ÿ”ฅ [Login-with-Apple-Firebase-SwiftUI](https://github.com/joehinkle11/Login-with-Apple-Firebase-SwiftUI)** SwiftUI component that handles logging in with Apple into Firebase. Complete tutorial in the README. * **[Awesome-SwiftUI](https://github.com/chinsyo/awesome-swiftui)** A curated list of awesome SwiftUI tutorials, libraries, videos and articles. * **[GrowingTextView-SwiftUI](https://github.com/Zaprogramiacz/GrowingTextView)** Growing text view implemetation in SwiftUI * **[๐Ÿš€ ActionOver](https://github.com/AndreaMiotto/ActionOver)** A SwiftUI modifier to show an Action Sheet on iPhone and a Popover on iPad and Mac. Write just once the actions for the menus. * **๐Ÿƒ[CardStack](https://github.com/dadalar/SwiftUI-CardStackView)** A easy-to-use SwiftUI view for Tinder like cards on iOS, macOS & watchOS. * **[Floating Tab Bar](https://github.com/claudiaeng/FloatingTabBar)** A floating tab bar made in SwiftUI * **[iOS Calculator Clone for iPadOS using SwiftUI](https://github.com/bofeiw/ios-calculator-clone-for-ipados)** A clone of the native iOS built-in Calculator for iPadOS using SwiftUI, mimicking the native Calculator UI and funtions. * **[StepperView](https://github.com/badrinathvm/StepperView)** SwiftUI iOS component for Step Indications * **[๐Ÿ”† UrbanVillageProjectScreens](https://github.com/10011-Studio/UrbanVillageProjectScreens)** Recreations of the Urban Village Project concept screens. * **[๐Ÿฑ SharedObject](https://github.com/lorenzofiamingo/SwiftUI-SharedObject)** A new property wrapper for SwiftUI `ObservableObject`. * **[๐Ÿงญ BetterSafariView](https://github.com/stleamist/BetterSafariView)** A better way to present a `SFSafariViewController` or start a `ASWebAuthenticationSession` in SwiftUI. * **[MGFlipView](https://github.com/Zaprogramiacz/MGFlipView)** allows to create flipping view in easy way without worrying about flipping animation and flipping logic. * **[SwiftUIListSeparator](https://github.com/SchmidtyApps/SwiftUIListSeparator)** View extension to hide/modify List separators in SwiftUI iOS13 and iOS14. * **[InfiniteScroller](https://github.com/cointowitcher/InfiniteScroller)** Horizontal and Vertical collection view for infinite scrolling that was designed to be used in SwiftUI * **[SwiftUI Tooltip](https://github.com/quassummanus/SwiftUI-Tooltip)** SwiftUI Tooltip implementation that works on all platforms and supports SwiftUI v1.0 * **[SVG to SwiftUI](https://github.com/quassummanus/SVG-to-SwiftUI)** SVG to SwiftUI Shape converter * **[Clendar](https://github.com/vinhnx/Clendar)** Clendar is an open-source & universal calendar app, written in SwiftUI. * **[Corona Widget](https://github.com/aaryankotharii/Corona-Widget)** ๐Ÿ˜ท open-source iOS 14 widget to get latest stats on Covid-19. * **[URL-Image](https://github.com/dmytro-anokhin/url-image)** ๐Ÿ”— Open-source solution for quickly displaying `Images` via URL. * **[SFSafeSymbols](https://github.com/piknotech/SFSafeSymbols)** A SF Symbols enum that safely automatically updates upon build. * **[Confetti-View](https://github.com/benlmyers/confetti-view)** ๐ŸŽ‰ A simple confetti view for apps using SwiftUI. * **[Open Source SwiftUI Documentation](https://github.com/SwiftOnTap/Docs)** ๐Ÿš€๐ŸŒŽ open-source SwiftUI documentation! * **[SwiftUICharts](https://github.com/mecid/SwiftUICharts)** A simple line and bar charting library that supports accessibility written using SwiftUI. * **[MarkdownUI](https://github.com/gonzalezreal/MarkdownUI)** Render Markdown text in SwiftUI. * **[Instasoup](https://github.com/robertherdzik/Instasoup)** Instagram home page SwiftUI implementation. * **[FlowStacks](https://github.com/johnpatrickmorgan/FlowStacks)** Coordinator pattern in SwiftUI. ##### Layout ๐ŸŽ› * **[ASCollectionView](https://github.com/apptekstudios/ASCollectionView)** A SwiftUI collection view with support for custom layouts. * **[QGrid](https://github.com/Q-Mobile/QGrid)** The missing SwiftUI collection view. * **[FlowStack](https://github.com/johnsusek/FlowStack)**. A grid layout component. * **[GridStack](https://github.com/pietropizzi/GridStack)**. A flexible grid layout view for SwiftUI. * **[WaterfallGrid](https://github.com/paololeonardi/WaterfallGrid)**. A waterfall grid layout view for SwiftUI. * **[Grid](https://github.com/SwiftUIExtensions/Grid)**. SwiftUI Grid with custom styles. #### ๐Ÿ–ฅ Videos * **[SwiftUI Sneak Preview Demo Project](https://www.youtube.com/watch?v=q421Ll4qOvc)** * **[How to Run SwiftUI on Mojave with Playgrounds and Sample Code](https://www.youtube.com/watch?v=VSvz62fGyYM)** * **[SwiftUI Basics: Dynamic Lists, HStack VStack, Images with Circle Clipped Stroke Overlays](https://www.youtube.com/watch?v=bz6GTYaIQXU)** * **[SwiftUI: Facebook Complex Layouts - Horizontal Scroll View](https://www.youtube.com/watch?v=7QgPpvqTfeo)** * **[SwiftUI Basics Tutorial](https://www.youtube.com/watch?v=IIDiqgdn2yo)** * **[SwiftUI App Tutorial - Lists, Navigation and JSON Data](https://www.youtube.com/watch?v=wbFuAs_UNYg)** * **[SwiftUI Presenting Data In A Scroll View & List](https://www.youtube.com/watch?v=wjqDQ3X5Vos)** * **[Intro To SwiftUI: Simple State Management](https://www.youtube.com/watch?v=AWPiup9fE2c)** * **[Before You Learn SwiftUI, You Need To Hear This...](https://www.youtube.com/watch?v=H9XyZ_F1tPI)** * **[SwiftUI = Mind-blow - WWDC iOS developer reaction](https://www.youtube.com/watch?v=fbuOxKqC5wQ)** * **[SwiftUI - DON'T LEARN IT (JUST YET)](https://www.youtube.com/watch?v=AKHsFNtANes)** * **[SwiftUI Beginner Tutorial On iOS 13 by Devslopes](https://www.youtube.com/watch?v=wwDAvq9MZlQ)** * **[Simple SwiftUI App by Brian Advent](https://www.youtube.com/watch?v=Pfw7zWxchQc)** * **[SwiftUI Tutorial (Swift UI Basics in 1 Video)](https://www.youtube.com/watch?v=IIDiqgdn2yo&ref=quuu)** * **[How To Create Views, Text and Stacks with Swift UI on Mojave](https://www.youtube.com/watch?v=wbxbe35Bbn4)** * **[SwiftUI NavigationView, List, Text, NavigationBarTitle Xcode 11](https://www.youtube.com/watch?v=rySUuXkN5wg)** * **[NavigationView and NavigationButton - Push View in SwiftUI](https://www.youtube.com/watch?v=8tZjVRXsuig)** * **[What's behind SwiftUI DSL? - Swift Function Builders - Following Swift Evolution](https://youtu.be/YG5u0aFgGQI)** * **[Let's Code SwiftUI (WWDC 2019 Preview) - Lesson #00 - รœber das Let's Code](https://www.youtube.com/watch?v=0oI29FIufQU&feature=youtu.be)** * **[SwiftUI - Understanding State](https://www.youtube.com/watch?v=KD4OAjQJYPc&feature=youtu.be)** * **[SwiftUI - Lists - Create Something like UITableView](https://www.youtube.com/watch?v=vLa1z5wVkq0)** * **๐Ÿ‡ช๐Ÿ‡ธ [SwiftUI: Primeros Pasos en Xcode 11 e iOS 13](https://youtu.be/VdOzrsJJIbc)** * **๐Ÿ‡ช๐Ÿ‡ธ [SwiftUI + Xcode 11: Descubre Swift Package Manager y SF Symbols](https://youtu.be/93YBmQNp_sQ)** * **[SwiftUI Tutorial - Create a list that fetches JSON](https://www.youtube.com/watch?v=xkclf3Alz8M)** * **[SwiftUI Complete Apps #1: Build a dynamic list app with navigation and images โ€“ Tutorial](https://www.youtube.com/watch?v=VGJBLlfSN-Y&feature=youtu.be)** * **[Complex UI with SwiftUI from Start to Finish](https://www.youtube.com/watch?v=Xetrbmnszjc)** * **[SwiftUI in UIKit? Yes! Meet DuckUI - Full Course](https://www.youtube.com/watch?v=DjITHGUbRSw&list=PL_csAAO9PQ8bOMSn6HnU31hwq__Yq4e2h)** * **[SwiftUI and State Management: Part 1](https://www.pointfree.co/episodes/ep65-swiftui-and-state-management-part-1)** * **[SwiftUI and State Management: Part 2](https://www.pointfree.co/episodes/ep66-swiftui-and-state-management-part-2)** * **[Orient Views Along Circular Motion Path](https://www.youtube.com/watch?v=8V6mLyeWX58)** * **[SwiftUI-CSS, The missing CSS-like module for SwiftUI](https://github.com/hite/SwiftUI-CSS)** * **[SwiftUI Live: Building an app from scratch](https://www.youtube.com/watch?v=SroTB1buuD0)** ### ๐Ÿ“ฑ Apps * **[DetailsPro - Design tool for SwiftUI](https://detailspro.app)** * **[Vulcan](https://www.purecreek.com)** An app for creating SwiftUI apps. #### โค๏ธ Contributing Feel free to contribute!! This repo is yours.
189
LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
<p align="center" > ย <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/header.png" alt="LLDebugTool" title="LLDebugTool"> </p> [![Version](https://img.shields.io/badge/iOS-%3E%3D8.0-f07e48.svg)](https://img.shields.io/badge/iOS-%3E%3D8.0-f07e48.svg) [![CocoaPods Compatible](https://img.shields.io/badge/pod-v1.3.8.1-blue.svg)](https://img.shields.io/badge/pod-v1.3.8.1-blue.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/badge/Platform-iOS-lightgrey.svg)](https://img.shields.io/badge/Platform-iOS-lightgrey.svg) [![License](https://img.shields.io/badge/License-Anti%20996-blue.svg)](https://github.com/996icu/996.ICU/blob/master/LICENSE) [![Language](https://img.shields.io/badge/Language-Objective--C%20%7C%20Swift-yellow.svg)](https://img.shields.io/badge/Language-Objective--C%20%7C%20Swift-yellow.svg) [![Twitter](https://img.shields.io/badge/[email protected])](https://twitter.com/HdbLi) ## Introduction [็‚นๅ‡ปๆŸฅ็œ‹ไธญๆ–‡็ฎ€ไป‹](https://github.com/HDB-Li/LLDebugTool/blob/master/README-cn.md) LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations. [LLDebugToolSwift](https://github.com/HDB-Li/LLDebugToolSwift) is the extension of [LLDebugTool](https://github.com/HDB-Li/LLDebugTool), it provide swift interface for LLDebugTool, LLDebugToolSwift will release with LLDebugTool at same time. If your project is a Objective-C project, you can use `LLDebugTool`, if your project is a Swift project or contains swift files, you can use `LLDebugToolSwift`. Choose LLDebugTool for your next project, or migrate over your existing projectsโ€”you'll be happy you did! ๐ŸŽŠ๐ŸŽŠ๐ŸŽŠ #### Gif <div align="left"> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/screenGif.gif" width="18%"></img> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenGif-Screenshot.gif" width="18%"></img> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenGif-Screenshot2.gif" width="18%"></img> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenGif-Screenshot3.gif" width="18%"></img> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenGif-Screenshot4.gif" width="18%"></img> </div> #### Preview <div align="left"> <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenShot-3.png" width="18%"> </img> </div> ## What's new in 1.3.8.1 <img src="https://raw.githubusercontent.com/HDB-Li/HDBImageRepository/master/LLDebugTool/ScreenGif-Screenshot4.gif" width="20%"></img> ### Remove auto check version. * Too many visits to the website `cocoadocs.org` cause `cocoadocs.org` to disable the access to `LLDebugTool`, so this function is removed. ## What can you do with LLDebugTool? - Always check the network request or view log information for certain events without having to run under XCode. This is useful in solving the testers' problems. - Easier filtering and filtering of useful information. - Easier analysis of occasional problems. - Easier analysis of the cause of the crash. - Easier sharing, previewing, or removing sandbox files, which can be very useful in the development stage. - Easier observe app's memory, CPU, FPS and other information. - Take screenshots, tag and share. - More intuitive view of view structure and dynamic modify properties. - Determine UI elements and colors in your App more accurately. - Easy access to and comparison of point information. - Easy access to element borders and frames. - Quick entry for html. - Mock location at anytime. ## Adding LLDebugTool to your project ### CocoaPods [CocoaPods](http://cocoapods.org) is the recommended way to add `LLDebugTool` to your project. ##### Objective - C > 1. Add a pod entry for LLDebugTool to your Podfile `pod 'LLDebugTool' , '~> 1.0'`. > 2. If only you want to use it only in Debug mode, Add a pod entry for LLDebugTool to your Podfile `pod 'LLDebugTool' , '~> 1.0' ,:configurations => ['Debug']`, Details also see [Wiki/Use in Debug environment](https://github.com/HDB-Li/LLDebugTool/wiki/Use-in-Debug-environment). If you want to specify the version, use as `pod 'LLDebugTool' , '1.3.8.1' ,:configurations => ['Debug']`. > 3. The recommended approach is to use multiple targets and only add `pod 'LLDebugTool', '~> 1.0'` to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if `:configurations => ['Debug']`, it can only run through XCode. It is not possible to Archive as an App). > 4. Install the pod(s) by running `pod install`. If you can't search `LLDebugTool` or you can't find the newest release version, running `pod repo update` before `pod install`. > 5. Include LLDebugTool wherever you need it with `#import "LLDebug.h"` or you can write `#import "LLDebug.h"` in your .pch in your .pch file. ##### Swift > 1. Add a pod entry for LLDebugToolSwift to your Podfile `pod 'LLDebugToolSwift' , '~> 1.0'`. > 2. If only you want to use it only in Debug mode, Add a pod entry for LLDebugToolSwift to your Podfile `pod 'LLDebugToolSwift' , '~> 1.0' ,:configurations => ['Debug']`, Details also see [Wiki/Use in Debug environment](https://github.com/HDB-Li/LLDebugTool/wiki/Use-in-Debug-environment). If you want to specify the version, use as `pod 'LLDebugToolSwift' , '1.3.8.1' ,:configurations => ['Debug']`. > 3. The recommended approach is to use multiple targets and only add `pod 'LLDebugToolSwift', '~> 1.0'` to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if `:configurations => ['Debug']`, it can only run through XCode. It is not possible to Archive as an App). > 4. Must be added in the Podfile **`use_frameworks!`**. > 5. Install the pod(s) by running `pod install`. If you can't search `LLDebugToolSwift` or you can't find the newest release version, running `pod repo update` before `pod install`. > 6. Include LLDebugTool wherever you need it with `import "LLDebugToolSwift`. ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. ##### Objective - C > 1. To integrate LLDebugTool into your Xcode project using Carthage, specify it in your `Cartfile`: > > `github "LLDebugTool"` > > 2. Run `carthage` to build the framework and drag the built `LLDebugTool.framework` into your Xcode project. ##### Swift > 1. To integrate LLDebugToolSwift into your Xcode project using Carthage, specify it in your `Cartfile`: > > `github "LLDebugToolSwift"` > > 2. Run `carthage` to build the framework and drag the built `LLDebugToolSwift.framework` into your Xcode project. ### Source files Alternatively you can directly add the source folder named LLDebugTool. to your project. ##### Objective - C > 1. Download the [latest code version](https://github.com/HDB-Li/LLDebugTool/archive/master.zip) or add the repository as a git submodule to your git-tracked project. > 2. Open your project in Xcode, then drag and drop the source folder named `LLDebugTool`. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed". > 3. Integrated [FMDB](https://github.com/ccgus/fmdb) to your project,FMDB is an Objective-C wrapper around SQLite. > 4. Integrated [Masonry](https://github.com/SnapKit/Masonry) to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version. > 5. Include LLDebugTool wherever you need it with `#import "LLDebug.h"` or you can write `#import "LLDebug.h"` in your .pch in your .pch file. ##### Swift > 1. Download the [LLDebugTool latest code version](https://github.com/HDB-Li/LLDebugTool/archive/master.zip) or add the repository as a git submodule to your git-tracked project. > 2. Download the [LLDebugToolSwift latest code version](https://github.com/HDB-Li/LLDebugToolSwift/archive/master.zip) or add the repository as a git submodule to your git-tracked project. > 3. Open your project in Xcode, then drag and drop the source folder named `LLDebugTool` and `LLDebugToolSwift`. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed". > 4. Integrated [FMDB](https://github.com/ccgus/fmdb) to your project,FMDB is an Objective-C wrapper around SQLite. > 5. Integrated [Masonry](https://github.com/SnapKit/Masonry) to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version. > 6. Include LLDebugTool wherever you need it with `import LLDebugToolSwift"`. ## Usage ### Get Started You need to start LLDebugTool at "application:(UIApplication * )application didFinishLaunchingWithOptions:(NSDictionary * )launchOptions", Otherwise you will lose some information. If you want to configure some parameters, must configure before "startWorking". More config details see [LLConfig.h](https://github.com/HDB-Li/LLDebugTool/blob/master/LLDebugTool/Config/LLConfig.h). * `Quick Start` In Objective-C ```Objective-C #import "AppDelegate.h" #import "LLDebug.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // The default color configuration is green background and white text color. // Start working. [[LLDebugTool sharedTool] startWorking]; // Write your project code here. return YES; } ``` In Swift ```Swift import LLDebugToolSwift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // ####################### Start LLDebugTool #######################// // Use this line to start working. LLDebugTool.shared().startWorking() // Write your project code here. return true } ``` * `Start With Custom Config` In Objective-C ```Objective-C #import "AppDelegate.h" #import "LLDebug.h" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Start working with config. [[LLDebugTool sharedTool] startWorkingWithConfigBlock:^(LLConfig * _Nonnull config) { //####################### Color Style #######################// // Uncomment one of the following lines to change the color configuration. // config.colorStyle = LLConfigColorStyleSystem; // [config configBackgroundColor:[UIColor orangeColor] primaryColor:[UIColor whiteColor] statusBarStyle:UIStatusBarStyleDefault]; //####################### User Identity #######################// // Use this line to tag user. More config please see "LLConfig.h". config.userIdentity = @"Miss L"; //####################### Window Style #######################// // Uncomment one of the following lines to change the window style. // config.entryWindowStyle = LLConfigEntryWindowStyleNetBar; }]; return YES; } ``` In Swift ```Swift import LLDebugToolSwift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Start working with config. LLDebugTool.shared().startWorking { (config) in //####################### Color Style #######################// // Uncomment one of the following lines to change the color configuration. // config.colorStyle = .system // config.configBackgroundColor(.orange, textColor: .white, statusBarStyle: .default) //####################### User Identity #######################// // Use this line to tag user. More config please see "LLConfig.h". config.userIdentity = "Miss L"; //####################### Window Style #######################// // Uncomment one of the following lines to change the window style. // config.windowStyle = .netBar //####################### Features #######################// // Uncomment this line to change the available features. // config.availables = .noneAppInfo } return true } ``` ### Network Request You don't need to do anything, just call the "startWorking" will monitoring most of network requests, including the use of NSURLSession, NSURLConnection and AFNetworking. If you find that you can't be monitored in some cases, please open an issue and tell me. ### Log Print and save a log. More log macros details see [LLDebugToolMacros.h](https://github.com/HDB-Li/LLDebugTool/blob/master/LLDebugTool/DebugTool/LLDebugToolMacros.h). * `Save Log` In Objective-C ```Objective-C #import "LLDebug.h" - (void)testNormalLog { ย  ย // Insert an LLog where you want to print. LLog(@"Message you want to save or print."); } ``` In Swift ```Swift import LLDebugToolSwift func testNormalLog() { // Insert an LLog where you want to print. LLog.log(message: "Message you want to save or print.") } ``` * `Save Log with event and level` In Objective-C ```Objective-C #import "LLDebug.h" - (void)testEventErrorLog { // Insert an LLog_Error_Event where you want to print an event and level log. ย  ย LLog_Error_Event(@"The event that you want to mark. such as bugA, taskB or processC.",@"Message you want to save or print."); } ``` In Swift ```Swift import LLDebugToolSwift func testEventErrorLog() { // Insert an LLog_Error_Event where you want to print an event and level log. LLog.errorLog(message: "Message you want to save or print.", event: "The event that you want to mark. such as bugA, taskB or processC.") } ``` ### Crash You don't need to do anything, just call the "startWorking" to intercept the crash, store crash information, cause and stack informations, and also store the network requests and log informations at the this time. ### AppInfo LLDebugTool monitors the app's CPU, memory, and FPS. At the same time, you can also quickly check the various information of the app. ### Sandbox LLDebugTool provides a quick way to view and manipulate sandbox, you can easily delete the files/folders inside the sandbox, or you can share files/folders by airdrop elsewhere. As long as apple supports this file format, you can preview the files directly in LLDebugTool. ### Screenshots LLDebugTool provides a screenshot and allows for simple painting and marking that can be easily recorded during testing or while the UI designers debugs the App. ### Hierarchy LLDebugTool provides a view structure tool for viewing or modify elements' properties and information in non-debug mode. ### Magnifier LLDebugTool provides a magnify tool for magnifying local uis and viewing color values at specified pixel. ### Ruler LLDebugTool provides a convenient tools to display touch point information. ### Widget Border LLDebugTool provides a function to display element border, convenient to see the view's frame. ### HTML LLDebugTool can debug HTML pages through `WKWebView`, `UIWebView` or your customized `ViewController` in your app at any time. ### Location LLDebugTool provides a function to mock location at anytime. ### More Usage * You can get more help by looking at the [Wiki](https://github.com/HDB-Li/LLDebugTool/wiki). * You can download and run the [LLDebugToolDemo](https://github.com/HDB-Li/LLDebugTool/archive/master.zip) or [LLDebugToolSwiftDemo](https://github.com/HDB-Li/LLDebugToolSwift/archive/master.zip) to find more use with LLDebugTool. The demo is build under MacOS 10.15.1, XCode 11.2.1, iOS 13.2.2, CocoaPods 1.8.4. If there is any version compatibility problem, please let me know. ## Requirements LLDebugTool works on iOS 8+ and requires ARC to build. It depends on the following Apple frameworks, which should already be included with most Xcode templates: * `UIKit` * `Foundation` * `SystemConfiguration` * `Photos` * `QuickLook` * `CoreTelephony` * `CoreLocation` * `MapKit` * `AVKit` ## Architecture * `LLDebug.h` > Public header file. You can refer it to the pch file. * `DebugTool` > `LLDebugTool` Used to start and stop LLDebugTool, you need to look at it. > `LLConfig` Used for the custom color , size , identification and other information. If you want to configure anything, you need to focus on this file. > `LLDebugToolMacros.h` Quick macro definition file. * `Components` - `Network` Used to monitoring network request. - `Log` Used to quick print and save log. - `Crash` Used to collect crash information when an App crashes. - `AppInfo` Use to monitoring app's properties. - `Sandbox` Used to view and operate sandbox files. - `Screenshot` Used to process and display screenshots. - `Hierarchy` Used to process and present the view structure. - `Magnifier` Used for magnifying glass function. - `Ruler` Used to ruler function. - `Widget Border` User to widget border function. - `Function` Used to show functions. - `Html` Used to dynamic test web view. - `Location` Used to mock location. - `Setting` Used to dynamically set configs. ## Communication - If you **need help**, open an issue. - If you'd like to **ask a general question**, open an issue. - If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. - If you **have a feature request**, open an issue. - If you **find anything wrong or anything dislike**, open an issue. - If you **have some good ideas or some requests**, send mail([email protected]) to me. - If you **want to contribute**, submit a pull request. ## Contact - Send email to [[email protected]]([email protected]) - Send message in twitter [@HdbLi](https://twitter.com/HdbLi) - Send message in [JianShu](https://www.jianshu.com/u/a3c82fae85be) ## Change-log A brief summary of each LLDebugTool release can be found in the [CHANGELOG](CHANGELOG.md). ## License This code is distributed under the terms and conditions of the [MIT license](LICENSE).
190
List of awesome iOS & Swift stuff!!
# Awesome iOS Developer [![Join the chat at https://gitter.im/awesome-ios-developer/community](https://badges.gitter.im/awesome-ios-developer/community.svg)](https://gitter.im/awesome-ios-developer/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) <p> <!-- %%%%%%%%%%%%%%%%%%%%%%% %%%%%%UPDATE LIST%%%%%% %%%%%%%%%%%%%%%%%%%%%%% git useful https://www.gitkraken.com/ -> similar with git tower https://www.git-tower.com/mac -> observe filehistory https://kaleidoscope.app -> diff file manager reduce build time when TDD line 1819 add more description add more description about router service pattern add TCA description add domain pattern(layer) + robot testing in ios add dependency inversion + add service locator + dependency container add description about coordinator pattern add modular architecture add description for tuist template add useful debugging in XCode(Youtube iOS) + need to add more with pic using fastlane + periphery dependency container AR Kit add add book for debugging( ray wenderlich) add service locator pattern composition layer -sil option for optimization build for swift compile SwiftGen - auto generate string & asset enum opensource apple developer tutorial video link update --> <p align="center"> <img alt="awesome" src="https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg" /> <a href="https://hits.seeyoufarm.com"> <img src="https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fjphong1111%2FUseful_Swift&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=true"/> </a> </p> <p align="center"> ๐ŸŒŸFeel free to contribute this Repository!!๐ŸŒŸ </p> ## ๐Ÿ”Ž Content - [Coding Convention](#Coding-convention) - [Swift Lint](#Swift-lint) - [App Life Cycle](#app-life-cycle) - [View Life Cycle](#view-life-cycle) - [Design Pattern](#Design-Pattern) - [Adaptor](#Adaptor) - [Coordinator](#Coordinator) - [Delegation](#Delegation) - [Dependency Injection](#Dependency-Injection) - [Factory](#Factory) - [Observer](#Observer) - [KVO](#KVO) - [KVC](#KVC) - [Singleton](#Singleton) - [Code Structuring](#code-structuringarchitecture) - [MVC](#MVC) - [MVP](#MVP) - [MVVM](#MVVM) - [VIPER](#VIPER) - [The Composable Architecture(TCA)](#The-Composable-Architecture) - [Reducer](#Reducer) - [Repository Pattern](#Repository-Pattern) - [UIDesign](#UIDesign) - [HIG](#highuman-interface-guidelines) - [SwiftUI](#SwiftUI) - [Useful Cheat Sheet for SwiftUI](#Useful-Cheat-Sheet-for-SwiftUI) - [UIdesign Inspiration](#UIdesign-Inspiration) - [Vector Graphic Editors](#Vector-Graphic-Editors) - [Design Collaboration](#Design-Collaboration) - [Design Tools](#Design-Tools) - [Useful Sites](#useful-sites) - [Screen Layout Programmatically](#screen-layout-programmatically) - [Helper](#Helper) - [Email, Message, Call](#email-message-call) - [Network Layer](#Network-Layer) - [Image Picker](#Image-Picker) - [File Manager](#File-Manager) - [Video Downloader](#Video-Downloader) - [Image Downloader](#Image-Downloader) - [Location Manager](#Location-Manager) - [Local Notification Manager](#local-notification-manager) - [API](#API) - [JSON](#JSON) - [JSONDecoder](#JSONDecoder) - [JSONSerialization](#JSONSerialization) - [NotificationCenter](#NotificationCenter) - [UserDefaults](#UserDefaults) - [How to find documentDirectory](#How-to-find-documentDirectory) - [Store Object](#Store-Object) - [Core Data](#Core-Data) - [Core Data Stack](#Core-Data-Stack) - [Set Up Core Data](#Set-Up-Core-Data) - [Core Data Usage](#Core-Data-Usage) - [Codegen](#codegen) - [Entities](#Entities) - [Attributes](#Attributes) - [Relationships](#Relationships) - [Delete Rules](#Delete-Rules) - [Store Data](#Store-Data) - [Load Data](#Load-Data) - [Update Data](#Update-Data) - [Delete Data](#Delete-Data) - [Core Bluetooth](#Core-Bluetooth) - [Third Party Library](#Third-Party-Library) - [Dependency/Package Manager](#Dependency/Package-Manager) - [CocoaPods](#CocoaPods) - [Carthage](#Carthage) - [Swift Package Manager](#Swift-Package-Manager) - [Recommend Library](#Recommend-Library) - [Localization](#Localization) - [Usage](#Localization-Usage) - [Useful for Localization](#Useful-for-Localization) - [Accessibility](#Accessibility) - [USage](#Accessibility-Usage) - [GCD](#GCD) - [DispatchQueue](#DispatchQueue) - [Thread Safety](#thread-safety) - [DispatchGroup](#DispatchGroup) - [DispatchWorkItem](#DispatchWorkItem) - [Operation](#operation) - [OperationQueue](#operationQueue) - [Thread Sanitizer](#Thread-Sanitizer) - [Testing](#Testing) - [Five Factor Testing](#Five-Factor-Testing) - [Test Double](#Test-Double) - [Useful Debugging Technique](#Useful-Debugging-Technique) - [TDD](#TDD) - [Reduce Build Time](#Reduce-Build-Time) - [Check build time in Xcode](#Check-build-time-in-Xcode) - [BDD](#BDD) - [Code Coverage](#Code-Coverage) - [Integration Testing](#Integration-Testing) - [Unit Testing](#Unit-Testing) - [UI Testing](#UI-Testing) - [Robot Testing](#Robot-Testing) - [Snapshot Testing](#snapshot-testing) - [TestFlight](#testflight) - [CI/CD](#cicd) - [Fastlane](#Fastlane) - [Jenkins](#Jenkins) - [Jira](#Jira) - [CircleCI](#CircleCI) - [Codemagic](#Codemagic) - [Xcode Cloud](#xcode-cloud) - [Tuist](#Tuist) - [In App Purchase(IAP)](#In-App-PurchaseIAP) - [Notification](#Notification) - [Local Notification](#Local-Notification) - [Remote Notification](#Remote-Notification) - [APNs](#APNS) - [Set Up APNs](#Set-Up-APNs) - [APNs Usage](#APNs-Usage) - [FRP](#FRP) - [Rxswift](#Rxswift) - [Combine](#Combine) - [RxCombine](#Rxcombine) - [Security](#Security) - [Checklist For App Security](#Checklist-For-App-Security) - [Keychain](#Keychain) - [SSL Pinning](#SSL-Pinning) - [Code Obfuscation](#Code-Obfuscation) - [Cryptography](#Cryptography) - [Biometric Access](#Biometric-Access) - [Face ID & Touch ID](#face-id--touch-id) - [Objective-C](#Objective-C) - [Bridging Header](#Bridging-Header) - [Error Search](#Error-Search) - [Useful Stuff](#Useful-Stuff) - [Useful Blogs for iOS Developers](#Useful-Blogs-for-iOS-Developers) - [How to submit your app to the AppStore](#how-to-submit-your-app-to-the-appstore) - [iOS Version Adoption Tracker](#iOS-version-adoption-tracker) - [Online Swift Playground](#Online-Swift-Playground) - [Show Preview in UIKit(Build UI with Code Base)](#show-preview-in-uikitbuild-ui-with-code-base-----) - [Compare Changes in Swift Version](#Compare-Changes-in-Swift-Version) - [Managing Xcode Space](#Managing-Xcode-Space) - [Roadmap for iOS Developer](#Roadmap-for-iOS-Developer) - [Vim in Xcode](#use-vim-in-xcode) - [Write README.md](#write-readmemd) ## Coding convention set of guidelines for a specific programming language that recommend programming style ### Swift Style Guide - [Swift Style Guide](https://github.com/linkedin/swift-style-guide) ### Swift Lint The way of force you to adapt coding convention >otherwise project build will **FAILED** - [Swift Lint](https://github.com/realm/SwiftLint) apply for all project:+1: ```swift if which swiftlint >/dev/null; then swiftlint else echo "error: SwiftLint not installed, download from https://github.com/realm/SwiftLint" exit 1 fi ``` put .yml file into root folder and apply following code in Build Phases **You can modify(delete) SwiftLint Option with opening .yml file** > Shift + Command + . will show the hidden file <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/swiftLintChange.png"> ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | Clean Code: A Handbook of Agile Software Craftsmanship | Robert C. Martin | | The Pragmatic Programmer Your Journey to Mastery, 20th Anniversary Edition| Andrew Hunt David Hurst Thomas | ## App Life Cycle [iOS App Life Cycle](https://medium.com/@neroxiao/ios-app-life-cycle-ec1b31cee9dc) <p align="right"> <a href="#-content">Back to Content</a> </p> ## View Life Cycle <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/iOSViewLifeCycle.png" width="70%" height="70%"/> - viewDidLoad - viewWillAppear - viewWillLayoutSubviews - viewDidLayoutSubviews - viewDidAppear - viewWillDisappear - viewDidDisappear [iOS View Controller Life Cycle](https://medium.com/good-morning-swift/ios-view-controller-life-cycle-2a0f02e74ff5) <p align="right"> <a href="#-content">Back to Content</a> </p> ## Design Pattern Check [this](https://refactoring.guru/design-patterns/swift) website for design pattern in Swift ## Adaptor Adapter pattern is a structural design pattern that is useful for composing classes and objects into a larger system. ```swift protocol Target { func request() } class Adaptee { func specificRequest() {} } class Adapter: Target { let adaptee: Adaptee init(adaptee: Adaptee) { self.adaptee = adaptee } func request() { adaptee.specificRequest() } } ``` - [โ€˜Adapterโ€™ Pattern in Swift](https://levelup.gitconnected.com/adapter-pattern-in-swift-b6403cfa0a78) - [Swift adapter design pattern](https://theswiftdev.com/swift-adapter-design-pattern/) - [Adapter in Swift](https://refactoring.guru/design-patterns/adapter/swift/example) ## Coordinator - [Leverage the Coordinator Design Pattern in Swift 5](https://betterprogramming.pub/leverage-the-coordinator-design-pattern-in-swift-5-cd5bb9e78e12) ## Delegation Delegation is a design pattern that enables a class to hand off (or โ€œdelegateโ€) some of its responsibilities to an instance of another class. ### Example Create a protocol ```swift protocol SomeProtocol: AnyObject { func reload() } ``` Create a delegate ```swift weak var delegate: SomeProtocol? ``` You can check the code using delegation pattern [here](https://github.com/jphong1111/Unsplash_Clone/blob/main/Unsplah_Clone/Module/MainMenu/AccountScreenModule/ViewModel/AccountViewModel.swift#L35) - [Delegation in Swift Swift by Sundell](https://www.swiftbysundell.com/articles/delegation-in-swift/) - [Delegation in Swift Explained](https://learnappmaking.com/delegation-swift-how-to/) - [Delegation Pattern in Swift 5.1](https://medium.com/@nimjea/delegation-pattern-in-swift-4-2-f6aca61f4bf5) ## Dependency Injection Dependency injection is a pattern that can be used to eliminate the need for singletons in a project 1. Raise Transparency 2. Improve Testability ### Type of Dependency Injection **1. initializer injection** ``` swift class DataManager { private let serializer: Serializer init(serializer: Serializer) { self.serializer = serializer } } ``` **2. property injection** ```swift import UIKit class ViewController: UIViewController { var requestManager: RequestManager? } ``` **3. method injection** ```swift import Foundation class DataManager { func serializeRequest(request: Request, withSerializer serializer: Serializer) -> Data? { ... } } ``` [Nuts and Bolts of Dependency Injection in Swift](https://cocoacasts.com/nuts-and-bolts-of-dependency-injection-in-swift) ## Factory Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes. - [Factory Method in Swift](https://refactoring.guru/design-patterns/factory-method/swift/example) - [The Factory Pattern using Swift](https://stevenpcurtis.medium.com/the-factory-pattern-using-swift-b534ae9f983f) ## Observer Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. - Observer - An object that wishes to be notified when the state of another object changes. - Subject (Observable) - An object that maintains a list of observers, and inform them of state changes usually by calling one of their methods. An observable slightly differs in this in that it is just a function that sets up an observation. - Subscribe - An observer lets a subject know that it wants to be informed of changes through a process called subscribing. <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/observer.png" /> Check following sites - [swiftbysundell](https://www.swiftbysundell.com/articles/observers-in-swift-part-1/) TBD ### KVO KVO stands for Key Value Observing - [Apple Developer Site](https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift) - [KVO (Key Value Observing) in Swift](https://medium.com/@abhishek1nacc/kvo-key-value-observing-in-swift-65d05ac2d240) ### KVC [KVO vs KVC](https://medium.com/hackernoon/kvo-kvc-in-swift-12f77300c387) We are using KVC in Storyboard! <p align="right"> <a href="#-content">Back to Content</a> </p> ## Singleton singleton pattern is to ensure only one instance of a class is alive at any one time. ```swift class SingletonPattern { static let manager = SingletonPattern() private init() {} } ``` <p align="right"> <a href="#-content">Back to Content</a> </p> ## Code Structuring(Architecture) ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | Advanced iOS App Architecture : Real-world app architecture in Swift | raywenderlich Tutorial Team | | Clean Architecture: A Craftsman's Guide to Software Structure and Design | Robert Martin | ## Clean Architecture <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/Clean_Architecture.png"> [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) ## MVC MVC pattern stands for Model - View - Controller <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/MVCModel.png"> - Model - Model take care of storing data. - View - View renders the data for users - Controller - Controller modifies the View, accepts user input and interacts directly with the Model. And take care of view logic and business logic. ## MVP <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/MVPdesign.png" /> ## MVVM MVVM patterns stand for Model - View - ViewModel ### MVC vs MVVM <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/MVVMvsMVC.png" width = "60%" height = "60%"> - Model โ€“ Which holds the application data - View โ€“ It displays the data that is stored in model. These are visual elements through which a user interacts. These are subclasses of UIView - View Model โ€“ Transform model information/data and it interacts with controller or view to display those informations. - Controller class โ€“ It will be there but the responsibility of view business logic has been removed and give to view model > You can check App example of using MVVM [here](https://github.com/jphong1111/Unsplash_Clone) ## VIPER <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/Viper.png"> - View - Displays what it is told to by the Presenter and relays user input back to the Presenter. - Interactor - Contains the business logic as specified by a use case. - Presenter - contains view logic for preparing content for display (as received from the Interactor) and for reacting to user inputs (by requesting new data from the Interactor). - Entity - contains basic model objects used by the Interactor. - Routing - contains navigation logic for describing which screens are shown in which order. [Getting Started with the VIPER Architecture Pattern](https://www.raywenderlich.com/8440907-getting-started-with-the-viper-architecture-pattern) # The Composable Architecture The Composable Architecture is a library for building applications in a consistent and understandable way, with composition, testing, and ergonomics in mind <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/SCA.png"> - [Composable Architecture @ Point Free](https://www.pointfree.co/collections/composable-architecture) - [The Composable Architecture GitHub](https://github.com/pointfreeco/swift-composable-architecture) - [The Composable Architecture โ€” One of the Best-Suited Architectures for SwiftUI](https://medium.com/swlh/the-composable-architecture-one-of-the-best-suited-architectures-for-swiftui-35bfc5102b83) ```swift // example will update here ``` ## Reducer A reducer describes how to evolve the current state of an application to the next state, given an action, and describes what Effects should be executed later by the store, if any. - [Reducer in TCA](https://pointfreeco.github.io/swift-composable-architecture/Reducer/) <p align="right"> <a href="#-content">Back to Content</a> </p> ## Repository Pattern [The Repository and Unit of Work Patterns](https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application) ## UIDesign ## HIG(Human Interface Guidelines) - [HIG](https://developer.apple.com/design/human-interface-guidelines/) - [Apple UI Kit](https://developer.apple.com/documentation/uikit) - [iOS Design Guide](https://ivomynttinen.com/blog/ios-design-guidelines) ## SwiftUI SwiftUI is a user interface toolkit that lets us design apps in a **declarative way(Declarative syntax)**. ## Useful Cheat Sheet for SwiftUI - [Fucking SwiftUI](https://fuckingswiftui.com/) Cheat Sheet for SwiftUI - [Gosh Darn SwiftUI](https://goshdarnswiftui.com/) Cheat Sheet for SwiftUI - [SimpleBoilerplates/SwiftUI-Cheat-Sheet](https://github.com/SimpleBoilerplates/SwiftUI-Cheat-Sheet) TBA <p align="right"> <a href="#-content">Back to Content</a> </p> ## iOS icon - [SF Symbols](https://developer.apple.com/sf-symbols/) Download SF Symbols2 for more icons! - [icon8](https://icons8.com/) You can download icons imge for your **APP** - [appicon](https://appicon.co/) generate the app icon size - [flaticon](www.flaticon.com) Free icons download ## UIdesign Inspiration - [Dribble](https://dribbble.com/) - [Pinterest](https://pinterest.com/) - [Behance](https://www.behance.net/) - [Pttrns](https://pttrns.com/)๐Ÿ‘ - [Awwwards](https://www.awwwards.com/) - [Flickr](http://www.flickr.com/) - [Mobbin](https://mobbin.design/dictionary)๐Ÿ‘ ## Vector Graphic Editors - [Figma](https://www.figma.com/) - [Sketch](https://www.sketch.com/) - [Adobe XD](https://www.adobe.com/products/xd.html) ## Design Collaboration Tools - [Sympli](https://sympli.io/) - [Zepline](https://zeplin.io/) ## Design Tools - [DetailsPro](https://detailspro.app) You can design with SwiftUI free ๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Useful Sites - [HEX Color Picker](https://imagecolorpicker.com/) Good for picking color as Hex ๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Screen Layout Programmatically TBA <p align="right"> <a href="#-content">Back to Content</a> </p> ## Helper All files are resuable files and protocol oriented. **Just Copy and Paste inside your project and use it!!** ๐Ÿ‘ **These helper files are not with Error Handling! careful at use** ## Email, Message, Call You can check the file in the follow link - [Email, Message, Call](https://github.com/jphong1111/Useful_Swift/blob/main/Helper/ConversationHandler/ConversationManager.swift) ### Usage import MessageUI first ```swift import MessageUI ``` Then use it > Don't forget to extend the mail, message delegate to your ViewController! ```swift lazy var conversation = ConversationManager(presentingController: self, mailDelegate: self, messageDelegate: self, viewController: self) @IBAction private func sendEmail(_ sender: UIButton) { conversation.sendEmail(feedback: MailFeedback(recipients: ["[email protected]"], subject: "FeedBack", body: "Write feedback here")) } @IBAction private func sendMessage(_ sender: UIButton) { conversation.sendMessage(feedback: MessageFeedBack(recipients: ["1111111111"], body: "Type here")) } @IBAction private func startCall(_ sender: UIButton) { conversation.makeCall(number: "1111111111") } ``` Good To GO ๐Ÿ‘๐Ÿ‘๐Ÿ‘ > See Example [here](https://github.com/jphong1111/ImageMessageHandler_DemoApp) <p align="right"> <a href="#-content">Back to Content</a> </p> ## Network Layer - [Network Layer](https://github.com/jphong1111/Useful_Swift/tree/main/Helper/Network%20Layer) ### Usage First, set the base URL in **EndPointType file** > Don't forget to put your API key in it! ```swift var baseURL: URL { guard let url = URL(string: "https://api.openweathermap.org/data/2.5/") else { fatalError("baseURL could not be configured.") } return url } ``` then make a instance of router.swift file in your code ```swift private let router = Router<YourAPI>() ``` for **YourAPI part**, simply create a new **enum** with cases about specific api URL > It will make your router more dynamic! > Don't forget extension to EndPointType! ```swift enum YourAPI { case first(country: String) case second(time: Int) case third(name: String) } extension YourAPI: EndPointType { var path: String { switch self { case .first(let country): return "\(country).json" case .second(let time): return "\(time).json" case .third(let name): return "\(name).json" } } } ``` then, use it like this ```swift router.request(.first(country: London)) { [weak self] (results: Result<CountryWeather, AppError>) in guard let self = self else { return } switch results { case .success(let data): // insert your modifications! case .failure(let error): // insert your modifications! print(error) } } ``` > **CountryWeather should be a model with Decodable** If you want to see how can I use Network Layer in Project, check [this](https://github.com/jphong1111/Unsplash_Clone/tree/main/Unsplah_Clone/ReusableComponent/NetworkLayer) This reusable network layer files for referenced from [here](https://medium.com/flawless-app-stories/writing-network-layer-in-swift-protocol-oriented-approach-4fa40ef1f908) > Also [Alamofire](https://github.com/Alamofire/Alamofire) will be a great option for Network Layer! ## Image Picker - [Image Picker](https://github.com/jphong1111/Useful_Swift/blob/main/Helper/ImagePickerHandler/ImagePicker.swift) ### Usage Copy and Paste in your project and then declare Image Picker object inside your project ```swift lazy var imagePicker = ImagePicker(presentationController: self, delegate: self) ``` Then, extend ImagePickerDelegate to your viewController ```swift extension ViewController: ImagePickerDelegate { func didSelect(image: UIImage?) { self.yourImageView.image = image self.dismiss(animated: true, completion: nil) } } ``` Good To GO ๐Ÿ‘๐Ÿ‘๐Ÿ‘ > See Example [here](https://github.com/jphong1111/ImageMessageHandler_DemoApp) ## File Manager - [File Manager](https://github.com/jphong1111/awesome-ios-developer/blob/main/Helper/FileManageHandler/FileManager.swift) ### Usage Copy and Paste in your project ```swift let readData = FileManageHelper.manager.readFile(filename: fileNameTextField.text ?? "", type: extensionTextField.text ?? "") resultTextField.text = readData ``` > File Manager are wrote with singleton pattern, therefore no need to declare in side your code! Good To GO ๐Ÿ‘๐Ÿ‘๐Ÿ‘ ## Video Downloader - [Video Downloader](https://github.com/jphong1111/awesome-ios-developer/blob/main/Helper/VideoDownloadHandler/VideoDownloadManager.swift) ## Usage Make an object of VideoManager inside your code ```swift let videoManager = VideoManager() ``` use downloadVideoLinkAndCreateAsset function to start download with entering URL ```swift self.videoManager.downloadVideoLinkAndCreateAsset(text) ``` Good To GO ๐Ÿ‘๐Ÿ‘๐Ÿ‘ ## Image Downloader There is no file for Image Downloader. To download images into device, only thing is this ```swift if let data = try? Data(contentsOf: urls), let image = UIImage(data: data) { UIImageWriteToSavedPhotosAlbum(image, nil, nilil) } ``` Just **change urls into your image URL** > UIImageWriteToSavedPhotosAlbum will take care it to download to device. > For more info go [here](https://www.hackingwithswift.com/example-code/media/uiimagewritetosavedphotosalbum-how-to-write-to-the-ios-photo-album) Good To GO ๐Ÿ‘๐Ÿ‘๐Ÿ‘ ## Location Manager - ~~[Location Manager](https://github.com/jphong1111/Useful_Swift/tree/main/Helper/LocationHandler/LocationManager.swift)~~ Currently Working <p align="right"> <a href="#-content">Back to Content</a> </p> ## Local Notification Manager - [Local Notification Manager](https://github.com/jphong1111/awesome-ios-developer/blob/main/Helper/LocalNotificationHelper/LocalNotificationManager.swift) <p align="right"> <a href="#-content">Back to Content</a> </p> # API API(Application Programming Interface) is an interface that defines interactions between multiple software applications or mixed hardware-software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc. ## Various API Site - [rapidAPI](https://www.rapidapi.com) - [AnyAPI](https://any-api.com/) - [Programmableweb](https://www.programmableweb.com/) <p align="right"> <a href="#-content">Back to Content</a> </p> ## JSON JSON is a language-independent data format > Which is relative with **KEY - VALUE** pair ```json { "main": [ { "title": "example1", "body": "body1" }, { "title": "example2", "body: "body2" } ] } ``` ### JSON parser extension for Chrome This extension makes JSON more structable [JSON parser pro](https://chrome.google.com/webstore/detail/json-viewer-pro/eifflpmocdbdmepbjaopkkhbfmdgijcc) **FREE** :+1: ## JSONDecoder To use JSONDecoder in swift, you have to define the model to be Codable or Decodable ```swift public typealias Codable = Decodable & Encodable ``` > Decodable can only decode the json data. Can't encoded json file!! ```swift struct User: Codable { var firstName: String var lastName: String var country: String enum CodingKeys: String, CodingKey { case firstName = "first_name" case lastName = "last_name" case country } } ``` > To avoid snake_case in swift, use CodingKeys or JSONDecoder.KeyDecodingStrategy To use JSONDecoding, declare JSONDecoder and use decode() function ```swift do { let data = try JSONDecoder().decode(T.self, from: unwrappedData) completionOnMain(.success(data)) } catch { print(error) completionOnMain(.failure(.parseError)) } ``` T.self -> Model(Struct) of the data that you want to decode > data will decoded to form of T unwrappedData -> Input actual data from file or server > This should be a Data Type!! ## JSONSerialization JSONSerialization is a old way of decode the JSON file. > Apple populated Codable since Swift 4 ### Example Example of number.json data ```json { "number": [ { "name": "Dennis", "number": "111-222-3333" }, { "name": "Jenny", "number": "444-555-6666" }, { "name": "Ben", "number": "777-888-9999" } ] } ``` Here is a example of JSONSerialization with actaul JSON file in project folder > Otherwise you can use URL! ```swift private func populateDataFromJson() { if let path = Bundle.main.path(forResource: "NumberData", ofType: "json") { do { let dataJson = try Data(contentsOf: URL(fileURLWithPath: path)) let jsonDict = try JSONSerialization.jsonObject(with: dataJson, options: .mutableContainers) if let jsonResults = jsonDict as? [String: Any], let results = jsonResults["number"] as? [[String: Any]] { results.forEach { dict in // simply appended to list(array) self.phoneNumberList.append(PhoneNumber(name: dict["name"] as? String ?? "", number: (dict["number"] as? String ?? ""))) self.phoneNumberListClone.append(PhoneNumber(name: dict["name"] as? String ?? "", number: (dict["number"] as? String ?? ""))) } } } catch { print(error.localizedDescription) } } } ``` > .mutableContainers allows to working like a array and dictionary type ### JSON Parser Library This library provide JSON parsing - [SwifyJSON](https://github.com/SwiftyJSON/SwiftyJSON) <p align="right"> <a href="#-content">Back to Content</a> </p> ## NotificationCenter A notification dispatch mechanism that enables the broadcast of information to registered observers. - [NotificationCenter Apple Document](https://developer.apple.com/documentation/foundation/notificationcenter) - [How To: Using Notification Center In Swift](https://learnappmaking.com/notification-center-how-to-swift/) <p align="right"> <a href="#-content">Back to Content</a> </p> ## UserDefaults The UserDefaults class provides a programmatic interface for interacting with the defaults system. Check [Apple Document](https://developer.apple.com/documentation/foundation/userdefaults) for more info > UserDefaults has to have **key-value** pair ### When do we use UserDafaults - User information, like name, email address, age, occupation - App settings, like user interface language, app color theme or โ€œdetailed vs. simple UIโ€ - Flags, more on this later - If store data is small ## How to find documentDirectory Put this line of code inside of your project ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last ?? "") return true } ``` <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/DocumentPath.png" /> simply move into that path and you can find the documentDirectory of your Application > if Library is not shown up, just do **Shift + Command + .** to show hidden files in your folder <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/UserDefaultPlistPath.png" /> ## Usage As you can see in the below, intArray will stored inside the device through UserDefaults(), so that if device is shut down, changed value wil be stored in device. ```swift class ViewController: UIViewController { var intArray = [1,2,3,4,5] let defaults = UserDefaults() override func viewDidLoad() { super.viewDidLoad() intArray = defaults.array(forKey: "IntArray") as! [Int] } @IBOutlet weak var textField: UILabel! @IBAction private func isClicked(_ sender: UIButton) { intArray.append(6) defaults.set(intArray, forKey: "IntArray") textField.text = "\(intArray)" } } ``` You can your plist file like this! <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/UserDefaultPlist.png" /> Declare Userdefault like this! ```swift let defaults = UserDefaults.standard ``` > **standard** allows to access from anywhere inside device **With using set function, you can set userdefaults** <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/UserDefaultSet.png" width = "60%" height = "60%"/> **Also these function will allow to get a data from plist** <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/UserDefaultGet.png" width = "60%" height = "60%"/> ## Store Object [Store Object](https://stackoverflow.com/questions/29986957/save-custom-objects-into-nsuserdefaults) **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> # Core Data [Everything Core Data](https://metova.com/everything-core-data/) Use Core Data to save your applicationโ€™s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. **Core Data in Swift is using SQLite as DEFAULT** <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/DataStoreInSwift.png" width = "50%" height = "50%"/> > Image From London App Brewery ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | Core Data by Tutorials: iOS 12 and Swift 4.2 Edition | raywenderlich Tutorial Team | ## Core Data Stack - [The Core Data Stack](https://www.raywenderlich.com/books/core-data-by-tutorials/v7.0/chapters/3-the-core-data-stack) <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/Core_Data_Stack.png" width = "70%" height = "70%"/> - **NSManagedObject** - This is a base class of all the core data model object. This provides the schema of our database table. This is used to store model data in our application. KVO and KVC compliant. It can notify any changes that are done on its properties if any object is listening. - **NSManagedObjectContext** - Most important class. This is the place where you do all the computations. You can think this as a scratch pad where you do all the operations realated to core data (CRUD). It's an object which you can use to manipulate and track any changes done to manage object. All the changes done on a context object will be held until and unless you are discarding or writing those changes permaneently to persistntent storage. - **NSPersistentStoreCoordinator** - The main functionality is to provide a communication between context and persistent store. - NSPersistentStore - They are the stores in which the data are being saved. These includes SQLite, In-Memory, Binary, XML(the XML store is not available on iOS). - NSPersistentContainer - This contains the whole core data stacks. ## Set Up Core Data Simply Click Core Data check box when you create a new project <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/AddCoreData.png" width = "50%" height = "50%"/> If you want to attach Core Data in exsiting project Create **Data Model** file first <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/AddDataModel.png" width = "50%" height = "50%"/> Then import CoreData inside your **AppDelegate.swift** file ```swift import CoreData ``` And Copy and Paste this lines of code inside your **AppDelegate.swift** file ```swift // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Your DataModel file name") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } ``` Don't forget to change it ```swift let container = NSPersistentContainer(name: "Your DataModel file name") ``` And goto **SceneDelegate.swift** file, copy below lines of code and replace yours ```swift func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. // Save changes in the application's managed object context when the application transitions to the background. (UIApplication.shared.delegate as? AppDelegate)?.saveContext() } ``` If your target is **below iOS13**, put this line of code in side your **applicationWillTerminate** of **AppDelegate.swift** file ```swift self.saveContext() ``` ## Core Data Usage Once you create your DataModel file, you can simply create a **Entity(Class)** and **Attributes(Properties)** And then, change the type of attributes in inspector like this <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/DataModelAttribute_inspector.png"/> Once you create your own Entities & Attributes, go to Inspector and change Module to **CurrentProductModule** <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/DataModelAttributes.png"/> > If you didn't set it, thats fine, but if you are working in big project, then you need to set it. Otherwise this can occurs some error. ## Codegen As you can see in above, there are three options - Manual/None - Swift didn't generate CoreDataClass, CoreDataProperties files so that you have to create yourself **(full control)** - Class Definition - Swift will generate CoreDataClass, CoreDataProperties files. **(No control)** - Category/Extension - Swift will generate only Extension file **(Some Control)** CoreDataClass, CoreDataProperties are located in below > /Users/dennis/Library/Developer/Xcode/DerivedData/CoreDataUserDefaultPractice-hisefjfyuvglrjekndpftwazftug/Build/Intermediates.noindex/CoreDataUserDefaultPractice.build/Debug-iphonesimulator/CoreDataUserDefaultPractice.build/DerivedSources/CoreDataGenerated/CoreDataUserDefaultPractice And CoreDataClass, CoreDataProperties are looking like this, <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/CoreDataClass_Properties.png"/> > If your code can run it but didn't get your Entities, **Rebuild it or Restart your Xcode** **The reason that files divided into two files is that one for writing Business Logic, one for Properties** ## Entities An entity represents a table in your database. It is the blueprint for the NSManagedObject subclass instances that you will create and use throughout your application. ## Attributes Attributes are properties of your object. They translate to a column in your database table and a property in your managed object. You can choose from a variety of primitive values that the database has to offer such as a string, integer, or date. ## Relationships A relationship describes how one entity relates to another. Two important aspects of this are the cardinality and the deletion rule ### Cardinality - **One-to-many** - Lets say that each Department has a group of Employees that can only work for a single Department. This would be a โ€œone-to-manyโ€ relationship since each Department could have many Employees and each Employee can only work for one Department. - **Many-to-many** - If a single Employee could work for multiple Departments, then our Department/Employee relationship would be โ€œmany-to-manyโ€ because each Department could have many Employees and each Employee could work for multiple Departments. ### Delete Rules [Core Data Relationships and Delete Rules](https://cocoacasts.com/core-data-relationships-and-delete-rules) - **No Action** - Do nothing to the object at the destination of the relationship. For example, if you delete a department, leave all the employees as they are, even if they still believe they belong to that department. - **Nullify (Default)** - Set the inverse relationship for objects at the destination to null. For example, if you delete a department, set the department for all the current members to null. This only makes sense if the department relationship for an employee is optional, or if you ensure that you set a new department for each of the employees before the next save operation. - **Cascade** - Delete the objects at the destination of the relationship. For example, if you delete a department, fire all the employees in that department at the same time. - **Deny** - If there is at least one object at the relationship destination, then the source object cannot be deleted. For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere (or fired!) otherwise the department cannot be deleted. ## Store Data Declare context as a global variable ```swift let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext ``` > Get viewContext that we defined in AppDelegate.swift file Simply you can use this code to save your data to CoreData ```swift func saveItem() { do { try context.save() } catch { print("Error Saving Context: \(error.localizedDescription)") } } ``` > Use it wherever you want Data can be find if you print the path ```swift print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)) ``` <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/CoreDataSQLite.png" /> > You can check Entities, Properties inside that file ## Load Data Refer this code and apply it to your code wherever you want to reload it ```swift func loadItem() { let request: NSFetchRequest<Item> = Item.fetchRequest() do { itemArray = try context.fetch(request) } catch { print("Load Item Error: \(error.localizedDescription)") } } ``` > Item will be your Entity, itemArray will be your Entity object > Don't forget to import **CoreData** ## Update Data Simply use setValue function so that you can update your value in DB ```swift itemArray[0].setValue(<#T##value: Any?##Any?#>, forKey: <#T##String#>) ``` > if you are using TableView or CollectionView, change 0 to indexPath.row ## Delete Data Simply use delete function in context ```swift context.delete(itemArray[0]) ``` > change number for dynamic! **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Core Bluetooth - [Introduction to BLE Mobile Development [iOS]](https://www.novelbits.io/intro-ble-mobile-development-ios/) - [Core Bluetooth Tutorial for iOS: Heart Rate Monitor](https://www.raywenderlich.com/231-core-bluetooth-tutorial-for-ios-heart-rate-monitor) - [Getting Started with Core Bluetooth](https://ditto.live/blog/posts/getting-started-with-core-bluetooth) **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> # Third Party Library Third Party Library saves you time as you do not need to develop the functionality that the library provides. [SHOULD DEVELOPERS USE THIRD-PARTY LIBRARIES?](https://www.scalablepath.com/blog/third-party-libraries/) > Relying on library(abused) is not a good idea - [awesome ios github](https://github.com/vsouza/awesome-ios) Contains all the popular libraries in Swift:+1: - [awesome swift site](https://swift.libhunt.com/) You can broswe popular libraries related to iOS - [Explore Swift](https://kandi.openweaver.com/explore/swift) Discover & find a curated list of popular & new libraries, top authors and trending discussions on kandi. ## Dependency/Package Manager A package manager is a tool that simplifies the process of working with code from multiple sources. - Centralised hosting of packages and source code with public server with access to developers or contributors - Download the source code at the run time, so that we donโ€™t need to include it in the repository - Link the source code to our working repository by including source files [More Info](https://medium.com/xcblog/swift-dependency-management-for-ios-3bcfc4771ec0) ## CocoaPods Download cocoapods ```bash $ sudo gem install cocoapods ``` After finish download cocoapods, go to your root folder of your project and make pod file ```bash $ pod init ``` Click into your pod file and edit Image After finish editing, update your pod file ```bash $ pod install ``` **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Carthage - [Getting started with Carthage to manage dependencies in Swift and iOS](https://www.twilio.com/blog/2016/05/getting-started-with-carthage-to-manage-dependencies-in-swift-and-ios.html) - [Carthage Tutorial: Getting Started](https://www.raywenderlich.com/7649117-carthage-tutorial-getting-started) - [Carthage](https://github.com/Carthage/Carthage) First, install Carthage through HomeBrew ```bash $ brew install carthage ``` if already installed, check if there is latest version. ```bash $ carthage update ``` Then, go to your root project folder, and do this ```bash touch Cartfile ``` open cartfile, put library that you want to use ```bash github "<owner>/<repo>" == <version> ``` Example ```bash github "Alamofire/Alamofire" == 4.9.0 github "Alamofire/AlamofireImage" ~> 3.4 ``` And then, do this ```bash carthage update --platform iOS ``` After finish downloading it, go to **Xcode -> Build phases** TBD **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Swift Package Manager <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/SwiftPackageManager.png" width = "50%" height = "50%"/> Enter url of library that you want to install <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/SwiftPackageManager2.png" width = "50%" height = "50%"/> <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/SwiftPackageManager3.png" width = "50%" height = "50%"/> **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Recommend Library - SDWebImage - Downloading and caching images from the web - Kingfisher - Downloading and caching images from the web - Hero - Various kind of animation with using Segue - Alamofire - Network Layer tool - Moya - Network abstraction layer written in Swift - RxSwift - Reactive Programming in Swift - SwiftyJSON - JSON parsar Helper - IQKeyboardManager - Easy to manage Keyboard settings - SnapKit - Swift Auto Layout DSL for iOS - Charts - Make Beutiful Charts in your App - Quick/Nimble - Testing Library + Asynchronous tests purpose - Periphery - A tool to identify unused code in Swift Projects - ReactorKit - A framework for a reactive and unidirectional Swift application architecture - SwiftGen - SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images etc), to make them type-safe to use. - etc... <p align="right"> <a href="#-content">Back to Content</a> </p> ## Localization Localization is the process of making your app support other languages. (Base language is English) - [Localization Apple](https://developer.apple.com/localization/) - [Localization Apple Developer](https://developer.apple.com/documentation/xcode/localization) - [iOS Localization Tutorial](https://medium.com/lean-localization/ios-localization-tutorial-938231f9f881) - [Internationalizing Your iOS App: Getting Started](https://www.raywenderlich.com/250-internationalizing-your-ios-app-getting-started) ## Localization Usage First, you have to check **Use Base Internationalization** > It might be checked <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization.png" width="70%" height ="70%" /> > English is a base Language After you check it, add languages that you want to support in your App <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization2.png" width="70%" height ="70%" /> Then, you can check your language file like this! <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization3.png" width="70%" height ="70%" /> Create **Localizable.strings** file into your project > Unlike Swift, the .strings file requires that each line terminate with a **semicolon** > .strings file is where you can add translation data as **key-value** pairs <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization4.png" width="70%" height ="70%" /> In your .strings file, check localization button and choose language <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization5.png" /> And then add Key - Value pairs for tanslation <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization6.png" width="70%" height ="70%"/> To use localization, use **NSLocalizedString** to implement it ```swift NSLocalizedString(<#T##key: String##String#>, comment: <#T##String#>) ``` - [key] - put (key - value) pair that you created in .strings file - [comment] - It will help your translators significantly and result in better translations Simple example below ```swift @IBAction func showAlert() { let alertTitle = NSLocalizedString("Welcome", comment: "") let alertMessage = NSLocalizedString("How are you", comment: "") let cancelButtonText = NSLocalizedString("Cancel", comment: "") let signupButtonText = NSLocalizedString("Signup", comment: "") let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert) let cancelAction = UIAlertAction(title: cancelButtonText, style: UIAlertAction.Style.cancel, handler: nil) let signupAction = UIAlertAction(title: signupButtonText, style: UIAlertAction.Style.default, handler: nil) alert.addAction(cancelAction) alert.addAction(signupAction) present(alert, animated: true, completion: nil) } ``` After that, we have to test if localization is working correctly or not To test it, you can do either **Edit Scheme** or **New Scheme** go to Run section, and change **App Language** <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization7.png" /> After finish setting Scheme try to run it! <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization8.png" width="50%" height ="50%" /> <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/Internationalization9.png" width="50%" height ="50%" /> **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Useful for Localization - [localazy](https://localazy.com/) localization tool for iOS and macOS apps. Supporting .strings, .stringsdict, .plist and XLIFF files. - [locastudio](https://www.cunningo.com/locastudio/index.html) Analyze, review, and edit your app translations. <p align="right"> <a href="#-content">Back to Content</a> </p> ## Accessibility Accessibility is all about making the iPhone, iPod touch, and iPad work for as wide a range of people as possible. That can include the very young, the very old, people brand new to computers and mobile devices, and also people with disabilities and special needs. - Designing your app for accessibility makes it easier to write functional tests, whether youโ€™re using the UI Testing in Xcode. - Youโ€™ll also broaden your market and user base by making your app usable by a larger group. - Implementing accessibility in your app shows youโ€™re willing to go the extra mile for every user, and thatโ€™s a good thing. - [iOS Accessibility: Getting Started](https://www.raywenderlich.com/6827616-ios-accessibility-getting-started) ## Accessibility Usage To use accessibility, you have to enable this > For most UIKit classes, **the default is true, but for UILabel itโ€™s false** ```swift label.isAccessibilityElement = true ``` - accessibilityLabel - short description of control e.g. "Save" for button, "Rating" for label - accessibilityHint - helps the user to understand result of the action e.g "Save the documents" - accessibilityTraits - collection of constants that describe the type of control and/or hot it should be treated - accessibilityValue - Used to describe the value of a none-label UI component e.g. "50%" for progress bar <p align="right"> <a href="#-content">Back to Content</a> </p> ## GCD GCD(Grand Central Dispatch) is a low-level API for managing concurrent operations. It can help you improve your appโ€™s responsiveness by deferring computationally expensive tasks to the background. ## DispatchQueue An object that manages the execution of tasks serially or concurrently on your app's main thread or on a background thread. ### main We can say main is a serial queue ### global() We can say global is a concurrent queue ## Thread Safety [Concurrency & Thread Safety in Swift](https://medium.com/cubo-ai/concurrency-thread-safety-in-swift-5281535f7d3a) [Thread Safety in Swift](https://swiftrocks.com/thread-safety-in-swift) - **Dispatch Barrier** Use a barrier to synchronize the execution of one or more tasks in your dispatch queue. [Dispatch Barrier Apple Documentation](https://developer.apple.com/documentation/dispatch/dispatch_barrier) - **Dispatch Semaphore** [Dispatch Semaphore Apple Documentation](https://developer.apple.com/documentation/dispatch/dispatch_semaphore) - **NSLock** An object that coordinates the operation of multiple threads of execution within the same application. [NSLock](https://developer.apple.com/documentation/foundation/nslock) ## DispatchGroup [DispatchGroup Apple Document](https://developer.apple.com/documentation/dispatch/dispatchgroup) ## DispatchWorkItem The work you want to perform, encapsulated in a way that lets you attach a completion handle or execution dependencies. [DispatchWorkItem Apple Document](https://developer.apple.com/documentation/dispatch/dispatchworkitem) ## Operation [NSOperation Apple Documentation](https://developer.apple.com/documentation/foundation/nsoperation) ## OperationQueue [NSOperationQueue Apple Documentation](https://developer.apple.com/documentation/foundation/nsoperationqueue) <p align="right"> <a href="#-content">Back to Content</a> </p> # Thread Sanitizer Thread Sanitizer is a tool to identifies the potential thread-related corruption issues. And it is a good way to find the [Readers and Writers problem](https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem) in your application. <p align="right"> <a href="#-content">Back to Content</a> </p> ## How to Use Thread Sanitizer Go to this Option and Click **EDIT SCHEME...** ๐Ÿ‘ˆ <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/address_sanitizer.png"> And then go to **RUN** and check **THREAD SANITIZER** ๐Ÿ‘ˆ <img src="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/thread_sanitizer.png"> # Testing ## Five Factor Testing [Five Factor Testing](https://madeintandem.com/blog/five-factor-testing/) # Test Double **Test Double is a generic term for any case where you replace a production object for testing purposes.** - Mocks - Mocks are pre-programmered with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting. ```swift // exaple code will update ``` - Fake - Objects actually have working implementations, but usually take some shortcut which makes them not suitable for production. ```swift // exaple code will update ``` - Spies - Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent. ```swift // exaple code will update ``` - Stubs - Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. ```swift // exaple code will update ``` - Dummy - Objects are passed around but never actually used. Usually they are just used to fill parameter lists. ```swift // exaple code will update ``` # Useful Debugging Technique [Debugging in Xcode 13: Tips & Tricks (2022) โ€“ iOS](https://www.youtube.com/watch?v=ZAqnJQn7xp4&list=LL&index=5&ab_channel=iOSAcademy) ## 1. Change expression in debugging stage <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/debugging_expression.png" width = "80%" height = "80%"> Use ```expression``` at the beginning and then add whatever what you want to change into. It will change in debugging stage ๐Ÿ‘ ## 2. Symbolic Breakpoint If we want to know whenever hit certain function, use symbolic breakpoint # TDD **Test Driven Development** <img src="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/TDD.png" width="30%" height="30%"/> - [Why Test-Driven Development (TDD)](https://marsner.com/blog/why-test-driven-development-tdd/) ## Reduce Build Time Normally in complicated Application, build time for testing is crazy therefore, TDD spent most of time in building the project. Here are useful ways that we can reduce build time when we are working with TDD style. ### 1. tuist focus ### 2. Detach debugger in **Edit Scheme** un-check Debugger option <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/detach_debuger.png"/> ## Check build time in Xcode Enter below code in your terminal, be sure to **restart Xcode** after enter this code and **Command + B** ```shell defaults write com.apple.dt.Xcode ShowBuildOperationDuration YES ``` <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/show_build_time.png"/> # BDD <img src="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/BDDvsTDD.png" width="70%" height="70%"/> BDD improves communication between tech and non-tech teams and stakeholders. In BDD, tests are more user-focused and based on the systemโ€™s behavior. **Behavior Driven Development** - Encouraging collaboration across roles to build shared understanding of the problem to be solved - Working in rapid, small iterations to increase feedback and the flow of value - Producing system documentation that is automatically checked against the systemโ€™s behaviour ## Three Steps(Iterative) in BDD First, take a small upcoming change to the system โ€“ a User Story โ€“ and talk about concrete examples of the new functionality to explore, discover and agree on the details of whatโ€™s expected to be done. Next, document those examples in a way that can be automated, and check for agreement. Finally, implement the behaviour described by each documented example, starting with an automated test to guide the development of the code. - [Behaviour-Driven Development](https://cucumber.io/docs/bdd/) - [What is BDD? An Introduction to Behavioral Driven Development](https://blog.testlodge.com/what-is-bdd/) - [The WHY Behind the Code: BDD vs. TDD](https://saucelabs.com/blog/a-two-minute-bdd-overview) # Code Coverage Before start your Testing, add coverage will be a good option to show the result of test First, check code coverage <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/addCoverage1.png"/> Then, go to **EDIT SHEME**, check like this <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/addCoverage2.png"/> # Integration Testing [Integration Testing Swift by Sundell](https://www.swiftbysundell.com/articles/integration-tests-in-swift/) # Unit Testing [Unit Testing Swift by Sundell](https://www.swiftbysundell.com/basics/unit-testing/) ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | iOS Unit Testing by Example | Jon Reid | # UI Testing UI Testing, also known as GUI Testing is basically a mechanism meant to test the aspects of any software that a user will come into contact with. This usually means testing the visual elements to verify that they are functioning according to requirements โ€“ in terms of functionality and performance. UI testing ensures that UI functions are bug-free. - [UI Testing: A Detailed Guide](https://www.browserstack.com/guide/ui-testing-guide) - [Your first UITest in Swift](https://uxdesign.cc/your-first-uitest-in-swift-847bc5595c26) ## Robot Testing Robot testing is a test design pattern that makes you to create stable, readable, and maintainable tests. <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/robot_testing.png"/> - [Robot Pattern Testing for XCUITest](https://www.capitalone.com/tech/software-engineering/robot-pattern-testing-for-xcuitest/)๐Ÿ‘ - [Testing Robots- JAKE WHARTON](https://jakewharton.com/testing-robots/) - [Robot Testing Pattern - Overview](https://www.youtube.com/watch?v=ykM9AiYtCz4&ab_channel=HandstandTechnologies) ## Snapshot Testing ## TestFlight TestFlight makes it easy to invite users to test your apps and App Clips and collect valuable feedback before releasing your apps on the App Store. - [TestFlight Apple](https://developer.apple.com/testflight/) # CI/CD CI and CD stand for continuous integration and continuous delivery/continuous deployment - [Why is CI/CD important?](#https://www.synopsys.com/glossary/what-is-cicd.html) - [What is CI/CD? Continuous integration and continuous delivery explained](#https://www.infoworld.com/article/3271126/what-is-cicd-continuous-integration-and-continuous-delivery-explained.html) - [Whatโ€™s the difference between agile, CI/CD, and DevOps?](#https://www.synopsys.com/blogs/software-security/agile-cicd-devops-difference/) ## Fastlane The easiest way to build and release mobile apps. - [Fastlane](https://fastlane.tools/) - [fastlane Tutorial: Getting Started](https://www.raywenderlich.com/233168-fastlane-tutorial-getting-started) <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/fastlane.png" /> ## Jenkins Jenkins is most popular CI/CD tools [Jenkins](https://www.jenkins.io/) ## Jira Jira is project management software first and foremost, but it began its life in 2002 as an issue tracking platform for software developers - [Jira](https://www.atlassian.com/software/jira) - [What is Jira used for?](https://www.atlassian.com/software/jira/guides/use-cases/what-is-jira-used-for#Jira-for-requirements-&-test-case-management) - [What Is Jira: An Overview of a Unique Project Management Tool](https://www.fool.com/the-blueprint/what-is-jira/) ## CircleCI [CircleCI](https://circleci.com/) You can integrate Circle CI into Github repo, therefore we can use it in PR. ## Danger [Danger](https://github.com/danger/danger) - Danger runs after your CI, automating your team's conventions surrounding code review. - This provides another logical step in your process, through this Danger can help lint your rote tasks in daily code review. - You can use Danger to codify your team's norms, leaving humans to think about harder problems. ## Codemagic [Codemagic](https://codemagic.io/) - Build, test and deliver your mobile projects 20% faster. ## Xcode Cloud [WWDC21](https://www.apple.com/apple-events/june-2021/?&cid=wwa-us-kwgo-features-slid--Brand-AppleLive-Post-&mtid=20925e1t39169&aosid=p238&mnid=sZH3E0Pf0-dc_mtid_20925e1t39169_pcrid_524281987644_pgrid_129696028064_) Apple released [Xcode Cloud](https://developer.apple.com/xcode-cloud/) for continuous integration For more info, go to [Apple Developer Website](https://developer.apple.com/documentation/Xcode/Xcode-Cloud) <p align="right"> <a href="#-content">Back to Content</a> </p> # Tuist - Tuist is a command line tool that helps you generate, maintain and interact with Xcode projects. - [Tuist](https://docs.tuist.io/tutorial/get-started) - [Tuist Github](https://github.com/tuist/tuist) - [Tuist Tutorial for Xcode](https://www.raywenderlich.com/24508362-tuist-tutorial-for-xcode) # In App Purchase(IAP) **Requirement** - Full Apple Developoment Program($99) - Physical IPhone Device to test IAP > **Simulator can not test IAP!!** ## Paywall <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/paywall.jpeg" /> Paywall is a way to restrict access to their information so that only paying users can use it. Lots of developer recommend 80% - (Paywall) - 20% ## Set Up TBD For more info about getting start of IAP, go [here](https://www.raywenderlich.com/5456-in-app-purchase-tutorial-getting-started) ๐Ÿ“‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Notification - Notifications are an integral way of conveying information to the user outside of an app. - Notifications can be either local or remote. The app on the device schedules and configures local notifications. In contrast, a server sends remote notifications using Apple Push Notification Service (APNS) - You can configure both local and remote notifications using the UserNotifications framework. ## Local Notification - [Local Notifications: Getting Started](https://www.raywenderlich.com/21458686-local-notifications-getting-started) - [Swift Local Notification All-In-One](https://itnext.io/swift-local-notification-all-in-one-ee6027ea6e3) If you set repeatation **less than 60 sec**, it will cause ERROR! <img src ="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/Repeatation_Error.png"/> <p align="right"> <a href="#-content">Back to Content</a> </p> ## Remote Notification ## APNs APNS stands for **Apple Push Notification service** ## APNs Setting First, go to **Signing & Capabilities** and add two features like this <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/apsn_Setting.png"/> ## APNs Usage - [Push Notifications Tutorial: Getting Started](https://www.raywenderlich.com/11395893-push-notifications-tutorial-getting-started) ## FRP Functional Reactive Programming ## Rxswift - [RxSwift raywenderlich](https://www.raywenderlich.com/books/rxswift-reactive-programming-with-swift/v4.0) - [RxSwift](https://github.com/ReactiveX/RxSwift) - Github Repository - [RxSwift](http://reactivex.io/intro.html) - Website ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | RxSwift: Reactive Programming with Swift | raywenderlich Tutorial Team | <p align="right"> <a href="#-content">Back to Content</a> </p> ## Combine Combine released on iOS13 from Apple for Functional Reactive Programming. [Swiftbysundell](https://www.swiftbysundell.com/basics/combine/) ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | Combine: Asynchronous Programming with Swift | raywenderlich Tutorial Team | ## RxCombine RxCombine provides bi-directional type bridging between RxSwift and Apple's Combine framework. [RxCombine](https://github.com/CombineCommunity/RxCombine) # Security Security secure the data your app manages, and control access to your app. Check below for more detail about iOS Security as well as Application security - [Introduction to Apple platform security](https://support.apple.com/ko-kr/guide/security/seccd5016d31/web) - [iOS Security](https://www.cse.wustl.edu/~jain/cse571-14/ftp/ios_security/index.html) - [Apple Developer Doc about Security](https://developer.apple.com/documentation/security) - [iOS App Security: Best Practices](https://quickbirdstudios.com/blog/ios-app-security-best-practices/) <p align="right"> <a href="#-content">Back to Content</a> </p> ## Checklist For App Security - [ ] Keychain For Sensitive Data Storage - [ ] Application Transport Security Layer(TSL) - [ ] SSL Pinning - [ ] Jailbroken Device Check - [ ] Disable Debug Logs - [ ] Third-Party Library Usage Check - [ ] Code Obfuscation - [ ] Cryptography - [ ] Biometric Access ## Keychain - [Storing Keys in the Keychain](https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_keychain) - [Keychain raywenderlich](https://www.raywenderlich.com/9240-keychain-services-api-tutorial-for-passwords-in-swift) ## SSL Pinning <img src = "https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/SSLCertificate.png"/> When a mobile app communicates with a server, it uses SSL(Secure Socket Layer) pinning technique for protecting the transmitted data against tampering and eavesdropping. - [Preventing Man-in-the-Middle Attacks in iOS with SSL Pinning](https://www.raywenderlich.com/1484288-preventing-man-in-the-middle-attacks-in-ios-with-ssl-pinning) - [How to Perform SSL Pinning in iOS Apps](https://appinventiv.com/blog/ssl-pinning-in-ios-app/) ## How SSL Works 1. A browser attempts to connect with a website which is secured with a SSL. The browser then requests the web server to identify itself. 2. Web server then sends the browser its SSL certificate copy. 3. The browser checks if the SSL certificate must be trusted. If it can be, a message is sent to the web server. 4. Web server then sends back an acknowledgement to begin the SSL encrypted session. 5. The encrypted data is then finally shared between the browser and web server. ## SSL pinning methods - Pin the certificate โ€“ you can download the serverโ€™s certificate and bundle them in the app. At the runtime, the app compares the server certificate to ones that you have embedded. - Pin the public key โ€“ you can retrieve the public key of certificate in the code as string. At the runtime, the application compared the certificateโ€™s public key to one which is hard-coded in the code. ## Using URLSession ```swift func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { if let serverTrust = challenge.protectionSpace.serverTrust { var secresult = SecTrustResultType.invalid let status = SecTrustEvaluate(serverTrust, &secresult) if (errSecSuccess == status) { if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) { let serverCertificateData = SecCertificateCopyData(serverCertificate) let data = CFDataGetBytePtr(serverCertificateData); let size = CFDataGetLength(serverCertificateData); let cert1 = NSData(bytes: data, length: size) let file_der = Bundle.main.path(forResource: "name-of-cert-file", ofType: "cer") if let file = file_der { if let cert2 = NSData(contentsOfFile: file) { if cert1.isEqual(to: cert2 as Data) { completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust)) return } } } } } } } // Pinning failed completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) } ``` ## Using Alamofire 5 If you are using above version, this code should be changed [More Info](https://devgenes.com/posts/SSL-Pinning-With-Alamofire/) First, Download SSL certificate to your project folder > https://www.yourdomain.com (NOT IN THIS WAY) ```bash openssl s_client -showcerts -connect yourdomain.com:443 < /dev/null | openssl x509 -outform DER > yourdomain.cer ``` Make a SessionManager to get SSL Pinning ```swift let sessionManager: SessionManager = { let serverTrustPolicies: [String: ServerTrustPolicy] = ["yourdomain.com": .pinCertificates(certificates: ServerTrustPolicy.certificates(), validateCertificateChain: true, validateHost: true)] return SessionManager(serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)) }() ``` request from sessionManager, if it is invalid, print error ```swift sessionManager.request("https://yourdomain.com").responseString { (dataResponse) in switch dataResponse.result { case .failure(let err): print(err) case .success(let val): print(val) if let headerFields = dataResponse.response?.allHeaderFields { print(headerFields) } } } ``` ### Relative Stuff TrustKit makes it easy to deploy SSL public key pinning [TrustKit](https://github.com/datatheorem/TrustKit) ## Code Obfuscation Code obfuscation is the act of deliberately obscuring source code, making it very difficult for humans to understand, and making it useless to hackers who may have ulterior motives. ## Cryptography [Introducing Swift Crypto](https://swift.org/blog/crypto/) ## Biometric Access Apple made a big change when it released the iPhone X: It ditched Touch ID fingerprint security for a new face-based biometric sign-on tool called Face ID. The fingerprint scanner on most post-iPhone X Apple products is gone, and in its place is a new camera array capable of capturing a face map that is, according to Apple, 20 times less likely to be hacked than a Touch ID fingerprint. [Apple's Face ID: Cheat sheet](https://www.techrepublic.com/article/apples-face-id-everything-iphone-x-users-need-to-know/) ## Face ID & Touch ID To use Face ID, Add **Privacy - Face ID Usage Description** into your info.plist file in your project <img src = "https://github.com/jphong1111/Useful_Swift/blob/main/Images/FaceID_Info.png" width = "50%" height = "50%"/> import LocalAuthentication, which can allow you to implement Biometric Access ```swift import LocalAuthentication ``` After that, using LAContext() we can implement Face ID Here are simple example that how Face ID can impelement ```swift @IBAction private func isTouched(_ sender: UIButton!) { let context = LAContext() var error: NSError? = nil if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "touch id" context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { [weak self](success, error) in DispatchQueue.main.async { guard success, error == nil else { // If Fail let alert = UIAlertController(title: "FAceID Fail", message: "error", preferredStyle: .alert) let action = UIAlertAction(title: "cancle", style: .cancel, handler: nil) alert.addAction(action) self?.present(alert, animated: true, completion: nil) return } // If success let vc = UIViewController() vc.title = "hi" vc.view.backgroundColor = .blue self?.present(vc, animated: true, completion: nil) } } } else { // If device is not supporting Face ID } } ``` > Error Handling is your own part **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ <p align="right"> <a href="#-content">Back to Content</a> </p> ## Objective-C Still we need to study Objective-C for legacy code which is still remain in our project! Here are some useful website that you can study about simple concept of Obj-C!! [Learn Objective-C in 24 Days](https://www.binpress.com/learn-objective-c-24-days/) ๐Ÿ“š๐Ÿ“š Recommend Book ๐Ÿ“š๐Ÿ“š | Book Name | Authors Name | | :----------- | :----------- | | Objective-C Programming: The Big Nerd Ranch Guide | Aaron Hillegass, Mikey Ward | ### Pure Swift Application? Can we really say "Our application is built with pure Swift"?. NO! Lots of Objective-C codes are running in the background to built swift. Here is a example that you can try **Simply create a pure swift application and use this lines in debug console!!** ```swift break set -r "-\[.*\]" break set -r DebugMode break set -r Emoji ``` Use one of above line when you want to find out how many Objective-C codes are consist in simple pure swift application!! <img src="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/ObjcBreakPoint.png" /> <p align="right"> <a href="#-content">Back to Content</a> </p> ## Bridging Header Bridging header means access classes and other declarations from your Objective-C code in Swift. [Importing Objective-C into Swift Apple Documentation](https://developer.apple.com/documentation/swift/imported_c_and_objective-c_apis/importing_objective-c_into_swift) <p align="right"> <a href="#-content">Back to Content</a> </p> # Error Search Find your common error here [Error Search](https://github.com/jphong1111/Useful_Swift/blob/error-search/README.md) # Useful Stuff I listed some of the useful & interesting stuff related with Swift <p align="right"> <a href="#-content">Back to Content</a> </p> ## Useful Blogs for iOS Developers Here are the useful blog list which you can get references & knowledges about iOS development - [SwiftLee](https://www.avanderlee.com/) ๐Ÿ‘ - [Apple Developer](https://developer.apple.com/videos/) Find recent technique with videos and example codes!! - [appinventiv](https://appinventiv.com/blog/) Including iOS and others!! - Continue adding lists... ## How to submit your app to the AppStore - [Publishing to AppStore](https://codewithchris.com/submit-your-app-to-the-app-store/#apple-developer-program) - [StoreKit](https://developer.apple.com/documentation/storekit) - [What is a provisioning profile & code signing in iOS?](https://abhimuralidharan.medium.com/what-is-a-provisioning-profile-in-ios-77987a7c54c2) ## iOS Version Adoption Tracker You can check the iOS Version adoption in this site [iOS Version Adoption Tracker](https://mixpanel.com/trends/#report/ios_15) <img src="https://github.com/jphong1111/awesome-ios-developer/blob/main/Images/iosVersionAdoption.png" /> <p align="right"> <a href="#-content">Back to Content</a> </p> ## Online Swift Playground [SwiftPlayground](http://online.swiftplayground.run/) - Online Swift Playground ## Show Preview in UIKit(Build UI with Code Base) ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ [Inject (3rd Party Library)](https://github.com/krzysztofzablocki/Inject) Copy this code and Paste into your controller ```swift #if canImport(SwiftUI) && DEBUG import SwiftUI struct SwiftLeeViewRepresentable: UIViewRepresentable { func makeUIView(context: Context) -> UIView { return UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()!.view } func updateUIView(_ view: UIView, context: Context) { } } @available(iOS 13.0, *) struct SwiftLeeViewController_Preview: PreviewProvider { static var previews: some View { SwiftLeeViewRepresentable() } } #endif ``` Enable canvas option like this <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/preview%20using%20canvas.png"> <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/preivew_screenShot.png"> **You are GOOD TO GO** ๐Ÿ‘๐Ÿ‘๐Ÿ‘ ## Compare Changes in Swift Version You can compare changes based on Swift Verison [Whatsnewinswift](https://www.whatsnewinswift.com/?from=5.3&to=5.4) ## Managing Xcode Space This will be helful when you are running out of storage in your mac ```bash # 1 echo "Removing Derived Data..." rm -rf ~/Library/Developer/Xcode/DerivedData/ # 2 echo "Removing Device Support..." rm -rf ~/Library/Developer/Xcode/iOS\ DeviceSupport rm -rf ~/Library/Developer/Xcode/watchOS\ DeviceSupport rm -rf ~/Library/Developer/Xcode/tvOS\ DeviceSupport # 3 echo "Removing old simulators..." xcrun simctl delete unavailable # 4 echo "Removing caches..." rm -rf ~/Library/Caches/com.apple.dt.Xcode rm -rf ~/Library/Caches/org.carthage.CarthageKit # 5 if command -v pod &> /dev/null then # 6 pod cache clean --all fi echo "Done!" ``` After writing, run it with this command ```bash chmod u+x clean-xcode.sh ``` And then ```script ./clean-xcode.sh ``` **This will cleans out derived data, device support, simulators and caches. So that once you execute it, You have to build your project AGAIN** For More Info, visit [here](https://www.raywenderlich.com/19998365-understanding-and-managing-xcode-space) <p align="right"> <a href="#-content">Back to Content</a> </p> ## Roadmap for iOS Developer check this out [here](https://github.com/BohdanOrlov/iOS-Developer-Roadmap) ## Use VIM in Xcode Check [this](https://www.twilio.com/blog/2017/06/adding-vim-keybindings-to-xcode-with-xvim.html) site for more info! ~~Since Xcode 13(BETA), you can find Vim in **Preference -> Text Editing -> Editing -> Enable Vim Key bindings**~~ this feature deprecated in Xcode 13(BETA) <img src="https://github.com/jphong1111/Useful_Swift/blob/main/Images/Vim.png"> ## Write README.md [how-to-write-a-readme](https://medium.com/@saumya.ranjan/how-to-write-a-readme-md-file-markdown-file-20cb7cbcd6f) will help you to write a README.md file more dynamically ๐Ÿ‘ Also you can edit Readme.md file with VSCode Extension! Check out in VSCode! [Markdown Preview Enhanced](https://github.com/shd101wyy/markdown-preview-enhanced) <p align="right"> <a href="#-content">Back to Content</a> </p> # โค Supporters ## โญ Stargazers <a href="https://github.com/jphong1111/awesome-ios-developer/stargazers"> <img src="https://reporoster.com/stars/jphong1111/awesome-ios-developer"></a> ## ๐Ÿด Forks <a href="https://github.com/jphong1111/awesome-ios-developer/fork"> <img src="https://reporoster.com/forks/jphong1111/awesome-ios-developer"></a> ## ๐ŸŒŸ GitHub Stargazers [![Stargazers over time](https://starchart.cc/jphong1111/useful_swift.svg)](https://starchart.cc/jphong1111/awesome-ios-developer) ## Author This README.md file is written by **Jungpyo Hong (Dennis)** email: [email protected] <p align="right"> <a href="#-content">Back to Content</a> </p>
191
Boilerplate-free mocking framework for Swift!
# Cuckoo ## Mock your Swift objects! [![CI Status](https://img.shields.io/travis/Brightify/Cuckoo?style=flat)](https://travis-ci.org/Brightify/Cuckoo) [![Version](https://img.shields.io/cocoapods/v/Cuckoo.svg?style=flat)](http://cocoapods.org/pods/Cuckoo) [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen?style=flat)](https://swift.org/package-manager) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen?style=flat)](https://github.com/Carthage/Carthage) [![License](https://img.shields.io/cocoapods/l/Cuckoo.svg?style=flat)](http://cocoapods.org/pods/Cuckoo) [![Platform](https://img.shields.io/cocoapods/p/Cuckoo.svg?style=flat)](http://cocoapods.org/pods/Cuckoo) ## Introduction Cuckoo was created due to lack of a proper Swift mocking framework. We built the DSL to be very similar to [Mockito](http://mockito.org/), so anyone coming from Java/Android can immediately pick it up and use it. ## How does it work Cuckoo has two parts. One is the [runtime](https://github.com/Brightify/Cuckoo) and the other one is an OS X command-line tool simply called [CuckooGenerator](./Generator). Unfortunately Swift does not have a proper reflection, so we decided to use a compile-time generator to go through files you specify and generate supporting structs/classes that will be used by the runtime in your test target. The generated files contain enough information to give you the right amount of power. They work based on inheritance and protocol adoption. This means that only overridable things can be mocked. Due to the complexity of Swift it is not easy to check for all edge cases so if you find some unexpected behavior, please file an issue. ## Changelog List of all changes and new features can be found [here](CHANGELOG.md). ## Features Cuckoo is a powerful mocking framework that supports: - [x] inheritance (grandparent methods) - [x] generics - [x] simple type inference for instance variables (works with initializers, `as TYPE` notation, and can be overridden by specifying type explicitly) - [x] [Objective-C mocks utilizing OCMock](#objective-c-support) ## What will not be supported Due to the limitations mentioned above, unoverridable code structures are not supportable by Cuckoo. This includes: - `struct` - workaround is to use a common protocol - everything with `final` or `private` modifier - global constants and functions - static properties and methods ## Requirements Cuckoo works on the following platforms: - **iOS 8+** - **Mac OSX 10.9+** - **tvOS 9+** **watchOS** support is not yet possible due to missing XCTest library. Note: Version `1.2.0` is the last one supporting **Swift 4.2**. Use versions `1.3.0`+ for **Swift 5** and up. ## Cuckoo ### 1. Installation #### CocoaPods Cuckoo runtime is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your test target in your Podfile: ```Ruby pod 'Cuckoo' ``` And add the following `Run script` build phase to your test target's `Build Phases` above the `Compile Sources` phase: ```Bash if [ $ACTION == "indexbuild" ]; then echo "Not running Cuckoo generator during indexing." exit 0 fi # Skip for preview builds if [ "${ENABLE_PREVIEWS}" = "YES" ]; then echo "Not running Cuckoo generator during preview builds." exit 0 fi # Define output file. Change "${PROJECT_DIR}/${PROJECT_NAME}Tests" to your test's root source folder, if it's not the default name. OUTPUT_FILE="${PROJECT_DIR}/${PROJECT_NAME}Tests/GeneratedMocks.swift" echo "Generated Mocks File = ${OUTPUT_FILE}" # Define input directory. Change "${PROJECT_DIR}/${PROJECT_NAME}" to your project's root source folder, if it's not the default name. INPUT_DIR="${PROJECT_DIR}/${PROJECT_NAME}" echo "Mocks Input Directory = ${INPUT_DIR}" # Generate mock files, include as many input files as you'd like to create mocks for. "${PODS_ROOT}/Cuckoo/run" generate --testable "${PROJECT_NAME}" \ --output "${OUTPUT_FILE}" \ "${INPUT_DIR}/FileName1.swift" \ "${INPUT_DIR}/FileName2.swift" \ "${INPUT_DIR}/FileName3.swift" # ... and so forth, the last line should never end with a backslash # After running once, locate `GeneratedMocks.swift` and drag it into your Xcode test target group. ``` **IMPORTANT**: To make your mocking journey easier, make absolutely sure that the run script is above the `Compile Sources` phase. **NOTE**: To avoid race condition errors when Xcode parallelizes build phases, add the path of the `OUTPUT_FILE` into the "Output Files" section of the build phase. If you find that `OUTPUT_FILE` still doesn't regenerate with new changes, adding mocked files to the "Input Files" section of the build phase might help. Input files can be also specified directly in `Run script` in `Input Files` form. Note: All paths in the Run script must be absolute. Variable `PROJECT_DIR` automatically points to your project directory. **Remember to include paths to inherited Classes and Protocols for mocking/stubbing parent and grandparents.** #### Swift Package Manager 1. In Xcode, navigate in menu: File > Swift Packages > Add Package Dependency 2. Add `https://github.com/Brightify/Cuckoo.git` 3. Select "Up to Next Major" with `1.9.1` Cuckoo relies on a script that is currently not downloadable using SPM. However, for convenience, you can copy this line into the terminal to download the latest `run` script. If the `run` script changes in the future, you'll need to execute this command again. ```Bash curl -Lo run https://raw.githubusercontent.com/Brightify/Cuckoo/master/run && chmod +x run ``` When you're all set, use the same `Run script` phase as above and replace ```Bash "${PODS_ROOT}/Cuckoo/run" ``` with ```Bash "${PROJECT_DIR}/run" --download ``` The `--download` option is necessary because the `Generator` sources are not cloned in your project (they're in `DerivedData`, out of reach). You can add a version (e.g. `1.9.1`) after it to get a specific version of the `cuckoo_generator`. Use `--clean` as well to replace the current `cuckoo_generator` if you're changing versions. #### Carthage To use Cuckoo with [Carthage](https://github.com/Carthage/Carthage) add this line to your Cartfile: ``` github "Brightify/Cuckoo" ``` Then use the `Run script` from above and replace ```Bash "${PODS_ROOT}/Cuckoo/run" ``` with ```Bash "Carthage/Checkouts/Cuckoo/run" ``` Don't forget to add the Framework into your project. ### 2. Usage Usage of Cuckoo is similar to [Mockito](http://mockito.org/) and [Hamcrest](http://hamcrest.org/). However, there are some differences and limitations caused by generating the mocks and Swift language itself. List of all the supported features can be found below. You can find complete examples in [tests](Tests). #### Mock initialization Mocks can be created with the same constructors as the mocked type. Name of mock class always corresponds to the name of the mocked class/protocol with `Mock` prefix (e.g. mock of protocol `Greeter` is called `MockGreeter`). ```Swift let mock = MockGreeter() ``` #### Spy Spies are a special type of Mocks where each call is forwarded to the victim by default. When you need a spy, give Cuckoo a class, then you'll then be able to call `enableSuperclassSpy()` (or `withEnabledSuperclassSpy()`) on a mock instance and it will behave like a spy for the parent class. ```Swift let spy = MockGreeter().withEnabledSuperclassSpy() ``` #### Stubbing Stubbing can be done by calling methods as a parameter of the `when` function. The stub call must be done on special stubbing object. You can get a reference to it with the `stub` function. This function takes an instance of the mock that you want to stub and a closure in which you can do the stubbing. The parameter of this closure is the stubbing object. Note: It is currently possible for the subbing object to escape from the closure. You can still use it to stub calls but it is not recommended in practice as the behavior of this may change in the future. After calling the `when` function you can specify what to do next with following methods: ```Swift /// Invokes `implementation` when invoked. then(_ implementation: IN throws -> OUT) /// Returns `output` when invoked. thenReturn(_ output: OUT, _ outputs: OUT...) /// Throws `error` when invoked. thenThrow(_ error: ErrorType, _ errors: Error...) /// Invokes real implementation when invoked. thenCallRealImplementation() /// Does nothing when invoked. thenDoNothing() ``` The available methods depend on the stubbed method characteristics. For example, the `thenThrow` method isn't available for a method that isn't throwing or rethrowing. An example of stubbing a method looks like this: ```Swift stub(mock) { stub in when(stub.greetWithMessage("Hello world")).then { message in print(message) } } ``` As for a property: ```Swift stub(mock) { stub in when(stub.readWriteProperty.get).thenReturn(10) when(stub.readWriteProperty.set(anyInt())).then { print($0) } } ``` Notice the `get` and `set`, these will be used in verification later. ##### Enabling default implementation In addition to stubbing, you can enable default implementation using an instance of the original class that's being mocked. Every method/property that is not stubbed will behave according to the original implementation. Enabling the default implementation is achieved by simply calling the provided method: ```Swift let original = OriginalClass<Int>(value: 12) mock.enableDefaultImplementation(original) ``` For passing classes into the method, nothing changes whether you're mocking a class or a protocol. However, there is a difference if you're using a `struct` to conform to the original protocol we are mocking: ```Swift let original = ConformingStruct<String>(value: "Hello, Cuckoo!") mock.enableDefaultImplementation(original) // or if you need to track changes: mock.enableDefaultImplementation(mutating: &original) ``` Note that this only concerns `struct`s. `enableDefaultImplementation(_:)` and `enableDefaultImplementation(mutating:)` are different in state tracking. The standard non-mutating method `enableDefaultImplementation(_:)` creates a copy of the `struct` for default implementation and works with that. However, the mutating method `enableDefaultImplementation(mutating:)` takes a reference to the struct and the changes of the `original` are reflected in the default implementation calls even after enabling default implementation. We recommend using the non-mutating method for enabling default implementation unless you need to track the changes for consistency within your code. ##### Chain stubbing It is possible to chain stubbing. This is useful for when you need to define different behavior for multiple calls in order. The last behavior will be used for all calls after that. The syntax goes like this: ```Swift when(stub.readWriteProperty.get).thenReturn(10).thenReturn(20) ``` which is equivalent to: ```Swift when(stub.readWriteProperty.get).thenReturn(10, 20) ``` The first call to `readWriteProperty` will return `10` and all calls after that will return `20`. You can combine the stubbing methods as you like. ##### Overriding of stubbing When looking for stub match Cuckoo gives the highest priority to the last call of `when`. This means that calling `when` multiple times with the same function and matchers effectively overrides the previous call. Also more general parameter matchers have to be used before specific ones. ```Swift when(stub.countCharacters(anyString())).thenReturn(10) when(stub.countCharacters("a")).thenReturn(1) ``` In this example calling `countCharacters` with `a` will return `1`. If you reversed the order of stubbing then the output would always be `10`. #### Usage in real code After previous steps the stubbed method can be called. It is up to you to inject this mock into your production code. Note: Call on mock which wasn't stubbed will cause an error. In case of a spy, the real code will execute. #### Verification For verifying calls there is function `verify`. Its first parameter is the mocked object, optional second parameter is the call matcher. Then the call with its parameters follows. ```Swift verify(mock).greetWithMessage("Hello world") ``` Verification of properties is similar to their stubbing. You can check if there are no more interactions on mock with function `verifyNoMoreInteractions`. With Swift's generic types, it is possible to use a generic parameter as the return type. To properly verify these methods, you need to be able to specify the return type. ```Swift // Given: func genericReturn<T: Codable>(for: String) -> T? { ... } // Verify verify(mock).genericReturn(for: any()).with(returnType: String?.self) ``` ##### Argument capture You can use `ArgumentCaptor` to capture arguments in verification of calls (doing that in stubbing is not recommended). Here is an example code: ```Swift mock.readWriteProperty = 10 mock.readWriteProperty = 20 mock.readWriteProperty = 30 let argumentCaptor = ArgumentCaptor<Int>() verify(mock, times(3)).readWriteProperty.set(argumentCaptor.capture()) argumentCaptor.value // Returns 30 argumentCaptor.allValues // Returns [10, 20, 30] ``` As you can see, method `capture()` is used to create matcher for the call and then you can get the arguments via properties `value` and `allValues`. `value` returns last captured argument or nil if none. `allValues` returns array with all captured values. ### 3. Matchers Cuckoo makes use of *matchers* to connect your mocks to your code under test. #### A) Automatic matchers for known types You can mock any object that conforms to the `Matchable` protocol. These basic values are extended to conform to `Matchable`: - `Bool` - `String` - `Float` - `Double` - `Character` - `Int` - `Int8` - `Int16` - `Int32` - `Int64` - `UInt` - `UInt8` - `UInt16` - `UInt32` - `UInt64` Matchers for `Array`, `Dictionary`, and `Set` are automatically synthesized as long as the type of the element conforms to `Matchable`. #### B) Custom matchers If Cuckoo doesn't know the type you are trying to compare, you have to write your own method `equal(to:)` using a `ParameterMatcher`. Add this method to your test file: ```swift func equal(to value: YourCustomType) -> ParameterMatcher<YourCustomType> { return ParameterMatcher { tested in // Implementation of equality test for your custom type. } } ``` โš ๏ธ Trying to match an object with an unknown or non-`Matchable` type may lead to: ``` Command failed due to signal: Segmentation fault: 11 ``` For details or an example (with Alamofire), see [this issue](https://github.com/Brightify/Cuckoo/issues/124). #### Parameter matchers `ParameterMatcher` itself also conforms to `Matchable`. You can create your own `ParameterMatcher` instances or if you want to directly use your custom types there is the `Matchable` protocol. Standard instances of `ParameterMatcher` can be obtained via these functions: ```Swift /// Returns an equality matcher. equal<T: Equatable>(to value: T) /// Returns an identity matcher. equal<T: AnyObject>(to value: T) /// Returns a matcher using the supplied function. equal<T>(to value: T, equalWhen equalityFunction: (T, T) -> Bool) /// Returns a matcher matching any Int value. anyInt() /// Returns a matcher matching any String value. anyString() /// Returns a matcher matching any T value or nil. any<T>(type: T.Type = T.self) /// Returns a matcher matching any closure. anyClosure() /// Returns a matcher matching any throwing closure. anyThrowingClosure() /// Returns a matcher matching any non nil value. notNil() ``` Cuckoo also provides plenty of convenience matchers for sequences and dictionaries, allowing you to check if a sequence is a superset of a certain sequence, contains at least one of its elements, or is completely disjunct from it. `Matchable` can be chained with methods `or` and `and` like so: ```Swift verify(mock).greetWithMessage("Hello world".or("Hallo Welt")) ``` #### Call matchers As a second parameter of the `verify` function you can use instances of `CallMatcher`. Its primary function is to assert how many times was the call made. But the `matches` function has a parameter of type `[StubCall]` which means you can use a custom `CallMatcher` to inspect the stub calls or for some side effect. Note: Call matchers are applied after the parameter matchers. So you get only stub calls of the desired method with correct arguments. Standard call matchers are: ```Swift /// Returns a matcher ensuring a call was made `count` times. times(_ count: Int) /// Returns a matcher ensuring no call was made. never() /// Returns a matcher ensuring at least one call was made. atLeastOnce() /// Returns a matcher ensuring call was made at least `count` times. atLeast(_ count: Int) /// Returns a matcher ensuring call was made at most `count` times. atMost(_ count: Int) ``` As with `Matchable` you can chain `CallMatcher` with methods `or` and `and`. However, you can't mix `Matchable` and `CallMatcher` together. #### Resetting mocks Following functions are used to reset stubbing and/or invocations on mocks. ```Swift /// Clears all invocations and stubs of given mocks. reset<M: Mock>(_ mocks: M...) /// Clears all stubs of given mocks. clearStubs<M: Mock>(_ mocks: M...) /// Clears all invocations of given mocks. clearInvocations<M: Mock>(_ mocks: M...) ``` #### Stub objects Stubs are used for suppressing real code. Stubs are different from Mocks in that they don't support stubbing nor verification. They can be created with the same constructors as the mocked type. Name of stub class always corresponds to name of the mocked class/protocol with `Stub` suffix (e.g. stub of protocol `Greeter` is called `GreeterStub`). ```Swift let stub = GreeterStub() ``` When a method is called or a property accessed/set on a stub, nothing happens. If a value is to be returned from a method or a property, `DefaultValueRegistry` provides a default value. Stubs can be used to set implicit (no) behavior to mocks without the need to use `thenDoNothing()` like this: `MockGreeter().spy(on: GreeterStub())`. ##### DefaultValueRegistry `DefaultValueRegistry` is used by Stubs to get default values for return types. It knows only default Swift types, sets, arrays, dictionaries, optionals, and tuples (up to 6 values). Tuples for more values can be added through extensions. Custom types must be registered before use with `DefaultValueRegistry.register<T>(value: T, forType: T.Type)`. Furthermore, default values set by Cuckoo can also be overridden by this method. Sets, arrays, etc. do not have to be registered if their generic type is already registered. `DefaultValueRegistry.reset()` returns the registry to its clean slate before the `register` method made any changes. ##### Type inference Cuckoo does a simple type inference on all variables which allows for much cleaner source code on your side. There are a total 3 ways the inference tries to extract the type name from a variable: ```Swift // From the explicitly declared type: let constant1: MyType // From the initial value: let constant2 = MyType(...) // From the explicitly specified type `as MyType`: let constant3 = anything as MyType ``` ## Cuckoo generator ### Installation For normal use you can skip this because the [run script](run) downloads or builds the correct version of the generator automatically. #### Custom So you have chosen a more complicated path. You can clone this repository and build it yourself. Take a look at the [run script](run) for more inspiration. ### Usage Generator can be executed manually through the terminal. Each call consists of build options, a command, generator options, and arguments. Options and arguments depend on the command used. Options can have additional parameters. Names of all of them are case sensitive. The order goes like this: ``` cuckoo build_options command generator_options arguments ``` #### Build Options These options are only used for downloading or building the generator and don't interfere with the result of the generated mocks. When the [run script](run) is executed without any build options (they are only valid when specified **BEFORE** the `command`), it simply searches for the `cuckoo_generator` file and builds it from source code if it's missing. To download the generator from GitHub instead of building it, use the `--download [version]` option as the first argument (i.e. `run --download generate ...` or `run --download 1.5.0 generate ...` to fetch a specific version). If you're having issues with rather long build time (especially in CI), this might be the way to fix it. **NOTE**: If you encounter Github API rate limit using the `--download` option, the [run script](run) refers to the environment variable `GITHUB_ACCESS_TOKEN`. Add this line (replacing the Xs with your [GitHub token](https://github.com/settings/tokens), no additional permissions are needed) to the script build phase above the `run` call: ```Bash export GITHUB_ACCESS_TOKEN="XXXXXXX" ``` The build option `--clean` forces either build or download of the version specified even if the generator is present. At the moment the [run script](run) doesn't enforce the generator version to be the same as the Cuckoo version. We recommend using this option after updating Cuckoo as well as if you're having mysterious compile errors in the generated mocks. Please try to use this option first to verify that your generator isn't outdated before filing an issue about incorrectly generated mocks. We recommend only using `--clean` when you're trying to fix a compile problem as it forces the build (or download) every time which makes the testing way longer than it needs to be. #### Generator commands ##### `generate` command Generates mock files. This command accepts options that can be used to adjust the behavior of the generator, these are listed below. After the options come arguments, in this case a list (separated by spaces) of files for which you want to generate mocks or that are required for correct inheritance mocking. ###### `--output` (string) Absolute path to where the generated mocks will be stored. If a path to a directory is supplied, each input file will be mapped to its own output file with mocks. If a path to a file is supplied, all mocks will be generated into this single file. The default value is `GeneratedMocks.swift`. ###### `--testable` (string)[,(string)...] A comma separated list of frameworks that should be imported as @testable in the mock files. ###### `--exclude` (string)[,(string)...] A comma separated list of classes and protocols that should be skipped during mock generation. ###### `--no-header` Do not generate file headers. ###### `--no-timestamp` Do not generate timestamp. ###### `--no-inheritance` Do not mock/stub parents and grandparents. ###### `--file-prefix` (string) Names of generated files in directory will start with this prefix. Only works when output path is directory. ###### `--no-class-mocking` Do not generate mocks for classes. ###### `--regex` (string) A regular expression pattern that is used to match Classes and Protocols. All that do not match are excluded. Can be used alongside `--exclude` in which case the `--exclude` has higher priority. ###### `-g` or `--glob` Activate [glob](https://en.wikipedia.org/wiki/Glob_(programming)) parsing for specified input paths. ###### `-d` or `--debug` Run generator in debug mode. There is more info output as well as included in the generated mocks (e.g. method parameter info). #### `version` command Prints the version of this generator. #### `help` command Display general or command-specific help. After the `help` command you can specify the name of another command for displaying command-specific information. ## Objective-C Support Cuckoo subspec `Cuckoo/OCMock` brings support for mocking Objective-C classes and protocols. Example usage: ```Swift let tableView = UITableView() // stubbing the class is very similar to stubbing with Cuckoo let mock = objcStub(for: UITableViewController.self) { stubber, mock in stubber.when(mock.numberOfSections(in: tableView)).thenReturn(1) stubber.when(mock.tableView(tableView, accessoryButtonTappedForRowWith: IndexPath(row: 14, section: 2))).then { args in // `args` is [Any] of the arguments passed and the closure needs to cast them manually let (tableView, indexPath) = (args[0] as! UITableView, args[1] as! IndexPath) print(tableView, indexPath) } } // calling stays the same XCTAssertEqual(mock.numberOfSections(in: tableView), 1) mock.tableView(tableView, accessoryButtonTappedForRowWith: IndexPath(row: 14, section: 2)) // `objcVerify` is used to verify the interaction with the methods/variables objcVerify(mock.numberOfSections(in: tableView)) objcVerify(mock.tableView(tableView, accessoryButtonTappedForRowWith: IndexPath(row: 14, section: 2))) ``` Detailed usage is available in Cuckoo tests along with DOs and DON'Ts of this Swift-ObjC bridge. So far, only CocoaPods is supported. To install, simply add this line to your `Podfile`: ```Ruby pod 'Cuckoo/OCMock' ``` ## Contribute Cuckoo is open for everyone and we'd like you to help us make the best Swift mocking library. For Cuckoo development, follow these steps: 1. Make sure you have the latest stable version of Xcode installed. 2. Clone the **Cuckoo** repository. 3. In terminal, run `make` at the root of the cloned **Cuckoo** repository, this will generate the project, install dependencies, and open the project in Xcode. 4. Select any scheme of `Cuckoo-iOS`, `Cuckoo-tvOS`, or `Cuckoo-macOS` ([OCMock](https://github.com/erikdoe/ocmock) schemes contain `Cuckoo_OCMock` instead) and verify by running the tests (โŒ˜+U). 5. Peek around or file a pull request with your changes. 6. Make sure to run `make` again whenever you checkout another branch. The project consists of two parts - runtime and code generator. When you open the `Cuckoo.xcworkspace` in Xcode, you'll see these directories: - `Source` - runtime sources - `Tests` - tests for the runtime part - `CuckoGenerator.xcodeproj` - project containing Generator source code (use the `cuckoo_generator` scheme) Thank you for your help! ## Inspiration - [Mockito](http://mockito.org/) - Mocking DSL - [Hamcrest](http://hamcrest.org/) - Matcher API ## Used libraries - [Commandant](https://github.com/Carthage/Commandant) - [FileKit](https://github.com/nvzqz/FileKit) - [SourceKitten](https://github.com/jpsim/SourceKitten) ## License Cuckoo is available under the [MIT License](LICENSE).
192
You don't have the time to watch all the WWDC session videos yourself? No problem me and many contributors extracted the gist for you ๐Ÿฅณ
# WWDC 2020 Session Notes <a href="https://twitter.com/blackjacxxx"><img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/blackjacxxx?label=%40Blackjacxxx"/></a> <a href="https://www.paypal.me/STHEROLD"><img alt="Donate" src="https://img.shields.io/badge/Donate-PayPal-blue.svg"/></a> ![Readme Auto Generation](https://github.com/Blackjacx/WWDC/workflows/Readme%20Auto%20Generation/badge.svg) ## Thank You ๐ŸŽ‰ Last years [WWDC Session Notes](https://github.com/Blackjacx/WWDC/tree/2019) was so successful that I decided to continue this form of WWDC session summary. I would like to take the moment to thank all of you for contribution, feedback, support and reading my session notes ๐Ÿ™ ## Intro Usually it is much faster to read through some bullet points instead of watching a 50 min session video. Then if you find something interesting you can still watch it. Sessions that are exceptionally mentionable are highlighted using a โ˜…. > This is work in progress since it is a lot of effort to watch all the videos by myself. So either please be patient or just [open up an issue](https://github.com/Blackjacx/WWDC/issues/new) to make a suggestion which session notes you like to see next :) ## Contribution Feel free to submit a PR if I got something wrong or you have a suggestion for improvement. Please also have a look in [CONTRIBUTING.md](CONTRIBUTING.md) if you want to contribute. Thanks so much to EVERYBODY who contributed and improved the overall quality of the notes and those who added complete notes to the list. ## Mentions This repo has already been mentioned many times on Twitter and apart from this also in the following places: - [iOS Dev Weekly Issue 409](https://iosdevweekly.com/issues/409) - [iOS Goodies Issue 287](https://ios-goodies.com/post/185729205551/week-287) - [Swift Developments Issue 189](https://andybargh.com/swiftdevelopments-189/) - [WWDCNotes](https://www.wwdcnotes.com/) ## Interesting WWDC-Related Links - [Apple Developer Documentation](https://developer.apple.com/documentation) by [@Apple](https://twitter.com/apple) - [Xcode Release Notes](https://developer.apple.com/documentation/xcode_release_notes/) - [iOS & iPadOS Release Notes](https://developer.apple.com/documentation/ios_ipados_release_notes) ## Table of Contents ![Progress](https://progress-bar.dev/31/?scale=204&title=Progress&width=600&suffix=%20/%20204%20Sessions) 1. **(TO-DO)** [Expanding automation with the App Store Connect API](#Expanding-automation-with-the-App-Store-Connect-API) 1. **(TO-DO)** [What's new in assessment](#Whats-new-in-assessment) 1. [Introducing Car Keys](#Introducing-Car-Keys) 1. **(TO-DO)** [Optimize the Core Image pipeline for your video app](#Optimize-the-Core-Image-pipeline-for-your-video-app) 1. **(TO-DO)** [Edit and play back HDR video with AVFoundation](#Edit-and-play-back-HDR-video-with-AVFoundation) 1. **(TO-DO)** [Export HDR media in your app with AVFoundation](#Export-HDR-media-in-your-app-with-AVFoundation) 1. **(TO-DO)** [Author fragmented MPEG-4 content with AVAssetWriter](#Author-fragmented-MPEG-4-content-with-AVAssetWriter) 1. **(TO-DO)** [Discover ray tracing with Metal](#Discover-ray-tracing-with-Metal) 1. **(TO-DO)** [Get to know Metal function pointers](#Get-to-know-Metal-function-pointers) 1. **(TO-DO)** [Core Data: Sundries and maxims](#Core-Data-Sundries-and-maxims) 1. **(TO-DO)** [App accessibility for Switch Control](#App-accessibility-for-Switch-Control) 1. **(TO-DO)** [Make your app visually accessible](#Make-your-app-visually-accessible) 1. **(TO-DO)** [Build Metal-based Core Image kernels with Xcode](#Build-Metal-based-Core-Image-kernels-with-Xcode) 1. **(TO-DO)** [Create a seamless speech experience in your apps](#Create-a-seamless-speech-experience-in-your-apps) 1. [Lists in UICollectionView](#Lists-in-UICollectionView) 1. [Modern cell configuration](#Modern-cell-configuration) 1. [Meet WidgetKit](#Meet-WidgetKit) 1. **(TO-DO)** [Stacks, Grids, and Outlines in SwiftUI](#Stacks-Grids-and-Outlines-in-SwiftUI) 1. **(TO-DO)** [Build SwiftUI views for widgets](#Build-SwiftUI-views-for-widgets) 1. **(TO-DO)** [Widgets Code-along, part 1: The adventure begins](#Widgets-Code-along-part-1-The-adventure-begins) 1. **(TO-DO)** [Widgets Code-along, part 2: Alternate timelines](#Widgets-Code-along-part-2-Alternate-timelines) 1. **(TO-DO)** [Widgets Code-along, part 3: Advancing timelines](#Widgets-Code-along-part-3-Advancing-timelines) 1. **(TO-DO)** [App essentials in SwiftUI](#App-essentials-in-SwiftUI) 1. **(TO-DO)** [Build document-based apps in SwiftUI](#Build-document-based-apps-in-SwiftUI) 1. [Data Essentials in SwiftUI](#Data-Essentials-in-SwiftUI) 1. [What's new in SwiftUI](#Whats-new-in-SwiftUI) 1. **(TO-DO)** [Build SwiftUI apps for tvOS](#Build-SwiftUI-apps-for-tvOS) 1. **(TO-DO)** [Build an Action Classifier with Create ML](#Build-an-Action-Classifier-with-Create-ML) 1. **(TO-DO)** [Advances in diffable data sources](#Advances-in-diffable-data-sources) 1. **(TO-DO)** [Create complications for Apple Watch](#Create-complications-for-Apple-Watch) 1. **(TO-DO)** [Enable encrypted DNS](#Enable-encrypted-DNS) 1. **(TO-DO)** [Build complications in SwiftUI](#Build-complications-in-SwiftUI) 1. **(TO-DO)** [Keep your complications up to date](#Keep-your-complications-up-to-date) 1. [Build with iOS pickers, menus and actions](#Build-with-iOS-pickers-menus-and-actions) 1. **(TO-DO)** [Optimize the interface of your Mac Catalyst app](#Optimize-the-interface-of-your-Mac-Catalyst-app) 1. **(TO-DO)** [Identify trends with the Power and Performance API](#Identify-trends-with-the-Power-and-Performance-API) 1. **(TO-DO)** [Design high quality Siri media interactions](#Design-high-quality-Siri-media-interactions) 1. **(TO-DO)** [Expand your SiriKit Media Intents to more platforms](#Expand-your-SiriKit-Media-Intents-to-more-platforms) 1. **(TO-DO)** [Background execution demystified](#Background-execution-demystified) 1. **(TO-DO)** [What's new in SiriKit and Shortcuts](#Whats-new-in-SiriKit-and-Shortcuts) 1. **(TO-DO)** [Evaluate and optimize voice interaction for your app](#Evaluate-and-optimize-voice-interaction-for-your-app) 1. **(TO-DO)** [Empower your intents](#Empower-your-intents) 1. **(TO-DO)** [Decipher and deal with common Siri errors](#Decipher-and-deal-with-common-Siri-errors) 1. **(TO-DO)** [Diagnose performance issues with the Xcode Organizer](#Diagnose-performance-issues-with-the-Xcode-Organizer) 1. [Eliminate animation hitches with XCTest](#Eliminate-animation-hitches-with-XCTest) 1. [Why is my app getting killed?](#Why-is-my-app-getting-killed) 1. **(TO-DO)** [What's new in MetricKit](#Whats-new-in-MetricKit) 1. **(TO-DO)** [Integrate your app with Wind Down](#Integrate-your-app-with-Wind-Down) 1. **(TO-DO)** [Feature your actions in the Shortcuts app](#Feature-your-actions-in-the-Shortcuts-app) 1. [Design for intelligence: Apps, evolved](#Design-for-intelligence-Apps-evolved) 1. **(TO-DO)** [Design for intelligence: Make friends with "The System"](#Design-for-intelligence-Make-friends-with-The-System) 1. [Design for intelligence: Discover new opportunities](#Design-for-intelligence-Discover-new-opportunities) 1. **(TO-DO)** [Discover Core Image debugging techniques](#Discover-Core-Image-debugging-techniques) 1. **(TO-DO)** [Decode ProRes with AVFoundation and VideoToolbox](#Decode-ProRes-with-AVFoundation-and-VideoToolbox) 1. **(TO-DO)** [Write tests to fail](#Write-tests-to-fail) 1. **(TO-DO)** [Build for the iPadOS pointer](#Build-for-the-iPadOS-pointer) 1. **(TO-DO)** [Handle trackpad and mouse input](#Handle-trackpad-and-mouse-input) 1. **(TO-DO)** [The Push Notifications primer](#The-Push-Notifications-primer) 1. **(TO-DO)** [Explore Packages and Projects with Xcode Playgrounds](#Explore-Packages-and-Projects-with-Xcode-Playgrounds) 1. [Advances in UICollectionView](#Advances-in-UICollectionView) 1. [What's new in Universal Links](#Whats-new-in-Universal-Links) 1. **(TO-DO)** [Explore the Action & Vision app](#Explore-the-Action--Vision-app) 1. [Keynote โ˜…](#Keynote-) 1. **(TO-DO)** [Meet Watch Face Sharing](#Meet-Watch-Face-Sharing) 1. **(TO-DO)** [Design great widgets](#Design-great-widgets) 1. **(TO-DO)** [Adopt the new look of macOS](#Adopt-the-new-look-of-macOS) 1. **(TO-DO)** [Build for iPad](#Build-for-iPad) 1. **(TO-DO)** [Meet Scribble for iPad](#Meet-Scribble-for-iPad) 1. **(TO-DO)** [What's new in PencilKit](#Whats-new-in-PencilKit) 1. **(TO-DO)** [Support hardware keyboards in your app](#Support-hardware-keyboards-in-your-app) 1. **(TO-DO)** [Support local network privacy in your app](#Support-local-network-privacy-in-your-app) 1. **(TO-DO)** [Boost performance and security with modern networking](#Boost-performance-and-security-with-modern-networking) 1. **(TO-DO)** [Build local push connectivity for restricted networks](#Build-local-push-connectivity-for-restricted-networks) 1. **(TO-DO)** [iPad and iPhone apps on Apple Silicon Macs](#iPad-and-iPhone-apps-on-Apple-Silicon-Macs) 1. **(TO-DO)** [AutoFill everywhere](#AutoFill-everywhere) 1. **(TO-DO)** [VoiceOver efficiency with custom rotors](#VoiceOver-efficiency-with-custom-rotors) 1. **(TO-DO)** [Accessibility design for Mac Catalyst](#Accessibility-design-for-Mac-Catalyst) 1. **(TO-DO)** [Create app clips for other businesses](#Create-app-clips-for-other-businesses) 1. **(TO-DO)** [Introduction to SwiftUI](#Introduction-to-SwiftUI) 1. [Streamline your app clip](#Streamline-your-app-clip) 1. **(TO-DO)** [Discover AppleSeed for IT and Managed Software Updates](#Discover-AppleSeed-for-IT-and-Managed-Software-Updates) 1. **(TO-DO)** [Leverage enterprise identity and authentication](#Leverage-enterprise-identity-and-authentication) 1. **(TO-DO)** [Build location-aware enterprise apps](#Build-location-aware-enterprise-apps) 1. **(TO-DO)** [Build scalable enterprise app suites](#Build-scalable-enterprise-app-suites) 1. **(TO-DO)** [What's new in Mac Catalyst](#Whats-new-in-Mac-Catalyst) 1. **(TO-DO)** [Design for Game Center](#Design-for-Game-Center) 1. [Configure and link your app clips](#Configure-and-link-your-app-clips) 1. [Distribute binary frameworks as Swift packages](#Distribute-binary-frameworks-as-Swift-packages) 1. **(TO-DO)** [Inspect, modify, and construct PencilKit drawings](#Inspect-modify-and-construct-PencilKit-drawings) 1. **(TO-DO)** [Structure your app for SwiftUI previews](#Structure-your-app-for-SwiftUI-previews) 1. **(TO-DO)** [What's new in CareKit](#Whats-new-in-CareKit) 1. **(TO-DO)** [Use model deployment and security with Core ML](#Use-model-deployment-and-security-with-Core-ML) 1. **(TO-DO)** [Get models on device using Core ML Converters](#Get-models-on-device-using-Core-ML-Converters) 1. **(TO-DO)** [Control training in Create ML with Swift](#Control-training-in-Create-ML-with-Swift) 1. **(TO-DO)** [Deliver a better HLS audio experience](#Deliver-a-better-HLS-audio-experience) 1. **(TO-DO)** [Build an Endpoint Security app](#Build-an-Endpoint-Security-app) 1. **(TO-DO)** [Formatters: Make data human-friendly](#Formatters-Make-data-human-friendly) 1. [Design for location privacy](#Design-for-location-privacy) 1. **(TO-DO)** [Advancements in the Objective-C runtime](#Advancements-in-the-Objective-C-runtime) 1. [XCTSkip your tests](#XCTSkip-your-tests) 1. [Embrace Swift type inference](#Embrace-Swift-type-inference) 1. **(TO-DO)** [Safely manage pointers in Swift](#Safely-manage-pointers-in-Swift) 1. **(TO-DO)** [Explore logging in Swift](#Explore-logging-in-Swift) 1. **(TO-DO)** [Swift packages: Resources and localization](#Swift-packages-Resources-and-localization) 1. [What's new in Swift](#Whats-new-in-Swift) 1. **(TO-DO)** [What's new in watchOS design](#Whats-new-in-watchOS-design) 1. **(TO-DO)** [Design great app clips](#Design-great-app-clips) 1. **(TO-DO)** [Get the most out of Sign in with Apple](#Get-the-most-out-of-Sign-in-with-Apple) 1. [Explore app clips](#Explore-app-clips) 1. **(TO-DO)** [The details of UI typography](#The-details-of-UI-typography) 1. **(TO-DO)** [Master Picture in Picture on tvOS](#Master-Picture-in-Picture-on-tvOS) 1. [What's new in HealthKit](#Whats-new-in-HealthKit) 1. **(TO-DO)** [Synchronize health data with HealthKit](#Synchronize-health-data-with-HealthKit) 1. **(TO-DO)** [Visually edit SwiftUI views](#Visually-edit-SwiftUI-views) 1. **(TO-DO)** [Discover WKWebView enhancements](#Discover-WKWebView-enhancements) 1. **(TO-DO)** [Secure your app: threat modeling and anti-patterns](#Secure-your-app-threat-modeling-and-anti-patterns) 1. **(TO-DO)** [Create quick interactions with Shortcuts on watchOS](#Create-quick-interactions-with-Shortcuts-on-watchOS) 1. **(TO-DO)** [Add configuration and intelligence to your widgets](#Add-configuration-and-intelligence-to-your-widgets) 1. **(TO-DO)** [Broaden your reach with Siri Event Suggestions](#Broaden-your-reach-with-Siri-Event-Suggestions) 1. [Platform State of the Union โ˜…](#Platform-State-of-the-Union-) 1. **(TO-DO)** [Design for intelligence: Meet people where they are](#Design-for-intelligence-Meet-people-where-they-are) 1. **(TO-DO)** [Create great enterprise apps: A chat with Box's Aaron Levie](#Create-great-enterprise-apps-A-chat-with-Boxs-Aaron-Levie) 1. **(TO-DO)** [Design with iOS pickers, menus and actions](#Design-with-iOS-pickers-menus-and-actions) 1. **(TO-DO)** [Design for iPad](#Design-for-iPad) 1. **(TO-DO)** [SF Symbols 2](#SF-Symbols-2) 1. **(TO-DO)** [What's new in Core NFC](#Whats-new-in-Core-NFC) 1. **(TO-DO)** [Modernize PCI and SCSI drivers with DriverKit](#Modernize-PCI-and-SCSI-drivers-with-DriverKit) 1. **(TO-DO)** [Port your Mac app to Apple Silicon](#Port-your-Mac-app-to-Apple-Silicon) 1. **(TO-DO)** [What's new in ResearchKit](#Whats-new-in-ResearchKit) 1. **(TO-DO)** [Explore numerical computing in Swift](#Explore-numerical-computing-in-Swift) 1. **(TO-DO)** [Build localization-friendly layouts using Xcode](#Build-localization-friendly-layouts-using-Xcode) 1. **(TO-DO)** [Handle interruptions and alerts in UI tests](#Handle-interruptions-and-alerts-in-UI-tests) 1. [Get your test results faster](#Get-your-test-results-faster) 1. **(TO-DO)** [Create custom apps for employees](#Create-custom-apps-for-employees) 1. **(TO-DO)** [Deploy Apple devices using zero-touch](#Deploy-Apple-devices-using-zero-touch) 1. **(TO-DO)** [Meet Audio Workgroups](#Meet-Audio-Workgroups) 1. **(TO-DO)** [Improve stream authoring with HLS Tools](#Improve-stream-authoring-with-HLS-Tools) 1. **(TO-DO)** [Record stereo audio with AVAudioSession](#Record-stereo-audio-with-AVAudioSession) 1. [What's new in Low-Latency HLS](#Whats-new-in-Low-Latency-HLS) 1. **(TO-DO)** [Discover HLS Blocking Preload Hints](#Discover-HLS-Blocking-Preload-Hints) 1. **(TO-DO)** [Optimize live streams with HLS Playlist Delta Updates](#Optimize-live-streams-with-HLS-Playlist-Delta-Updates) 1. **(TO-DO)** [Reduce latency with HLS Blocking Playlist Reload](#Reduce-latency-with-HLS-Blocking-Playlist-Reload) 1. **(TO-DO)** [Adapt ad insertion to Low-Latency HLS](#Adapt-ad-insertion-to-Low-Latency-HLS) 1. **(TO-DO)** [The artistโ€™s AR toolkit](#The-artists-AR-toolkit) 1. **(TO-DO)** [Harness Apple GPUs with Metal](#Harness-Apple-GPUs-with-Metal) 1. **(TO-DO)** [Optimize Metal apps and games with GPU counters](#Optimize-Metal-apps-and-games-with-GPU-counters) 1. **(TO-DO)** [Shop online with AR Quick Look](#Shop-online-with-AR-Quick-Look) 1. **(TO-DO)** [Gain insights into your Metal app with Xcode 12](#Gain-insights-into-your-Metal-app-with-Xcode-12) 1. [Explore ARKit 4](#Explore-ARKit-4) 1. **(TO-DO)** [What's new in RealityKit](#Whats-new-in-RealityKit) 1. **(TO-DO)** [What's new in USD](#Whats-new-in-USD) 1. **(TO-DO)** [Advancements in Game Controllers](#Advancements-in-Game-Controllers) 1. **(TO-DO)** [Build GPU binaries with Metal](#Build-GPU-binaries-with-Metal) 1. **(TO-DO)** [Debug GPU-side errors in Metal](#Debug-GPU-side-errors-in-Metal) 1. **(TO-DO)** [Bring keyboard and mouse gaming to iPad](#Bring-keyboard-and-mouse-gaming-to-iPad) 1. **(TO-DO)** [Tap into Game Center: Dashboard, Access Point, and Profile](#Tap-into-Game-Center-Dashboard-Access-Point-and-Profile) 1. **(TO-DO)** [Tap into Game Center: Leaderboards, Achievements, and Multiplayer](#Tap-into-Game-Center-Leaderboards-Achievements-and-Multiplayer) 1. **(TO-DO)** [Support performance-intensive apps and games](#Support-performance-intensive-apps-and-games) 1. **(TO-DO)** [Bring your Metal app to Apple Silicon Macs](#Bring-your-Metal-app-to-Apple-Silicon-Macs) 1. **(TO-DO)** [Optimize Metal Performance for Apple Silicon Macs](#Optimize-Metal-Performance-for-Apple-Silicon-Macs) 1. **(TO-DO)** [Capture and stream apps on the Mac with ReplayKit](#Capture-and-stream-apps-on-the-Mac-with-ReplayKit) 1. **(TO-DO)** [Discover search suggestions for Apple TV](#Discover-search-suggestions-for-Apple-TV) 1. [Accelerate your app with CarPlay](#Accelerate-your-app-with-CarPlay) 1. **(TO-DO)** [What's new in streaming audio for Apple Watch](#Whats-new-in-streaming-audio-for-Apple-Watch) 1. **(TO-DO)** [What's new in managing Apple devices](#Whats-new-in-managing-Apple-devices) 1. **(TO-DO)** [Design for the iPadOS pointer](#Design-for-the-iPadOS-pointer) 1. **(TO-DO)** [Handle the Limited Photos Library in your app](#Handle-the-Limited-Photos-Library-in-your-app) 1. **(TO-DO)** [Build Image and Video Style Transfer models in Create ML](#Build-Image-and-Video-Style-Transfer-models-in-Create-ML) 1. **(TO-DO)** [Build a SwiftUI view in Swift Playgrounds](#Build-a-SwiftUI-view-in-Swift-Playgrounds) 1. **(TO-DO)** [Use Swift on AWS Lambda with Xcode](#Use-Swift-on-AWS-Lambda-with-Xcode) 1. **(TO-DO)** [Support multiple users in your tvOS app](#Support-multiple-users-in-your-tvOS-app) 1. **(TO-DO)** [What's new in Web Inspector](#Whats-new-in-Web-Inspector) 1. **(TO-DO)** [Become a Simulator expert](#Become-a-Simulator-expert) 1. **(TO-DO)** [Unsafe Swift](#Unsafe-Swift) 1. **(TO-DO)** [Add custom views and modifiers to the Xcode Library](#Add-custom-views-and-modifiers-to-the-Xcode-Library) 1. **(TO-DO)** [Sync a Core Data store with the CloudKit public database](#Sync-a-Core-Data-store-with-the-CloudKit-public-database) 1. [What's new in App Store Connect](#Whats-new-in-App-Store-Connect) 1. [Meet the new Photos picker](#Meet-the-new-Photos-picker) 1. **(TO-DO)** [Detect Body and Hand Pose with Vision](#Detect-Body-and-Hand-Pose-with-Vision) 1. **(TO-DO)** [Create Swift Playgrounds content for iPad and Mac](#Create-Swift-Playgrounds-content-for-iPad-and-Mac) 1. **(TO-DO)** [Discover how to download and play HLS offline](#Discover-how-to-download-and-play-HLS-offline) 1. **(TO-DO)** [Beyond counting steps](#Beyond-counting-steps) 1. **(TO-DO)** [Make apps smarter with Natural Language](#Make-apps-smarter-with-Natural-Language) 1. **(TO-DO)** [What's new in education](#Whats-new-in-education) 1. **(TO-DO)** [Introducing StoreKit Testing in Xcode](#Introducing-StoreKit-Testing-in-Xcode) 1. **(TO-DO)** [What's new in location](#Whats-new-in-location) 1. **(TO-DO)** [Whatโ€™s new with in-app purchase](#Whats-new-with-in-app-purchase) 1. [What's new in Wallet and Apple Pay](#Whats-new-in-Wallet-and-Apple-Pay) 1. **(TO-DO)** [What's new for web developers](#Whats-new-for-web-developers) 1. **(TO-DO)** [Getting started with HealthKit](#Getting-started-with-HealthKit) 1. **(TO-DO)** [Meet Safari Web Extensions](#Meet-Safari-Web-Extensions) 1. **(TO-DO)** [One-tap account security upgrades](#One-tap-account-security-upgrades) 1. **(TO-DO)** [Custom app distribution with Apple Business Manager](#Custom-app-distribution-with-Apple-Business-Manager) 1. **(TO-DO)** [Meet Nearby Interaction](#Meet-Nearby-Interaction) 1. **(TO-DO)** [Handling FHIR without getting burned](#Handling-FHIR-without-getting-burned) 1. **(TO-DO)** [Meet Face ID and Touch ID for the web](#Meet-Face-ID-and-Touch-ID-for-the-web) 1. **(TO-DO)** [Architecting for subscriptions](#Architecting-for-subscriptions) 1. **(TO-DO)** [What's new in ClassKit](#Whats-new-in-ClassKit) 1. **(TO-DO)** [Explore Computer Vision APIs](#Explore-Computer-Vision-APIs) 1. **(TO-DO)** [Build trust through better privacy](#Build-trust-through-better-privacy) 1. **(TO-DO)** [Build customized ML models with the Metal Performance Shaders Graph](#Build-customized-ML-models-with-the-Metal-Performance-Shaders-Graph) 1. **(TO-DO)** [Refine Objective-C frameworks for Swift](#Refine-Objective-C-frameworks-for-Swift) 1. **(TO-DO)** [Explore the new system architecture of Apple Silicon Macs](#Explore-the-new-system-architecture-of-Apple-Silicon-Macs) 1. **(TO-DO)** [Triage test failures with XCTIssue](#Triage-test-failures-with-XCTIssue) ## Expanding automation with the App Store Connect API https://developer.apple.com/wwdc20/10004 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in assessment https://developer.apple.com/wwdc20/10005 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Introducing Car Keys https://developer.apple.com/wwdc20/10006 Presenter: _Matthias Lerch_ - People can unlock, lock and start their car (iPhone or Apple Watch) - Stored securely on the device and can be deleted via iCloud - Keys can be shared with the family or friends - Agnostic to radio technology (**supports NFC so far**) - Offline capable - Car needs to support: - **Owner pairing** (association if iPhone and car) - Prove ownership of car - Initiate pairing - Place iPhone near car's NFC reader - Car key appears in Wallet - **Transactions** (unlock, lock, start the car) - NFC readers in door handle and dashboard (engine start) - Optimized for security and performance - Express mode lets the feature work without Face ID or passcode (turned on by default) - iPhone and car can be offline - Apple doesn't know when you use your car - **Server Interfaces** (key sharing, key management) - Share keys over Messages - Car can be offline when sharing - Apple doesn't know who you share your car key with - Optional access levels (e.g. 'Unlock and Drive', 'Access and drive up to 65 mph') - It's up to each auto maker to define access levels - **Key management** - Manage owner and shared keys from iPhone or car - Keys removed from a device stop working immediately (even if the device is offline) - Easy to change owner device (e.g. when buying a new iPhone) - **System architecture** - Fully integrated into iOS natively - Keys created and stored in Secure Elements and never exported - All features use AES and eliptic-curve cryptography - Offline design based on PKI - Automaker TSM (Trusted Service Manager) not required for simple server integration - **What is a digital car key?** - Binded to the user's device and not to Apple or auto makers - Private key (SK) never leaves SE (Secure Element) - Public key is exported in an X.509 certificate for verification - **Applet** - Implements the car key in the Secure Element - Stores key pair, car public key, secure mailboxes - All car keys hosted in a single applet instance - **Owner pairing flow (online)** 1. PAKE Verifier 2. Pairing password 3. Pairing 4. Cryptographic linking 5. Key activation/registration 6. Key attestation - **Key sharing flow** 1. Owner sends invitation using Messages 2. New key crated in 3. Identity certificate chain 4. Owner verification 5. Attestation returned 6. Offline registration - **Lifecycle of a car key** - Created during owner pairing or key sharing - Transactions - Suspensions - Revocation - Deletion - **Certificates and Transaction** - Owner sharing, key sharing, fast and standard transactions - Take a deeper look at the presented flows and schemes at [11:30](https://developer.apple.com/wwdc20/10006?time=690) - **Radio technologies** - **NFC** - Based on standard NFC reader - Enhanced Contactless Protocol (ECP) - Enables a fully automatic NFC experience - Identifiers available before transaction starts (Reader type, Automaker) - Efficient reader polling - **Ultra Wideband** - iPhone with U1 chip - Use with iPhone in bag or pocket - Common key management architecture - Specification is currently in development - **Server integration** - Required for remote key management - Auto maker server needs to establish connection to Apple's backend (for each environment, e.g. testing and production) - Exchange certificates - Implement and test server interfaces (register a new key, revoke keys, send notifications) - Provide artwork - Connect to automaker app - **Automaker apps** - Provide custom features using keys stored in Wallet - Start owner pairing - Available to automakers - Entitlement is required - Use PassKit APIs - **How to get started (for auto makers)** - Car Connectivity Consortium - Digital Key Specification 2.0 - Digital Key Specification 3.0 (in development, will support Ultra Wideband) - [carconnectivity.org](https://carconnectivity.org/) - Entroll to [Apple MFi Program](https://mfi.apple.com/contact) ## Optimize the Core Image pipeline for your video app https://developer.apple.com/wwdc20/10008 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Edit and play back HDR video with AVFoundation https://developer.apple.com/wwdc20/10009 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Export HDR media in your app with AVFoundation https://developer.apple.com/wwdc20/10010 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Author fragmented MPEG-4 content with AVAssetWriter https://developer.apple.com/wwdc20/10011 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Discover ray tracing with Metal https://developer.apple.com/wwdc20/10012 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Get to know Metal function pointers https://developer.apple.com/wwdc20/10013 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Core Data: Sundries and maxims https://developer.apple.com/wwdc20/10017 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## App accessibility for Switch Control https://developer.apple.com/wwdc20/10019 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Make your app visually accessible https://developer.apple.com/wwdc20/10020 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build Metal-based Core Image kernels with Xcode https://developer.apple.com/wwdc20/10021 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create a seamless speech experience in your apps https://developer.apple.com/wwdc20/10022 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Lists in UICollectionView https://developer.apple.com/wwdc20/10026 Presenters: _Michael Ochs_ - Lists in iOS 14 Collection Views present `UITableView`-like appearances in `UICollectionView` - Improved self-sizing support: now default when using lists in `UICollectionView` - Build cells with AutoLayout and let collection view take over - Override `preferredLayoutAttributesFittingAttributes:` on cell subclasses to exercise manual sizing - [**UICollectionLayoutListConfiguration**](https://developer.apple.com/documentation/uikit/uicollectionlayoutlistconfiguration) - The only new type required on the layout side to build lists in collection view - Built on top of `NSCollectionLayoutSection` and `UICollectionViewCompositionalLayout`: check out [Advances in Collection View Layout](https://developer.apple.com/videos/play/wwdc2019/215) - Adds two list-exclusive styles: `.sidebar` and `.sidebarPlain` for building multicolumn apps on iPadOS 14 - Options to show/hide separators and configure list headers/footers - Creating lists - Easy way 1. Create a `UICollectionLayoutListConfiguration` 2. Create a `UICollectionViewCompositionalLayout` with the configuration - **Per-section setup** 1. Create a `UICollectionLayoutListConfiguration` 2. Create a `NSCollectionLayoutSection` with the configuration 3. Place the above code inside existing section provider initializer on compositional layout 4. Customize the layout on a per section basis - Configuring list section headers/footers - List headers/footers have to be explicitly enabled - Register headers/footers as supplementary views - Set header/footer configuration mode to 'supplementary' - **Provide a supplementary view** when rendering the header/footer on screen - **Set `headerMode` to `firstItemInSection` (headers-only)** - Configure the first collection view cell to look like a header - Recommended for hierarchical data structures and snapshot APIs: check out [Advances in Diffable Data Source](https://developer.apple.com/videos/play/wwdc2020/10045/) - Data source need to be aware of first cell being header - **[UICollectionViewListCell](https://developer.apple.com/documentation/uikit/uicollectionviewlistcell?language=objc)** - Subclass of `UICollectionViewCell`, can be used interchangeably - Better support to configure separator insets and cell content indentations - Features Swipe Actions - Better accessories API - Granted access to default system content/background configurations: check out [Modern Cell Configuration](https://developer.apple.com/videos/play/wwdc2020/10027) - Separator Layout Guide - Separators are supposed to line up with **primary** cell content - Constrain this layout guide to the content: opposite of UIKit layout guides 1. Configure the cell's layout 2. Constrain the separator layout guide's leading anchor to cell's primary content's leading anchor - Automatically handled when using system provided content configurations - Swipe Actions - Only supported if the cell is rendered inside sections configured using a list configuration - Override the leading/trailing swipe action's configuration getter to configure - **Caution**: never capture the index path (unstable) of the cell being configured in action handler - Directly capture the data model - Capture a stable identifier of the cell: - Diffable Data Source and its stable item identifier - The new cell registration type in iOS 14: UICollectionViewListCell - Accessories API of list cells - Options to configure both leading and trailing side of the cell - Configure multiple accessories on the same side - Functionalities on list cell accessories - Re-ordering accessory: cell is automatically in re-rodering mode when tapped - Delete accessory: cell automatically reveals configured trailing swipe actions when tapped - Outline disclosure accessory - Cell automatically communicate with the data source and expand/collapse its children when tapped - Requires the new section snapshot APIs: check out [Advances in Diffable Data Source](https://developer.apple.com/videos/play/wwdc2020/10045/) - Plenty of system defaults are provided while customizabilities are kept ## Modern cell configuration https://developer.apple.com/wwdc20/10027 Presenter: _Tylor Fox_ - **Getting started with configurations** - In iOS 13, we use the built-in imageView and textLabel properties on `UITableViewCell` to display an image and some text. - In iOS 14, we use the content configuration to describe the cell appearance for a specific state - This is how you configure a cell using a content configuration: - `var content = cell.defaultContentConfiguration()` This always returns a fresh configuration without any content set on it. Don't need to think about the old state at all. - Set the image and text on the content configuration. - `cell.contentConfiguration = content` As soon as we call this, the cell is updated to display the image and text that we specified. - Same code to configure any cell and any view that supports content configurations. - Composable, lightweight, very inexpensive to create and built for performance - **Configuration types** - Background Configuration - let you set things such as background color, visual effect, stroke, insets, corner radius and custom view - List Content Configuration - let you set things such as image, text, secondary text, layout metrics and behaviors - **Configuration state** - Configuration state represents the various inputs that you use to configure your cells and views. - Each cell, header and footer has its own configuration state. - **Two Types** - **View configuration state** - Trait collection - 4 states: highlighted, selected, disabled and focused - Custom state: this is key-value storage to add any extra states or data that use to configuring your view. - **Cell configuration state** - Everything from the View configuration state - Editing, swiped, expanded - Drag and drop states - When `automaticallyUpdatesContentConfiguration` is true, The cell automatically calls `updated(for:)` on its contentConfiguration when the cellโ€™s configurationState changes, and applies the updated configuration back to the cell. The default value is true. - When `automaticallyUpdatesBackgroundConfiguration` is true, the cell automatically calls `updated(for:)` on its backgroundConfiguration when the cellโ€™s configurationState changes, and applies the updated configuration back to the cell. The default value is true. - You can override `updateConfiguration(using:)` to manually update and customize the content configuration, disable automatic updates by setting this property to false. This method is called before your cell first displays and will be called anytime the configuration state have changed. ## Meet WidgetKit https://developer.apple.com/wwdc20/10028 Presenters: _Nahir Khan, Neil Desai_ - Widgets are now used across all platforms - Great widgets are glancable, relevant and personalized - **Smart stacks** are collections of widgets and automatically show the right one on top using on-device intelligence - Widgets support **configuration** by tapping them - this is realized using **intents** similar to SiriKit - e.g. choosing the city in a Weather app - UI built entirely in SwiftUI - **How WidgetKit works** - WidgetKit extensions are background extensions - They return a series of view hierarchies in a time line - Time line is sent to the home screen which presents the right view at the right time - Since views are "ready" they can be re-used at different points in the system, e.g. the Widget Gallery - Time line is refreshed from main app and updates are scheduled by extension - Imagine the Calendar time line for the day. One event is updated from Calendar, which then wakes up the extension and provides the new time line. - **Building a Widget** - Single Widget Extension supports multiple kinds of widgets on different platforms - **Possible configurations:** `Static` (Workout widget) or `Intent-Based` (Reminder widget that can be personalized) - **Supported Families:** A widget can enable one or many of the following families: `systemSmall`, `systemMedium`, `systemLarge` - Widget struct must conform to `Widget` and its body to `WidgetConfiguration` - **How to build a glancable experience** - Widgets are **not** mini apps they rather project content on the home screen - No scrolling - No videos or animated images - Tap interactions to deep link into main app. Widget associable with a URL link using the widgetURL API (use the new Link API of SwiftUI) - Important new view types: - `Placeholder` - Should not contain user data - Great placeholder UIs show a representation of what kind your data is - `Snapshot` - Represent a single entry in time - Should return a view as quickly as possible - Used to display your widget in the gallery - Use it as the first entry in your time line so users get what they see in the gallery - `Time line` - Combination of views and dates - Output if WidgetKit extension is serialized to disk which enabled rendering of individual entries just in time - **Reloads** - Wake up the extension and ask for a new time line - Help to ensure that content is up to date - Get a `TimelineProvider` by `struct Provider: TimelineProvider` - Implement `func snapshot(...)` and `func timeline(...)` for returning the respective data - Provide a reload policy at Time line cretion time to tell when the time line should be reloaded: `atEnd`, `after(date: Date)`, `never` - System determines the best time to reload the widget, e.g. based on: - Background notification - Significant time change - Changes in the app made by the user, e.g. new Calendar entry - Use `WidgetCenter.[reloadTimelines(ofKind:), reloadAllTimelined]` to programmatically reload time lines - Get current configurations with `WidgetCenter.getCurrentConfigurations(completion:)` - Use batch requests - Do not overuse networking from a widget - Use `onBackgroundURLSessionEvents` modifier to launch a network task which delivers the result to your extension - Reloads are budgeted by the system, do not overuse them - **Personalization** - Use the `Intents` framework, known from Siri, to customize the widgets behavior - Use the new **In-App Intent Handling** to answer requests from your widget - `IntentConfiguration` is used to power intent-based widget configurations - `IntentTimelineProvider` is used to generate specific time lines - **Intelligence** - Widgets are displayed on the home screen by on-device intelligence - Your app can donate shortcuts - Widget extension can annotate time line entries using `TimelineEntryRelevance` with its score and duration properties ## Stacks, Grids, and Outlines in SwiftUI https://developer.apple.com/wwdc20/10031 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build SwiftUI views for widgets https://developer.apple.com/wwdc20/10033 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Widgets Code-along, part 1: The adventure begins https://developer.apple.com/wwdc20/10034 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Widgets Code-along, part 2: Alternate timelines https://developer.apple.com/wwdc20/10035 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Widgets Code-along, part 3: Advancing timelines https://developer.apple.com/wwdc20/10036 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## App essentials in SwiftUI https://developer.apple.com/wwdc20/10037 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build document-based apps in SwiftUI https://developer.apple.com/wwdc20/10039 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Data Essentials in SwiftUI https://developer.apple.com/wwdc20/10040 Presenters: _Curt Clifton, Luca Bernardi, Raj Ramamurthy_ - **Getting Started** - Always ask you the following questions: - What data does my view need? - How will the view manipulate this date? - Where will the data come from? - Immutable views, that just display data, contain only let properties - Pull multiple properties in their own **config object** - The config object can contain functions to mutate its state - Using `@State private var config: ConfigObject()` to re-render your view after `config` changed - Let parent and sub views communicate over a single config object by sharing it using `@Binding var config` - Pass `config` down by marking the it as reference using the dollar symbol: `SubView(config: $config)` - **Modeling Data Using ObservableObject** - Class-constrained protocol (only adoptable by reference types) - Can be used to achieve super-custom behaviors, e.g. _backing data by a service or server_ - Conform by implementing `var objectWillChange: Self.ObjectWillChangePublisher { get }` - Use to **manage data life cycle**, **handle side-effects**, **integrate with existing components** - Will be your source of truth - Doesn't need to be your full data model - split into multiple observable objects if your model is complex - Use a single ObservableObject for all your views if your data model is simple - Mark properties of your ObservableObject, your view is interested in as `@Published var progress: Double` - **How to create an ObservableObject dependency?** - `@ObservedObject` - `@ObservedObject var config: Configuration` - You need to manage the objects ownership outside of your view - Create a binding to any value-type property of the ObservableObject to pass it into e.g. `$config.isFinished` a `Toggle` control and let it automatically update your view - `@StateObject` - SwiftUI owns the ObservableObject - Creation/destruction is tied to view's life cycle - Instantiated just before body runs - Use it to implement e.g. an `ImageLoader: ObservableObject` with a `@published var image: Image` property - Whenever `@StateObject` changes the view is re-rendered and thus populated with the image - `EnvironmentObject` - In SwiftUI you typically have a hierarchy of many modular sub views - To avoid a lot of boilerplate by passing around ObservableObject's pass it to `.environmentObject(...)` on your root view - Changes to it, from any view in the hierarchy, will be reflected in any other view - **SwiftUI Performance Considerations** - **Avoid slow view updates** - Make view initializers cheap, e.g. no dispatches - Make body a pure function - Avoid assumptions - New event sources: `onChange`, `onOpenURL`, `onContinueUserActivity` - run on main thread - **Who owns the data?** - Share data in a common ancestor - Leverage `@StateObject` - Consider placing global data in `App` and pass it down the view hierarchy. Changes to it will re-render **all** scenes (instances/windows) of your app - New 2020: Property Wrappers that offer **data persistence across app restarts** and can be used as source of truth - `@SceneStorage` - Per-scene property wrapper for reading/writing data managed by SwiftUI - Light-weight storage for your views data - Use it to populate your collection views - `@AppStorage` - App-scoped global storage, persisted using `UserDefaults`, usable anywhere (app/view) - Perfect for storing settings - `@AppStorage("amountOfGold") private var amountOfGold = 5000` - Automatically reads/writes from/to UserDefaults whenever the property changes ## What's new in SwiftUI https://developer.apple.com/wwdc20/10041 Presenters: _Matt Ricketson, Taylor Kelly_ - **Apps** - Bild your whole app using SwiftUI: `struct BookClubApp: App` - Apps can declare data dependencies - Use `WindowGroup` to manage windows platform independent. Supports multiple windows on macOS and iPadOS out of the bos - Use `Settings` to get a preference pane for free โ€ข available on macOS - Use `DocumentGroup` scene type to automatically handle opening, saving and editing documents โ€ขย macOS, iOS, iPadOS - Use `CommandMenu` command to add additional menus to the menu bar including keyboard shortcuts - New multi-platform templates specifically for SwiftUI apps - `LaunchScreen` Info.plist key to configure your launch screen โ€ขย simple alternative to the storyboard - **Widgets** - iOS, iPadOS, macOS exclusively built using SwiftUI - Declared by `struct YourWidget: Widget` and `var body: some WidgetConfiguration` - Use SwiftUI to build custom complications for watchOS - **Lists and Collections** - List now receive outlines to quickly access the lists content โ€ขย reduces the need for push/pop navigation patterns - Lazy loading grid layouts (`Lazy[V|H]Stack`) to reduce memory footprint and preserve smooth scrolling for large amounts of data - View Builder for switch statements to show e.g. different image styles in a list of images - **Toolbars and Controls** - `.toolbar` modifier for unified display of toolbars - Use `ToolbarItem(placement: .principal)` to make an item prominent - Use `ToolbarItem(placement: .bottomBar)` to place an item in the bottom bar - When using `Label("Title", systemImage: "sf.symbol.name")` SwiftUI automatically display icon and/or text depending on where the label is displayed: toolbar, list, ... - `.keyboardShortcut` modifier can now be used for additional controls like `Button` - New default focus support in tvOS - New controls: - `ProgressView("Downloading", value: progress)` - horizontal bar - `ProgressView("Downloading", value: progress).progressViewStyle(CircularViewStyle())` - circular progress indicator - `ProgressView()` - spinner - `Gauge` to indicate the level of value โ€ขย can contain value labels and min/max value labels - **New effects and styling** - New control center UI with beautiful transitions - `.matchedGeometryEffect` to provide smooth animations inside of a grid of UI elements - `.clipShape(ContainerRelativeShape())` to automatically apply a super views shape to the subview - custom fonts automatically scaled with dynamic type changes - Custom accent color directly form the AssetCatalog on all platforms - Many controls can now be tinted - **System integration** - New `Link` control to display URLs in link style and open them with the default browser โ€ขย also supports url schemes to open other apps - `@Environment(\.openURL) private var openURL` to programmatically open urls via `openURL(url)` in your views - `onDrag {}` and `onDrop {}` to support drag & drop - `UniformTypeIdentifers` framework for e.g. introspection of file types - `Sign in with Apple` as first class component in SwiftUI โ€ข available on every platform - Other Frameworks: **AuthenticationServices**, **AVKit**, **MapKit**, **SceneKit**, **SpriteKit** ## Build SwiftUI apps for tvOS https://developer.apple.com/wwdc20/10042 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build an Action Classifier with Create ML https://developer.apple.com/wwdc20/10043 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Advances in diffable data sources https://developer.apple.com/wwdc20/10045 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create complications for Apple Watch https://developer.apple.com/wwdc20/10046 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Enable encrypted DNS https://developer.apple.com/wwdc20/10047 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build complications in SwiftUI https://developer.apple.com/wwdc20/10048 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Keep your complications up to date https://developer.apple.com/wwdc20/10049 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build with iOS pickers, menus and actions https://developer.apple.com/wwdc20/10052 Presenters: _Eric Dudiac, David Duncan_ - **UISlider and UIProgressView:** More consistent across platforms now - **UIActivityIndicatorView:** New simpler design, Use color API and modern styles, Updates "pull-to-refresh" - **UIPickerView:** Updated styling - **UIPageControl** - New interactions (scrubbing, scrolling) - Unlimited pages - Optional custom indicator icons: `.preferredIndicatorImage(UIImage())` to set all or `.setIndicatorImage(UIImage(), forPage: 0)` for a specific image - Multiple styles: `.backgroundStyle = .prominent` to highlight the background - **UIColorPickerViewController** - New view controller for picking colors - Eyedropper, Favorites, Hex specification - **UIDatePicker** - New compact style to select date and time - In-line style on iOS - great for iPad or if date picking is primary UI (matches modal presentation) - Useful when you have space constraints - Full modal calendar when selecting dates - Keyboard for selecting times - New macOS style (10.15.4) - Compact, modal calendar presentation - Supported in Catalyst apps - **Menus** - Provided on `UIControl` - Directly supported by UIButton and UIBarButtonItem by `button.menu = UIMenu(...)` - Triggered via long-press by default - Show the menu by a simple tap by setting `button.showsMenuAsPrimaryAction = true` and don't provide a primary action - Back buttons implement menus to quickly jump back in navigation stack - Take action when the menu action is recognized, register for `UIControl.Event.menuActionTriggered` - `UIDeferredMenuElement` to async provide menu items - `UIContextMenuInteraction` to modify or replace provided menu `updateVisibleMenu(_ block menu: (UIMenu) -> UIMenu)` - Use `UIContextMenuInteraction.rich` to display previews and `.compact` to only show a menu - New `UIBarButtonItem` initializers `init(systemItem:primaryAction:menu:)`, `init(title:image:primaryAction:menu:)` - New `UIBarButtonItem` `.fixedSpace()` and `.flexibleSpace` - `UIButton` can finally be initialized using an `UIAction`: `init(type:primaryAction:)` -> **native block based API** - `UISegmentedControls` can now finally be initialized using `UIActions` -> **native block based API** ## Optimize the interface of your Mac Catalyst app https://developer.apple.com/wwdc20/10056 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Identify trends with the Power and Performance API https://developer.apple.com/wwdc20/10057 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design high quality Siri media interactions https://developer.apple.com/wwdc20/10060 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Expand your SiriKit Media Intents to more platforms https://developer.apple.com/wwdc20/10061 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Background execution demystified https://developer.apple.com/wwdc20/10063 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in SiriKit and Shortcuts https://developer.apple.com/wwdc20/10068 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Evaluate and optimize voice interaction for your app https://developer.apple.com/wwdc20/10071 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Empower your intents https://developer.apple.com/wwdc20/10073 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Decipher and deal with common Siri errors https://developer.apple.com/wwdc20/10074 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Diagnose performance issues with the Xcode Organizer https://developer.apple.com/wwdc20/10076 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Eliminate animation hitches with XCTest https://developer.apple.com/wwdc20/10077 Presenter: _Tanuja Mohan_ - **Hitch:** A frame appears on screen later than expected - **VSYNC:** Time the screen swaps the frame onto the display - **Hitch time:** Time in *ms* that a frame is late to display - **Hitch ratio:** Hitch time in **ms** per second for a given duration - Apple doesn't use frames per second (fps) since: - 60 or 120 fps is not always the desired target - Display may intentionally not be updated - Target frame rate may intentionally be lower than possible - Hitch ratio is always comparable across tests, following ratios are recommended: - Good: < 5ms/s - Warning: 5..10ms/s - users will start recognizing hitches - Critical: >10ms/s - Can be measured using `XCTestMetrics` and unit tests or for production apps using `MetricsKit` and Xcode Organizer - `XCTOSSignpostMetric` gives you the following when using an animation os_signpost interval: - Duration - Total count of hitches - Total duration of hitches - Hitch time ratio - Frame rate - Frame count - Specify an animation os_signpost interval by: - `os_signpost(.animationBegin, log: logHandle, name: "performanceAnimationInterval")` - `os_signpost(.end, log: logHandle, name: "performanceAnimationInterval")` - UIKit has pre-defined metrics: - `XCTOSSignpostMetric.navigationTransitionMetric` - `XCTOSSignpostMetric.customNavigationTransitionMetric` - `XCTOSSignpostMetric.scrollDecelerationMetric` - `XCTOSSignpostMetric.scrollDraggingMetric` - Application state can be reset to avoid tests influencing themselves: `XCTMeasureOptions().invocationOptions = [.manualStop]` - Listen to a live testing session at [8:15](https://developer.apple.com/wwdc20/10077/?time=498) ## Why is my app getting killed? https://developer.apple.com/wwdc20/10078 Presenter: _Andy Aude_ - **Most common reasons why apps can be terminated in the background** - **Crash** - Segmentation fault - Illegal instruction - Asserts and uncaught exceptions - **CPU resource limit** - High sustained CPU load in background - Energy Exception Report - Xcode Organizer - [`MXCPUExceptionDiagnostic`](https://developer.apple.com/documentation/metrickit/mxcpuexceptiondiagnostic) - Reports contain call stack points out hotspots in code - Consider moving work into [`BGProcessingTask`](https://developer.apple.com/documentation/backgroundtasks/bgprocessingtask) - **Watchdog** - Long hang during key app transitions - `application(_:didFinishLaunchingWithOptions:)` - `applicationDidEnterBackground(_:)` - `applicationWillEnterForeground(_:)` - These transitions have a time limit on the order of 20 seconds - Terminations are disabled in Simulator and in the Debugger - Eliminate deadlocks, infinite loops, synchronous work - Report available via [`MXCrashDiagnostic`](https://developer.apple.com/documentation/metrickit/mxcrashdiagnostic) - **Memory limit exceeded** - App using too much memory - Same limit for foreground and background - Use Instruments and Memory Debugger - Keep in mind older devices - **Memory pressure exit** (jetsam) - Not a bug with your app - Most common termination - System freeing up memory for active applications - Reducing jetsame rate - Aim for less than 50MB in background - Upon background flush state to disk, clear out image views, drop caches - Recovering from jetsame - Save state upon entering background - Adopt UIKit State Restoration - User should not realize app was terminated - **Background task timeout** - [`UIApplication.beginBackgroundTask(expirationHandler:)`](https://developer.apple.com/documentation/uikit/uiapplication/1623031-beginbackgroundtask) - [`UIApplication.endBackgroundTask(_:)`](https://developer.apple.com/documentation/uikit/uiapplication/1622970-endbackgroundtask) - Failure to end the task explicitly result in termination - Counts exposed via [`MXBackgroundExitData`](https://developer.apple.com/documentation/metrickit/mxbackgroundexitdata) - Preventable - Use the named variant of the UIKit API [`beginBackgroundTask(withName:expirationHandler:)`](https://developer.apple.com/documentation/uikit/uiapplication/1623051-beginbackgroundtask) - Terminations do not occur in Debugger - New console message in iOS 13.4 (_Background Task DatabaseTransaction was created over 30 seconds ago. In Applications running in the background, this creates a risk of termination. Remember to call `endBackgroundTask` for your task in a timely manner to avoid this._) - Expiration handler - Implement an `expirationHandler` - Call `endBackgroundTask(_:)` inside the handler - Do not begin new work - Do not rely on it exclusively - Add telemetry at the start and end of each expiration handler - Inspect [`MXMetricPayload`](https://developer.apple.com/documentation/metrickit/mxmetricpayload) - Check [`backgroundTimeRemaining`](https://developer.apple.com/documentation/uikit/uiapplication/1623029-backgroundtimeremaining) - Only start work if plenty of time remains - Unsafe to begin tasks with < 5 seconds remaining - Avoid leaking [`UIBackgroundTaskIdentifier`](https://developer.apple.com/documentation/uikit/uibackgroundtaskidentifier) - **New MetricKit API (iOS 14)** - [`MXBackgroundExitData`](https://developer.apple.com/documentation/metrickit/mxbackgroundexitdata) shows how often these terminations happen providing counts of each termination type - `cumulativeBadAccessExitCount` - `cumulativeIllegalInstructionExitCount` - `cumulativeAbnormalExitCount` - `cumulativeMemoryResourceLimitExitCount` - `cumulativeMemoryPressureExitCount` - `cumulativeSuspendedWithLockedFileExitCount` - `cumulativeAppWatchdogExitCount` - `cumulativeBackgroundTaskAssertionTimeoutExitCount` - `cumulativeNormalExitCount` - Crash reporting via MetricKit - Diagnostics on a per-device basis - Ability to get crash info programmatically directly from the device - [`MXCrashDiagnostic`](https://developer.apple.com/documentation/metrickit/mxcrashdiagnostic) - Stack trace - Signal - Exception code - Termination reason - Check out [What's New in MetricKit](https://github.com/Blackjacx/WWDC#whats-new-in-metrickit) to get detailed information - **How to improve multi-tasking experience?** - Identify and fix terminations - Reduce memory usage - Implement state restoration ## What's new in MetricKit https://developer.apple.com/wwdc20/10081 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Integrate your app with Wind Down https://developer.apple.com/wwdc20/10083 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Feature your actions in the Shortcuts app https://developer.apple.com/wwdc20/10084 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for intelligence: Apps, evolved https://developer.apple.com/wwdc20/10086 Presenter: _Mark Mikin_ - This is one of those "why" sessions. Why we should build something? - **Intelligent System Experience** - The main idea is to be proactive - Intelligence is how the OS works with the apps that people use every day to make the "every day" easier for people - Intelligence is design (it should be viewed as a design practice) - **Living design**. What is that? - The core job of the designer is to help people accomplish something - One of the key ways a designer can leverage this is by using elements familiar to the user - People use a signifier or a symbol - For example, "Share" button. In the case of iOS, almost everyone can easily recognize the "default" share symbol because it consistently gets used across a lot of apps - Intelligence is a platform convention, it's in a static glyph or icon, like the share button. It's live - Intelligence manifests itself by adapting to how the system, the platform, conforms to how people use their devices - Intelligence is expected (people expect their devices and apps to be smart) - **Extensibility** - Intelligence is powered by an app through extensibility - Apps have actually been evolving over time - A lot of the technologies built by Apple that are foundational to the intelligence system (starting from App Extensions debuted at WWDC 2014 and ending with App Clips so far) - It's built to help growing ecosystem of devices and apps - Intelligence system is built from a foundation of respecting users privacy - In the next sessions about system intelligence, Apple's team will try to cover it from a few different angles ## Design for intelligence: Make friends with "The System" https://developer.apple.com/wwdc20/10087 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for intelligence: Discover new opportunities https://developer.apple.com/wwdc20/10088 Presenters: _JP Lacerda_ - **Intelligence** - Goal to make your Apple products knowing/understanding you - Achieve and Discover more, Less tedium, Fewer distraction - System helps you through suggestions from **Siri**, **Shortcuts**, **Suggestions**, **Widgets** - **Siri / Shortcuts** - Helps you getting things done by a single tap or asking Siri - Helps you setting up simple and complex operations ran, e.g. just by your voice - View shortcuts through the new Siri suggestion Widget displayed just at the right time to you using the new smart stack and on-device intelligence - Siri suggestions automatically appear at the right place and time, e.g. restaurant reservations are added automatically to the calendar - Siri can remind you when it's time to leave right on your lock screen - Get Siri suggestions in Maps to e.g. conveniently find your way to the Airport - **Privacy / Analytics** - Apple chose opt-in to enable analytics on your device to help improve their intelligence services - **Examples** - 82% of all notification-based check-ins come from suggestions (data from some Airline apps) - Apps are visible on average 5x more per day via lock screen, sharing suggestion, search or other entry points - **Give your app superpowers** - Think about which entry points are suitable for your app - Consider how you can measure the impact of intelligence on your app - Understand intelligence from the users perspective ## Discover Core Image debugging techniques https://developer.apple.com/wwdc20/10089 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Decode ProRes with AVFoundation and VideoToolbox https://developer.apple.com/wwdc20/10090 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Write tests to fail https://developer.apple.com/wwdc20/10091 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build for the iPadOS pointer https://developer.apple.com/wwdc20/10093 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Handle trackpad and mouse input https://developer.apple.com/wwdc20/10094 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## The Push Notifications primer https://developer.apple.com/wwdc20/10095 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore Packages and Projects with Xcode Playgrounds https://developer.apple.com/wwdc20/10096 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Advances in UICollectionView https://developer.apple.com/wwdc20/10097 Presenters: _Steve Breen_ - **Diffable Data Source** - Recap - `UICollectionView` was first released in iOS 6 - `UICollectionView` was built on the separation of concerns between the data, or the "what"; from the layout, the "where" content is being rendered. - For layout, an abstract class is `UICollectionViewLayout`, and a concrete subclass is `UICollectionViewFlowLayout`. - For the presentation, there are `UICollectionViewCell` and `UICollectionReusableView`. - In iOS 13, there are two new components for Data and Layout respectively with Diffable Data Source and Compositional Layout. - Section snapshot [New in iOS 14] - Allow data sources to be more composable into section-sized chunks of data. - Allow modeling of hierarchical data, which is needed to support rendering outline-style UIs. - **Compositional Layout** - Recap - Compositional Layout was introduced in iOS 13 - Allows us to build rich, complex layouts by composing smaller, easy-to-reason bits of layout together. - Describes what the layout to look like instead of how the layout ought to work. - Section-specific layouts to help you build more sophisticated UIs - Support for orthogonal scrolling sections. - **Lists [New in iOS 14]** - `UITableView`-like sections right in to any `UICollectionView`. - Rich with features you've come to expect from `UITableView`, like swipe actions and many common cell layouts. - Easily mix and match Lists with other kinds of layout on a per-section basis. - Concrete `UICollectionViewListCell`, header and footer support - New Sidebar appearance we see in many iPadOS system apps. - **Modern Cells** - Cell registrations - Simple, reusable way to set up a cell from a view model. - Eliminate the extra step of registering a cell class or nib to associate it with a reuse identifier. - Use a generic registration type which incorporates a configuration closure for setting up a new cell from a view model. - Cell content configurations. - Standardized layouts for cells similar to what is seen in `UITableView` standard cell types. - Can be used with any cell, or even a generic UIView. - Background configurations. - Similar to content configurations but apply to any cell's background with the ability to adjust properties such as color, border styles and more. ## What's new in Universal Links https://developer.apple.com/wwdc20/10098 Presenter: _Christopher Linn_ - **Universal Links** - HTTPS URLs that represent your content both on the web and in your app - Allow to open your app instead of browser - Enable by adding an entitlement to your app and a JSON file to your web server - creates secure association between both - Custom URL schemes not recommended anymore - switch as soon as possible - **Support for watchOS** - Same functionalities like on iOS, tvOS and macOS - Apply entitlement to your WatchKit extension - not your WatchKit App - Use `[WKExtensionDelegate.handle(_ userActivity: NSUserActivity) -> Void](https://developer.apple.com/documentation/watchkit/wkextensiondelegate/2798966-handle)` to handle Universal Links - Use `[WKExtension.shared().openSystemURL(url)](https://developer.apple.com/documentation/watchkit/wkextension/1628224-opensystemurl)` to open Universal Links in other apps - Different API on iOS (UIKit) and macOS (AppKit) - **Universal Links in SwiftUI** - Now it is possible to handle Universal Links equally on all platforms - Handle Universal Links using `.onOpenURL { url in /* ... */ }` - Open Universal Links in other apps using `@Environment (\.openURL) var openURL; let url = /* ... */; openURL(url)` - **Enhanced Pattern Matching** - `*` matches zero or more characters greedily - `?` matches any one character - `*?` matches at least one character - `"components": [{ "/": "/sourdough/?*", "caseSensitive": false }]` for case-insensitive pattern matching (macOS Catalina 10.15.5 and iOS 13.5) - `"components": [{ "/": "/ไธญๅœ‹ๅ“ฒๅญธๆ›ธ้›ปๅญๅŒ–่จˆๅŠƒ/?*", "percentEncoded": false }]` for Unicode pattern matching (macOS Big Sur and iOS 14) - `"defaults": { "percentEncoded": false, "caseSensitive": false }` to specify defaults for all components (macOS Big Sur and iOS 14) - Apply `defaults` to "details" (includes app IDs and components) or only to "components" to match all elements of the respective arrays - **Substitution Variables** - Named lists of substrings to match against - Names can contain anything but `$`, `(`, `)` - Names are always case sensitive in patterns - Values can contain `?` and `*` but no other substitution variables - Values are case-sensitive by default - Available today in macOS Catalina 10.15.6 and iOS 13.5 - **Predefined Substitution Variables** - `$(alpha)* - match upper and lower case letters` - `$(upper),$(lower)* - match either upper or lower case letters` - `$(alnum)* - match upper and lower case letters including digits` - `$(digit),$(xdigit)* - match either digits or hexadecimal digits` - `$(region)** - match every ISO region code defined by Foundation: Locale.isoRegionCodes` - `$(lang)** - match every ISO language code defined by Foundation: Locale.isoLanguageCodes` - Use `"exclude": true` to exclude specific patterns - Substitution variables can be used to form different combinations of patterns, e.g. show different menus for different countries - **Example** ```json { "appLinks": { "substitutionVariables": { "food": [ "burrito", "sushi" ], "Canadian food": [ "burrito", "poutine", "tรชte-de-violon" ] }, "details": [{ "appIDs": [ "ABCDEF.com..example.restaurant" ], "components": [ { "/": "$(lang)_CA/$(Canadian food)/", "percentEncoded": false } { "/": "$(lang)_CA/$(food)/", "exclude": true } { "/": "$(lang)_$(region)/$(food)/" } ] }] } } ``` - **Universal Links Workflow** - After download of an app the system checks its entitlements to see if it needs any app-association files, and downloads them - App association files can now be downloaded in parallel by connecting to an **Apple CDN** instead of opening one connection per downloaded app - CDN is dedicated to associated domains - CDN uses single HTTP/2 connection for all associated domains on a device - CDN Reduces load on your server - CDN routes devices to a known-good, known-fast connection - **Alternate Modes** for internal domains not reachable from an Apple CDN - **Managed Mode** when distributing within your organization (see [What's New in Managing Apple Devices (WWDC20)](https://github.com/Blackjacx/WWDC#Whats-new-in-managing-Apple-devices)) - System trusted root certificate - MDN admin must opt-in - Works using any profile - **Developer Mode** when building your app - Use any SSL certificate - User must opt-in from `iOS Settings > Developer > Associated Domains Development` or for macOS using the command `swcutil developer-mode -e true` - Only works using a development profile - Server path for all modes: `https://example.com/.well-known/apple-app-site-association` - Specify domains for different modes in the entitlements as `<string>applinks:testing.example.com?mode=developer</string>` (or `?mode=managed` or `?mode=developer+managed`) in an array under the key `com.apple.developer.associated-domains` ## Explore the Action & Vision app https://developer.apple.com/wwdc20/10099 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Keynote โ˜… https://developer.apple.com/wwdc20/101/ - **App Library** - Automatically created at the end of your app pages on the Home Screen - Makes it easier than ever to get to your apps - **Widgets on Home Screen** - Richer UI - more possibilities - Different sizes to choose one that best fits your needs - Droppable on the home screen - Widget gallery to explore all widgets - **SmartStack** as intelligent assistant which enables you to scroll through your widgets - **Picture in Picture** on iPhone - Swipe to the side, out of the screen, and audio keeps playing - Video keeps playing when switching apps - **Siri** - Got smarter and has a new interface which doesn't block your UI anymore - Can now send audio messages using the messages app - completely hands free - **Translate** as new app of offline conversation translate - Conversation mode when switching to landscape mode in the app - **Messages** - Pinning messages to the top of the screen - Memoji gets hundreds of new options to customize your avatar, including masts, fist-pumps and more - Group conversations got some โค๏ธ by adding inline replies and most-active member widget - **Maps** - More countries like UK, Ireland and Canada - It gets easier to find places you love and how you get there in an ecological way - Maps offers **Guides** that help you discover great new places - Brand new **cycling** option to reduce your carbon footprint - **EV-Routing** option to optimize your route for electric cars - e.g. by selecting routes with charging station on your way - **CarPlay** - New wallpaper option - New categories for CarPlay apps: Parking, EV-Charging, and Quick-Food ordering - Car Key API - first supported by BMW - enable open/close/start your car - **App Clips** as small, fast parts of an app, designed for speed - A way to discover what the App Store has to offer - Launchable from the web, by NFC tags, QR codes or the brand new Apple designed tags - Needs to be smaller than 10 MB - Use Sign in With Apple to provide the most seamless app experience - Use Apply Pay to allow quick payments - Option to download the full app - **iPadOS** - Photos app gets an all new side bar - new way to navigate and organize your photos - Incoming calls become unobtrusive using notification style UI (available for all apps: WhatsApp, Skype, ...) โ€ขย available for iOS too - New searching experience - **Apple Pencil** - **Scribble** lets you hand-write in any text field. iOS converts your writing then to text - **Smart Selection** lets you select single words / characters you've written using your pencil using iOS text recognition features - DataDetectors are used to automatically detect e.g. phone numbers, email addresses - **AirPods** - are now able to automatically switch to new incoming audio sources - **Spatial Audio** for AirPods Pro (AirPods Motion API) to emulate movie theatre experience using AirPods gyroscope to sync the sound to your head position/orientation - **watchOS 7** - Configure your own watch faces styled by your current living style - Watch faces can now be shared on Websites or via the usual sharing features of watchOS - Workout app adds dance, cooldown, functional training and more workouts plus it is renamed to **Fitness** - **Sleep Tracking** is a new app that helps you to get to bed at time using `Wind Down` which dims all distractions (also available in iPhone) - **Handwashing detection** to make sure you wash as long as you're supposed to (20 seconds shown in demo) - **Privacy Improvements** - **Location** only share rough location - **Camera** ... - **Tracking Control** require apps to ask before tracking - **App Privacy** makes data tracked by developers visible to the users before they download the app - **Home** - Alliance among different manufacturers to make smart home devices even better - **Adaptive lighting** to auto-adjust color temperature throughout the day - **Cameras** get activity zones, richer notifications - **Face recognition** extends to Home Pod - **Camera** content can be displayed on TV via your Apple TV - **Apple TV** - Picture in Picture - Better Airplay in full 4K - Apple TV+ already on over 1 billion devices - **Foundation** as newest production only available on Apple TV+ - **macOS Big Sur** - use of a lot of translucency - Design refresh for all system apps - New side and compact, space efficient toolbars - Control center now on the mac - **Notification Center** - Notification grouping - iOS widgets also available on the mac - **Messages** with new search, photo picker, messages effects, pin conversations, inline replies and more - **Maps** with indoor-maps, favorites, ETA from friends and all of it implemented using Catalyst - **Safari** with 50% faster page loading, Privacy Report via toolbar button, Web Extensions API, built-in translation - **Mac** - Processor-transition to **Apple Silicon** - Apple's own processor line - bye bye Intel ๐Ÿ‘‹ - **Universal 2** is the new universal binary type that contains binaries compiled for both architectures - **Rosetta 2** lets existing app run on new architectures from day one by making them compatible at installation time - Supports iPhone and iPad apps **directly** ## Meet Watch Face Sharing https://developer.apple.com/wwdc20/10100 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design great widgets https://developer.apple.com/wwdc20/10103 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Adopt the new look of macOS https://developer.apple.com/wwdc20/10104 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build for iPad https://developer.apple.com/wwdc20/10105 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Meet Scribble for iPad https://developer.apple.com/wwdc20/10106 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in PencilKit https://developer.apple.com/wwdc20/10107 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Support hardware keyboards in your app https://developer.apple.com/wwdc20/10109 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Support local network privacy in your app https://developer.apple.com/wwdc20/10110 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Boost performance and security with modern networking https://developer.apple.com/wwdc20/10111 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build local push connectivity for restricted networks https://developer.apple.com/wwdc20/10113 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## iPad and iPhone apps on Apple Silicon Macs https://developer.apple.com/wwdc20/10114 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## AutoFill everywhere https://developer.apple.com/wwdc20/10115 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## VoiceOver efficiency with custom rotors https://developer.apple.com/wwdc20/10116 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Accessibility design for Mac Catalyst https://developer.apple.com/wwdc20/10117 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create app clips for other businesses https://developer.apple.com/wwdc20/10118 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Introduction to SwiftUI https://developer.apple.com/wwdc20/10119 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Streamline your app clip https://developer.apple.com/wwdc20/10120 Presenters: _Yongjun Zhang, Luming Yin_ - **Best practices** - Focus on essential tasks - Limit the features. Reserve complex features for your app - Require all assets for initial experience - Do not include splash screens - Avoid requiring people to sign up _before_ finishing their task - Only ask for location and notification permissions if needed (more on this below) - Make sure your App Clip has the same name and icon as your app - Put shared assets in a shared asset catalog - Authentication - Support Sign in with Apple - Use `ASWebAuthenticationSession` for other federated login - Offer username and password login for existing users - Offer "Sign In With Apple" upgrade in the app - For privacy reasons, and because App Clips are ephemeral, some contents are not available to App Clips, such as HealthKit info - App Clips can request permission to use Bluetooth, the camera, and microphone - **Streamlining Transactions** - 2 new types of ephemeral permissions: Location and Notification - Allows App Clips to check if the user is within a region, **without prompting for location permission** - Add `NSAppClipRequestLocationConfirmation` with value `true` in your `Info.plist` to enable this - Supports checking a region with a radius of up to 500 meters - Allows App Clips to send notifications for up to 8 hours after each launch, **without prompting for notification permission**. - Add `NSAppClipRequestEphemeralUserNotification` with value `true` in your Info.plist to enable this - Check the authorization status in the `NotificationSettings`, under the new `.ephemeral` status - Users can explicitly disable these permissions via App Clip settings panel - App Clips can prompt the user for full Location and Notifications access, although discouraged - Strongly suggest using ApplePay - Strongly suggest using "Sign In With Apple" - Use `AuthenticationServices` API to sign your users in without showing a login screen (assuming they have already previously signed up in your website for instance) - **Transition users to your app** - iOS suggests downloading your app from App Clip experiences, banners and App Clip settings - You can embed `StoreKit` `SKOverlay` in a view - Suggestion: display this overlay only after the user finishes their task, e.g. after payment - **Transfer data on device with a secure App Group** - Only accessible between your App Clip and your app - Once user downloads the app, the App Group will be transferred to the app after the App Clip is deleted - Migrate your "Sign In With Apple" session from your App Clip by persisting the user ID in the secure App Group. Use `ASAuthorizationAppleIDProvider` to verify the user's session without prompting UI ## Discover AppleSeed for IT and Managed Software Updates https://developer.apple.com/wwdc20/10138 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Leverage enterprise identity and authentication https://developer.apple.com/wwdc20/10139 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build location-aware enterprise apps https://developer.apple.com/wwdc20/10140 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build scalable enterprise app suites https://developer.apple.com/wwdc20/10142 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Mac Catalyst https://developer.apple.com/wwdc20/10143 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for Game Center https://developer.apple.com/wwdc20/10145 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Configure and link your app clips https://developer.apple.com/wwdc20/10146/ Presenters: _Ada Chan, Luming Yin_ - **Intro** - App Clips provide entry points to your users to experience your app with minimal friction. - Use deep-linked navigation to present the App Clip - **User Quest** - User is in a smoothie shop. They see an NFC tag and tap it using the phone. - An app clip shows up on the phone's lockscreen with summarized detail about that smoothie. - User taps "open" and a single screen of your app shows up. - User can then proceed to the payment via Apple Pay. - **Activation** - Tapping NFC tags or scanning QR codes - they're just deep links after all (a URL) - Maps and Siri Nearby Suggestions (for registered businesses) - Smart app banner in your website (shown in Safari and Messages) - Apple App Clip codes will be introduced later this year (it's a prettified QR code) - If the user already has the your app installed, following an App Clip link will open the full app instead. - **Setup** - Configure web server and App Clip for link handling - Web Server: Update the apple-app-site-association file - App Clip: Add associated domains entitlement and handle NSUserActivity - Configure App Clip default and advanced experiences on App Store Connect - Layout requirements: - Title: 18 chars limit - Subtitle: 43 chars limit - Image: - Size: 3000 x 2000px - Aspect Ratio: 3:2 - Format: png/jpg - Transparency: No - **Best Practices** - URL mapping is based on **most specific** prefix match against registered App Clip experience URLs - Your App Clip must be able to launch using an exact registered URL. For example: - App registers https://bikesrental.com/rent instead of https://website.com/rent?bikeID=2 - When receiving https://website.com/rent?bikeID=2, it should be able to deliver the https://website.com/rent App Clip - App is responsible for parsing the remaining arguments and presenting the specific bike with ID 2 - You can also register a more specific URL if you want to provide a different and more specific App Clip experience for it - Configure the Smart App Banner to open App Clip (add this if the content of your web page can be delivered as a better and more streamlined app experience) - Add/update your website's HTML to add the Smart App Banner meta tag - **Test** - Specify an App Clip URL under the `_XCAppClipURL` environment variable to launch App Clip from Xcode - TestFlight - new App Clips section in App Store Connect ## Distribute binary frameworks as Swift packages https://developer.apple.com/wwdc20/10147 Presenters: _Boris Buegling_ - **Xcode 11** - Introduction of Swift Packages to distribute libraries as source code - Introduction of XCFrameworks to distribute closed-source binary frameworks and libraries - **Xcode 12** adds support for binary dependencies - **Binary Dependencies (XCFrameworks)** - Used to distribute closed-source frameworks, static and dynamic libraries - Contain a single module - Easily addable via the `Xcode > File > Swift Packages > Add Package Dependency` - Has sub directories corresponding to platform and target environment, each containing a framework - Declare dependency in your Package.swift using `.package(url: "https://github.com/owner/package", from: "1.0.0")` - **Distribute Binary Frameworks as a Swift Package** - New target type `.binaryTarget(name: "Emoji", url: https://example.com/Emoji/Emoji-1.0.0.xcframework.zip, checksum: "6d98....")` - Binary targets can be offered to clients just like regular targets - **Binary Targets** - Use XCFrameworks - Only supported on Apple platforms - HTTPS or path based - paths can point to files inside your package - Name corresponds to the module name - Use semantic versioning - **Create your own Binary Dependency** - Create `File > New Swift Package` - Replace template-added targets and add a binary target - Compute the checksum using `swift package compute-checksum Emoji-1.0.0.xcframework.zip` - Set `Build Libraries for Distribution` build setting - Archive each variant - `xcodebuild -create-xcframework` - See [2019 session "Binary frameworks in Swift"](https://developer.apple.com/wwdc19/416) or read the [session notes](https://github.com/Blackjacx/WWDC/tree/2019#binary-frameworks-in-swift) which is way quicker - Tradeoffs of Binary Dependencies - Harder to debug since source code is missing - You won't be able to compile for your specific platform if not included by the author ## Inspect, modify, and construct PencilKit drawings https://developer.apple.com/wwdc20/10148 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Structure your app for SwiftUI previews https://developer.apple.com/wwdc20/10149 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in CareKit https://developer.apple.com/wwdc20/10151 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Use model deployment and security with Core ML https://developer.apple.com/wwdc20/10152 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Get models on device using Core ML Converters https://developer.apple.com/wwdc20/10153 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Control training in Create ML with Swift https://developer.apple.com/wwdc20/10156 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Deliver a better HLS audio experience https://developer.apple.com/wwdc20/10158 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build an Endpoint Security app https://developer.apple.com/wwdc20/10159 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Formatters: Make data human-friendly https://developer.apple.com/wwdc20/10160 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for location privacy https://developer.apple.com/wwdc20/10162 Presenter: _Rachel Needle_ - Today people share precise location data - **In iOS 14, Core Location allowing users to control and share their approximate location** - All kinds of apps will be impacted by this change (even Apple's apps) - **How to adapt the app** to work without precise location? - **Prioritize user control** - Give everyone control over their location data they share and respect their preferences - Don't require precise location - Replace precise data with approximate where possible - Identify where else you use precise location and remove non-essential uses of precise location - **Build trust through transparency** - Communicate with people about what data your app uses and how that data is used - Make status easy to access - Allow users to change their decision - **Offer proportional value** - Only ask for precise location when you really need it - Request precise location in response to user action - Position the request close to the value it provides - Consider checking out these two sessions to **get detailed information** - [Build trust through better privacy](https://github.com/Blackjacx/WWDC#build-trust-through-better-privacy) - [What's new in location](https://github.com/Blackjacx/WWDC#whats-new-in-location) ## Advancements in the Objective-C runtime https://developer.apple.com/wwdc20/10163 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## XCTSkip your tests https://developer.apple.com/wwdc20/10164 Presenters: _Wil Addario-Turner_ - Tests can pass or fail, or with `XCTSkip`, be marked with an explicit "skip" result. - In Xcode 11.4, `XCTSkip`, `XCTSkipIf` and `XCTSkipUnless` were introduced to allow skipping tests at runtime. - Call `throw XCTSkip("message")` and the test will be skipped. - `XCTSkipIf` skips when the expression is true. `XCTSkipUnless` skips when the expression is false. - Check the results from the test navigator and the test report with the line where the skip occurred, along with a reason explaining why. ## Embrace Swift type inference https://developer.apple.com/wwdc20/10165 Presenter: _Holly Borla_ - **Leveraging type inference** - A type can be inferred by the compiler given the context surrounding a variable or function - SwiftUI code relies on type inference for reusable views - A demo is presented showing a SwiftUI component being built using generics - **How type inference works in compiler** - Think of type inference as a puzzle - It resolves the puzzle by filling in the missing pieces using clues from the source code - Solving one puzzle can give the compiler more clues on how to solve other puzzles - **Type inference errors** - If a puzzle can't be solved, there's an error in the source code - During type inference, the compiler will record information about errors in source code - Compiler uses heuristics to attempt to fix errors in order to continue type inference - Once type inference is done, the compiler will provide actionable error messages based on collected information (some errors might have auto-fixes) - Swift 5.3 and Xcode 12 improved error handling a lot, showing more meaningful and reliable error messages - **Using Swift and Xcode to fix compile errors** - The compiler will leave breadcrumbs about what the compiler was doing when it found an error - This can help you connect the dots between the error you're seeing on the editor and other files in your project - Hold **โŒฅ + โ‡ง** on an error breadcrumb and drag it to the right of the source editor, to open the source editor and the breadcrumbs details side by side ## Safely manage pointers in Swift https://developer.apple.com/wwdc20/10167 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore logging in Swift https://developer.apple.com/wwdc20/10168 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Swift packages: Resources and localization https://developer.apple.com/wwdc20/10169 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Swift https://developer.apple.com/wwdc20/10170 Presenters: _Ted Kremenek, Kyle Macomber_ - **Swift Releases** - Xcode 11.4 - Swift 5.2 - Xcode 12 (beta) - Swift 5.3 - **Runtime Performance** - Code Size - Code size is the part of the app that represents the machine code representation of the app's logic - Swift 5.3 is below 1.5 times the code size of Objective-C version (based on app that ships with iOS) - Size difference is inevitable because of Swift safety features - SwiftUI app binary code size can be reduced by 40% (based on MoviesSwiftUI app) - Memory Layout - Comparing models with three properties in Obj-C (`NSUUID`, `NSString` and `float`) and Swift (`UUID`, `String`, `Float`) - In Obj-C, object variables are just pointers which then hold a pointer to their properties - Swift's use of value types avoid the need to access values via pointers (UUID and Strings) - Significant memory benefit because it is allocated directly within array storage (contiguous block of memory) - Heap memory use comparison: 20kB in Swift 5.1 vs 35kB in Obj-C (400 models in array) - Swift's Standard Library now is below Foundation in the stack which means it can be used to develop low-level frameworks for Objective-C frameworks where previously C has to be used! - **Diagnostics** - New diagnostics in the Swift compiler result in more precise and actionable errors - Additional notes in error messages (SwiftUI as an example) - More info on [swift.org](https://swift.org/blog/new-diagnostic-arch-overview/) - **Code completion** - Much better code completion thanks to improvements in SourceKit - Code completion for dictionary literals, ternary expressions and more dynamic features like key paths - Code completion in Xcode 12.0 is 15x faster compared to Xcode 11.5 - **Code Indentation** - Improved indentation formatting in chained methods calls, tuples, multiline `if` and `guards` - Improved indentation in SwiftUI as well - **Debugging** - Debugger now displays the reason for Swift runtime failure traps - **Cross-Platform Support** - Multiple platform support - Apple Platforms - Ubuntu 16.04, 18.04, 20.04 - CentOS 8 - Amazon Linux 2 - Windows (coming soon) - Swift on AWS Lambda - Runtime is open-source and is available on [GitHub](https://github.com/swift-server/swift-aws-lambda-runtime/) - **Language** - [Swift Evolution website](https://apple.github.io/swift-evolution/) - Multiple trailing closure syntax [SE-0279](https://github.com/apple/swift-evolution/blob/master/proposals/0279-multiple-trailing-closures.md) - It's important to set the correct base name of the method that will indicate the first trailing closure that its label will be dropped - Key Path Expressions as Functions [SE-0249](https://github.com/apple/swift-evolution/blob/master/proposals/0249-key-path-literal-function-expressions.md) - `@main`: Type-Based Program Entry Points [SE-0281](https://github.com/apple/swift-evolution/blob/master/proposals/0281-main-attribute.md) - The standardized way to delegate a program's entry point - Increased availability of implicit self in @escaping closures when reference cycles are unlikely to occur [SE-0269](https://github.com/apple/swift-evolution/blob/master/proposals/0269-implicit-self-explicit-capture.md) - Now it's possible to add `self` to the capture list - In Swift 5.3, if self is a structure it can be omitted entirely from the closure - Multi-Pattern Catch Clauses [SE-0276](https://github.com/apple/swift-evolution/blob/master/proposals/0276-multi-pattern-catch-clauses.md) - Enum Enhancements - `Comparable` conformance is now synthesized automatically [SE-0266](https://github.com/apple/swift-evolution/blob/master/proposals/0266-synthesized-comparable-for-enumerations.md) - Enum cases as protocol witnesses [SE-0280](https://github.com/apple/swift-evolution/blob/master/proposals/0280-enum-cases-as-protocol-witnesses.md) - Embedded DSL Enhancements - Builder closures - Swift 5.3 introduces pattern matching statements like `if let` and `switch` - Builder inference (`@SceneBuilder` is not longer needed) - **Libraries** - `Float16` [SE-0277](https://github.com/apple/swift-evolution/blob/master/proposals/0277-float16.md) - Half-width floating point type - Performance gains but low precision and small range - Apple Archive - Modular archive format - Fast compression - Idiomatic Swift API - Swift System - Idiomatic Swift interface to system calls - Low-level currency types - Wraps Darwin APIs - OSLog - Unified logging API - Faster and more expressive (formatting options) - Packages - [Swift Numerics](https://github.com/apple/swift-numerics) - Support for complex numbers and basic math functions - [Swift ArgumentParser](https://github.com/apple/swift-argument-parser) - [Swift Standard Library Preview](https://github.com/apple/swift-standard-library-preview) - Includes features that have not been included in the release yet ## What's new in watchOS design https://developer.apple.com/wwdc20/10171 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design great app clips https://developer.apple.com/wwdc20/10172 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Get the most out of Sign in with Apple https://developer.apple.com/wwdc20/10173 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore app clips https://developer.apple.com/wwdc20/10174 Presenters: _James Savage, Luming Yin_ - **What is an App Clip?** - App Clip Experience URL is required to run App Clips which are parts of your app - On-demand app experiences - **App Clip Experiences** - App Clip URLs are similar to Universal Links - Registered using App Store Connect - Surfaced through user actions via NFC / QR codes / links in Safari or other apps / Apple App Clip codes combine the ease of NFC and visual codes so they can be tapped or scanned - **New App Clip Target in Xcode** - Contains all assets - Needs to be submitted along with the app for review - It gets downloaded separately if the app is not installed on userโ€™s device - Should be as small as possible for quick downloads (less than 10MB but with enough assets to load UI quickly) - Focused user flows - one at a time - **Demo** - Ordering smoothies - New App Clip target embedded in the application - Name and bundle ID for App Clip added - It can build and run with boilerplate code right away - Add code and resources - `NutritionFacts` dependency added - Create new Assets Catalog as shared assets - Drag App Icon, Colors and other image assets required for app clip into the shared assets catalog - Add the required model and view files to App Clip target - Let go of unwanted Swift files like navigation - Conditionally compile out the references to files not added to App Clip - Build Settings > Swift Compiler custom flags > Active Compilation Conditions > Add APPCLIP condition for required schemes. - Use #if !APPCLIP to compile out unwanted references in Swift code - Write code for App Clip - Add required models and views to the new AppClip - Include existing views in the App Clipโ€™s content view - **Technology Overview** - App Clips are built using same UI components as an app - When launched, it receives `NSUserActivity` - Use the URL to identify the type of experience to be handled - Unlike extensions, App Clip can make use of all iOS SDK APIs - Note: Access to sensitive data is limited - Always check if data is available - New location confirmation API helps get the location quickly without requesting full access - New API for migrating data from App Clip to main app using shared data container once installed - App Clip and its local storage will be deleted after period of inactivity - Not included in backups - Can not be launched via Universal Links or custom URL schemes - Can not include bundle extensions like content blockers - **Device states and transitions** - User scans QR code - iOS locates, downloads and runs the App Clip - If the App Clip is not revisited for a while, the App Clip and its data gets deleted - Treat App Clip data as cache; which can be deleted - If the App Clip is visited frequently, its lifespan will be extended and data may never be cleared - When user downloads your app, iOS will automatically migrate the data container and the permissions that were already granted by the user - iOS still deletes the App Clip and its container after copying the data container to the app - **Other technologies** - Apple Pay - Notifications - SwiftUI - `SKOverlay` / `AppStoreOverlayModifier` (refer to [Whatโ€™s new with in-app purchase](https://developer.apple.com/wwdc20/10661/) session) - `ASAuthorizationController` for sign in or sign up ## The details of UI typography https://developer.apple.com/wwdc20/10175 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Master Picture in Picture on tvOS https://developer.apple.com/wwdc20/10176 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in HealthKit https://developer.apple.com/wwdc20/10182 Presenter: _Netra Kenkarey_ - **Symptoms** - Developers can now track symptoms in HealthKit, read and write symptom samples - HealthKit attempted to cover and track a wide range of symptoms (shortness of breath, sleep changes, appetite changes, fever, headache, etc.) - There are 13 symptom data types in HealthKit - **Electrocardiogram (ECG)** - ECG samples will be available for reading in the latest version of iOS and watchOS - An ECG sample can be read as an [`HKElectrocardiogram`](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram) (it represents a waveform as a series of voltage values) - ECG sample has important properties that describe the measurements - [classification (`HKElectrocardiogram.Classification`)](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram/3551981-classification) - Apple Watch will give the result of the recording in the form of a classification - The classification is divided into 2 types - Sinus Rhythm (heart is beating in a uniform pattern) - Atrial fibrillation (form of irregular rhythm, user should probably go see their doctor) - If Apple Watch is unable to determine the ECG result, either due to a low or a high heart rate or due to any other reason, the result is considered inconclusive - [symptomStatus (`HKElectrocardiogram.SymptomsStatus`)](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram/3551984-symptomsstatus) - It tells if the user associated a symptom with this ECG (e.g. heartburn, tightness in the chest) - The symptom experienced can be recorded along with the ECG - [averageHeartRage (`HKQuantity?`)](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram/3551980-averageheartrate) - [samplingFrequence (`HKQuantity?`)](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram/3551983-samplingfrequency) - [numberOfVoltageMeasurements (`Int`)](https://developer.apple.com/documentation/healthkit/hkelectrocardiogram/3551982-numberofvoltagemeasurements) - It refers to the individual voltage measurements that make up an ECG sample - **[`HKElectrocardiogramQuery`](https://developer.apple.com/documentation/healthkit/hkelectrocardiogramquery)** - To retrieve the individual measurements run the [`HKElectrocardiogramQuery`](https://developer.apple.com/documentation/healthkit/hkelectrocardiogramquery) - Fetch the ECG samples with any of the HealthKit queries and then initialize the [`HKElectrocardiogramQuery`](https://developer.apple.com/documentation/healthkit/hkelectrocardiogramquery) with the fetched sample - When this query is executed on the HealthStore, you get the individual voltage measurements back in the ECG and the data handler - **Mobility** - **New set of mobility types** (available for reading and writing on the latest iOS and watchOS) - Walking speed and step length - Walking assymetry and double support percentage - Stair ascent and descent speed - Six-minute walk test distance ## Synchronize health data with HealthKit https://developer.apple.com/wwdc20/10184 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Visually edit SwiftUI views https://developer.apple.com/wwdc20/10185 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Discover WKWebView enhancements https://developer.apple.com/wwdc20/10188 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Secure your app: threat modeling and anti-patterns https://developer.apple.com/wwdc20/10189 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create quick interactions with Shortcuts on watchOS https://developer.apple.com/wwdc20/10190 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Add configuration and intelligence to your widgets https://developer.apple.com/wwdc20/10194 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Broaden your reach with Siri Event Suggestions https://developer.apple.com/wwdc20/10197 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Platform State of the Union โ˜… https://developer.apple.com/wwdc20/102/ - Some new features: **AirPods Motion API**, **SwiftPM resources**, **New Catalyst Controls**, **ARKit 4**, **Widgets in SwiftUI**, **Depth API**, **TestFlight 100 Testers**, **SwiftUI Lifecycle**, **Catalyst Native Screen Resolution**, **Complications in SwiftUI**, **Xcode StoreKit Testing**, **HomePod Music Services**, **App Clips**, **New SwiftUI Controls**, **Xcode Tabs**, ... - Users can make your app the default app used for email and set a default web browser - Developers can bring existing web-browser extensions to Safari using a new command line tool - **FindMy** can now leverage **all** iPhones out there to locate your devices, even if they are not connected to the internet ([applicable to all kinds of objects](developer.apple.com/find-my)) - Mac transition to **Apple Silicon** - Apple's own processor line - brings more security, better performance, longer battery life and amazing graphics - **Advantages** - Cached cloud content can be kept up to date for days, even if your mac goes to sleep - Higher quality, hardware-supported 4:4:4 encoder for e.g. better image quality when connecting your Mac via SideCar - Best-In-Class platform security - Apple provides a Developer Transition Kit - Mac mini enclosure + A12Z SoC - 16GB memory, 512GB SSD - macOS Big Sur Developer Beta + Xcode - First Macs will appear by end of the year - **Universal 2** create universal apps that run on both Apple Silicon and older architectures - Porting to Apple Silicon takes only a few days, even for grown projects. As a result, all Apple system apps are already converted in macOS Big Sur - **Rosetta 2** lets existing app run on new architectures from day one by making them compatible at installation time - Supports iPhone and iPad apps **directly** - iOS/iPad Apps natively on Mac - Apps will run natively on the Mac - Apps will automatically support features like resizing, Dark Mode, scrolling, multi-window, native share sheets, ... - Apple plans to make iOS/iPadOS apps available on the App Store for macs running with Apple Silicon - **macOS Big Sur - macOS 11** - Rounded dock ๐ŸŽ‰ - Control Center for mac - New translucent look for notification center - Refined layout for menus of the menu bar - New sheet presentation - parent window is dimmed - Completely re-designed toolbars with extending search fields and images provided by SF-Symbols - App-specific accent color - **macOS Catalyst** - macOS-specific implementation of iOS API's - Native resolution support - Messages re-written in Catalyst - SwiftPlaygrounds will support multiple windows - **iPadOS** - New sidebars can now expand from two-column layout to three-column layout - even available in portrait mode - Recommended to use side bars instead of tab bars - New inline emoji picker - also for custom apps - New color picker UI - easy to adopt - New Depth APIs give you access to precise distance info captured by the [LiDAR scanner on iPad](https://www.apple.com/newsroom/2020/03/apple-unveils-new-ipad-pro-with-lidar-scanner-and-trackpad-support-in-ipados/) - Dramatic improvement of people inclusion and motion detection - objects can be placed in front or behind real objects in the world - **Apple Pencil** - New **handwriting** improvements will work in your apps without any additional work - Hand-writing for any UITextField - Automatic support for **Scribble** which converts any hand-written text to typed text - Stroke API gives access to the strokes as the user draws - **Smart Selection** lets you select single words / characters you've written using your pencil and iOS text recognition features - **iOS 14** - **Widgets** - New widgets take UX to a whole new level - Users can move them to the home screen - Widgets are packed as SwiftUI archives which are optimized for performance - Are rendered by the system at the right time, when the user needs them - Can be smartly stacked to consume less space and let the user flip through them - Stack automatically moves the right widget to the top at just the right time - Configurable in the Widget Gallery - **App Clips** - Small part of the app which is light/fast and easy to discover - Can use Apple Pay and Sign in With Apple to provide a seamless UX - Easily discoverable in a variety of ways, like other apps or places in the real world via new Apple-designed (QR-like) codes which are basically NFC tags - Introduce users to what your app offers - **Misc. New Features** - Cycling directions, Guides and EV routing in Maps - Translate app - Messages inline replies - Car keys - App Library - On device dictation - **watchOS 7** - Xcode is now able to preview watchOS complications - SwiftUI complications - **Watch-face sharing** via any sharing capabilities, e.g Messages, social media, etc - **Xcode 12** - Cleaner, more expressive UI - Navigators realized using the new Side Bar - Any kind of content is now openable in document tab - Navigate through nested calls in compiler failure messages - StoreKit test environment lets you unit test In-App Purchase and Subscriptions - New StoreKit transaction manager shows details during debugging - Faster code completion with simplified presentation - **SwiftUI** - All SwiftUI apps will continue to compile without additional changes (Apple added no breaking changes - just extensions) - **Lazy** statement makes large collections of views way less memory hungry and makes scrolling snappy again - Now contains app-structure APIs for all Apple platforms, e.g. `@main`, `@SceneBuilder`, `Settings`, ... ## Design for intelligence: Meet people where they are https://developer.apple.com/wwdc20/10200 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create great enterprise apps: A chat with Box's Aaron Levie https://developer.apple.com/wwdc20/10204 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design with iOS pickers, menus and actions https://developer.apple.com/wwdc20/10205 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for iPad https://developer.apple.com/wwdc20/10206 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## SF Symbols 2 https://developer.apple.com/wwdc20/10207 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Core NFC https://developer.apple.com/wwdc20/10209 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Modernize PCI and SCSI drivers with DriverKit https://developer.apple.com/wwdc20/10210 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Port your Mac app to Apple Silicon https://developer.apple.com/wwdc20/10214 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in ResearchKit https://developer.apple.com/wwdc20/10216 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore numerical computing in Swift https://developer.apple.com/wwdc20/10217 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build localization-friendly layouts using Xcode https://developer.apple.com/wwdc20/10219 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Handle interruptions and alerts in UI tests https://developer.apple.com/wwdc20/10220 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Get your test results faster https://developer.apple.com/wwdc20/10221 Presenters: _Sean Olszewski_ - **The Testing Feedback Loop** - Write tests > run tests > Interpret result >if sufficient confidence [ > Next task] else go back to write tests - Short feedback loops is important because that means you get results from your tests faster, you can ship features to your users faster. - Real world example: Result bundle from that CI job, which never finished. Due to dead lock, poorly chosen timeout. - **Execution Time Allowance [NEW in XCode 12]** - When enabled, Xcode enforces a limit on the amount of time each individual test can take. When a test exceeds this limit, Xcode will first capture spin dump, then kill the test that hung, restart the test runner, so that the rest of the suite can execute. - A spin dump shows you which functions each thread is spending the most time in. It's also possible to manually capture spin dump from Terminal using the spin dump command or from within Activity Monitor. - By default, each test gets 10 minutes. If you need to a specific test or test class, you can use the `executionTimeAllowance` API to special case a particular test or subclass. For values under 60 seconds, they'll be rounded up to 60 seconds, the nearest whole minute. - Prevent a test requests unlimited time by enforcing a maximum allowance. - You can customize the default time allowance and a maximum allowance either via a setting in the Test Plan or through an Xcodebuild option. - Use `XCTest`'s performance APIs to automate testing for regressions in the performance. Use Instruments to identify what parts of your code are slow, - **Parallel Distributed Testing** - Xcode build will distribute tests to each run destination by class. Each device runs a single test class at a time. - If you're testing logic that is device or OS specific, this can lead to unexpected failures or skipped tests. ## Create custom apps for employees https://developer.apple.com/wwdc20/10222 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Deploy Apple devices using zero-touch https://developer.apple.com/wwdc20/10223 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Meet Audio Workgroups https://developer.apple.com/wwdc20/10224 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Improve stream authoring with HLS Tools https://developer.apple.com/wwdc20/10225 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Record stereo audio with AVAudioSession https://developer.apple.com/wwdc20/10226 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Low-Latency HLS https://developer.apple.com/wwdc20/10228 Presenter: _Roger Pantos_ - Comes out of beta this year - Available in iOS 14, tvOS 14, watchOS 7 and this year's macOS - Includes support for bit-rate switching, FairPlay Streaming, fMP4 CMAF, ad insertion, captioning - Native app support, no entitlement necessary - [draft-pantos-hls-rfc8216bis07](https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-07) and later now includes LL-HLS - Includes Low-Latency Server Configuration Profile - Includes CDN tune-in algorithm - Updated informative articles on [developer.apple.com](https://developer.apple.com/) - [Protocol Extension for Low-Latency HLS](https://developer.apple.com/documentation/http_live_streaming/protocol_extension_for_low-latency_hls_preliminary_specification) - [HLS Authoring Specification for Apple Devices](https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices) - **Significant changes and improvements to the protocol** - **Reducing segment delay** - Approach described last year using HTTP/2 Push to send segment with Playlist is not compatible with some delivery models - **Replaced Push with Blocking Preload Hints** - Client requests next part in advance - Server will hold on to the request until it can send it - Also triggers global CDN cache fill - [Discover HLS Blocking Preload Hints session](https://developer.apple.com/videos/play/wwdc2020/10229/) for more information - **Other improvements** - Eliminated HLS report - All Rendition Reports are provided unconditionally - Defined EXT-X-DATERANGE handling for Playlist Delta Updates - [Optimize Live Streams with HLS Playlist Delta Updates](https://developer.apple.com/videos/play/wwdc2020/10230/) session for more detailed information - Added signaling of gaps in Parts and Rendition Reports - New attributes: GAP=YES in EXT-X-PART and EXTT-X-RENDITION-REPORT - This allowing clients to deal better with encoded outages in Low-Latency streams - **Low-Latency HLS Tools changes** - Reference implementation now produces fMP4/CMAF - Added self-contained LL-HLS origin written in Go - Incorporated Low-Latency HLS tools into the regular HLS tools package - Find out more in [Improve Stream Authoring with HLS Tools](https://developer.apple.com/videos/play/wwdc2020/10225/) session - **Summary of important changes** - Replaced HTTP/2 Push with Preloading Hinting - Simplified Delivery Directives - Generate CMAF in reference tools - **Everything is included in the current HLS spec** ## Discover HLS Blocking Preload Hints https://developer.apple.com/wwdc20/10229 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Optimize live streams with HLS Playlist Delta Updates https://developer.apple.com/wwdc20/10230 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Reduce latency with HLS Blocking Playlist Reload https://developer.apple.com/wwdc20/10231 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Adapt ad insertion to Low-Latency HLS https://developer.apple.com/wwdc20/10232 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## The artistโ€™s AR toolkit https://developer.apple.com/wwdc20/10601 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Harness Apple GPUs with Metal https://developer.apple.com/wwdc20/10602 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Optimize Metal apps and games with GPU counters https://developer.apple.com/wwdc20/10603 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Shop online with AR Quick Look https://developer.apple.com/wwdc20/10604 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Gain insights into your Metal app with Xcode 12 https://developer.apple.com/wwdc20/10605 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore ARKit 4 https://developer.apple.com/wwdc20/10611 Presenters: _Quinton Petty, Praveen Gowda_ - **Location Anchors** - Geo-referenced AR Content - Uses "visual localization" from Maps - No processing in the cloud - No images sent back to Apple - Pinned to a geo-location - 3 main parts - [`ARGeoTrackingConfiguration`](https://developer.apple.com/documentation/arkit/argeotrackingconfiguration) - [`ARGeoAnchor`](https://developer.apple.com/documentation/arkit/argeoanchor) - [`ARGeotrackingStatus`](https://developer.apple.com/documentation/arkit/argeotrackingstatus) - Device support A12 Bionic or later + GPS support - Requires availability checks for both device and location - [`ARGeotrackingStatus`](https://developer.apple.com/documentation/arkit/argeotrackingstatus) - [`State`](https://developer.apple.com/documentation/arkit/argeotrackingstatus/3580876-state) - [`StateReason`](https://developer.apple.com/documentation/arkit/argeotrackingstatus/statereason) - [`accuracy`](https://developer.apple.com/documentation/arkit/argeotrackingstatus/3580875-accuracy): low, medium, high - Methods for converting between local and latitude / longitude positions via `getGeoLocation(forPoint:)` - Recommended to point towards buildings / static objects - May struggle in wide open spaces (e.g a field) - [Locations currently available](https://developer.apple.com/documentation/arkit/argeotrackingconfiguration/3571351-checkavailability): San Francisco Bay Area, Los Angeles, New York, Chicago and Miami - Sample: [Tracking Geographic Locations in AR](https://developer.apple.com/documentation/arkit/tracking_geographic_locations_in_ar) - **Scene Geometry** - Topological map of environment - Semantic classification - Allowing for: - Occlusion - Physics - Virtual lighting - Based upon the Depth API - **Depth API** - Provides a dense depth image - Use [`sceneDepth`](https://developer.apple.com/documentation/arkit/arframe/3566299-scenedepth) under frame semantics - Runs at 60Hz, on every ARFrame - [`depthMap`](https://developer.apple.com/documentation/arkit/ardepthdata/3566296-depthmap) and [`confidenceMap`](https://developer.apple.com/documentation/arkit/ardepthdata/3566295-confidencemap) provided - Depth map provided as `CVPixelBuffer` - [`ARConfidenceLevel`](https://developer.apple.com/documentation/arkit/arconfidencelevel): high, medium or low - Available on LiDAR devices - **Object Placement** - Improvements in Raycasting - Quicker placement with LiDAR sensor - Allows for placing on a white wall - Raycasting is recommend over hit-testing - 2 types of query: - Raycast - Tracked Raycasts - **Face Tracking** - Support added for non-TrueDepth iPhones - Requires A12 processor or later - iPhone SE (2020) ## What's new in RealityKit https://developer.apple.com/wwdc20/10612 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in USD https://developer.apple.com/wwdc20/10613 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Advancements in Game Controllers https://developer.apple.com/wwdc20/10614 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build GPU binaries with Metal https://developer.apple.com/wwdc20/10615 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Debug GPU-side errors in Metal https://developer.apple.com/wwdc20/10616 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Bring keyboard and mouse gaming to iPad https://developer.apple.com/wwdc20/10617 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Tap into Game Center: Dashboard, Access Point, and Profile https://developer.apple.com/wwdc20/10618 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Tap into Game Center: Leaderboards, Achievements, and Multiplayer https://developer.apple.com/wwdc20/10619 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Support performance-intensive apps and games https://developer.apple.com/wwdc20/10621 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Bring your Metal app to Apple Silicon Macs https://developer.apple.com/wwdc20/10631 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Optimize Metal Performance for Apple Silicon Macs https://developer.apple.com/wwdc20/10632 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Capture and stream apps on the Mac with ReplayKit https://developer.apple.com/wwdc20/10633 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Discover search suggestions for Apple TV https://developer.apple.com/wwdc20/10634 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Accelerate your app with CarPlay https://developer.apple.com/wwdc20/10635 Presenters: _Jonathan Hersh, Allen Langmaier_ - **New CarPlay App Possibilites** - EV charging - Parking - Quick food ordering - **Audio Apps** - Playable content template will be deprecated - New audio template - **New Templates** - Communication Apps - `CPMessageListItem` - Contact template - List template - Tab bar template - Now playing template - Point of interest template - Information template - **CarPlay Design Principles** - Design for the driver - Streamline interactions - Reuse app configuration - Launch first in CarPlay - CarPlay apps must adapt `UIScene` - **Updates to development** - Dynamic updates to list elements - `CPListItem` - `CPListImageRowItem` ## What's new in streaming audio for Apple Watch https://developer.apple.com/wwdc20/10636 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in managing Apple devices https://developer.apple.com/wwdc20/10639 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Design for the iPadOS pointer https://developer.apple.com/wwdc20/10640 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Handle the Limited Photos Library in your app https://developer.apple.com/wwdc20/10641 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build Image and Video Style Transfer models in Create ML https://developer.apple.com/wwdc20/10642 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build a SwiftUI view in Swift Playgrounds https://developer.apple.com/wwdc20/10643 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Use Swift on AWS Lambda with Xcode https://developer.apple.com/wwdc20/10644 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Support multiple users in your tvOS app https://developer.apple.com/wwdc20/10645 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Web Inspector https://developer.apple.com/wwdc20/10646 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Become a Simulator expert https://developer.apple.com/wwdc20/10647 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Unsafe Swift https://developer.apple.com/wwdc20/10648 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Add custom views and modifiers to the Xcode Library https://developer.apple.com/wwdc20/10649 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Sync a Core Data store with the CloudKit public database https://developer.apple.com/wwdc20/10650 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in App Store Connect https://developer.apple.com/wwdc20/10651 Presenter: _Daniel Miao_ - **App Clips** - **Beta Testing** - Safari App Clip banner appears when a website is associated with an App Clip. Tapping brings up the `App Clip Card`. Tapping the card opens the app itself. - App Clips can be invoked from Safari, Messages, Maps, NFC Tags, QR Code or Location - Invocation URL from the website is used what to show on the App Clip Card and is passed to it upon tap of the banner - App Clip is packaged with the app and delivered to ASC - In the new `App Clip Invocation` Section on ASC you can provide titles and along with invocation URLs used in the App Clip - Title-URL combinations are selectable in TestFlight and take you directly to the App Clip by passing the invocation URL (without showing the App Clip Card) - **App Clip Card Meta Data** - Header image, App Clip title, App Clip subtitle, call to action button - Enter the default meta data on the apps version page on ASC - Associate your website with the App Clip by including the meta-data tag `<meta name="apple-itunes-app", content:"app-id=123456", app-clip-bundle-id:=org.appname.clip>` - Use **Advanced App Clip Experiences** to get customized meta data and association with e.g. location in Maps - Advanced assistant on your app's version page on ASC to setup advanced experience - You can select to promote `Your own business` or `Other Businesses` (e.g. Yelp) - You have to specify an Apple App Site Association file (like with universal links) that has to match the Associated Domains Entitlement in your app - Manage / Debug your website association on ASC - **Game Center** - **Challenges** other players to get achievement - **Recurring Leaderboards** to collect scores for a certain period of time - Reset after that time - Configurable on ASC - **Family Sharing for Subscriptions** - Subscriptions can be shared among the family form fall 2020 - Auto-renewable subscriptions - Non-consumables - Automatic sharing for new customers - Existing subscribers can opt-in - Family-shared in-app purchase can be enabled on the ASC-In-App-Purchase section of your app - **Once turned on it cannot be tuned off again** - **App Store Connect API** - Over 200 new endpoints will be added - Add `App Meta Data API` - Create new version - Set app pricing - Edit app and version metadata - Associate build with version - Submit app for review - Add `Power and Performance Metrics and Diagnostics API` ## Meet the new Photos picker https://developer.apple.com/wwdc20/10652 Presenters: _Tobias Conradi, Justin Jia_ - **PHPicker** - Direct access to userโ€™s photo gallery - Supports zoom in, multi-select, review - Types are filterable - Privacy built in by default - It wonโ€™t prompt the user for access - It runs out of the appโ€™s process - Separate process rendered on top of the app - Only what user selects is passed back to the app - **Implementation** - `PHPickerConfiguration` (which can include type filters) is passed to `PHPickerViewController`, which has delegates to handle responses - `PHPickerConfiguration` - Selection limit - Image / Video type - Initialize `PHPickerViewController` by using the configuration - Set delegate and implement protocol functions - `didFinishPicking` - `NSItemProvider` - representation of the item, async, requires error handling - **Demo** - Photo preview app - `UIImageView` with placeholder image - Plus button for image selection - Present the new picker - Create `PHPickerConfiguration` with images filter and selection limit (set to zero for unlimited selection) - Initialize the `PHPickerViewController` with this configuration - Present the new controller after setting delegate and following the protocol - Implement `didFinishPicking` - Dismiss the picker first - Retrieve the image via item provider and use main queue to update your UI - Use `IndexingIterator<[NSItemProvider]>` to save array of item providers - Add touch event to iterate through the array of picked images - **Note** - `AssetsLibrary` will go away; switch to `PhotoKit` - `UIImagePickerController` is to be deprecated and replaced with `PHPickerViewController` ## Detect Body and Hand Pose with Vision https://developer.apple.com/wwdc20/10653 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Create Swift Playgrounds content for iPad and Mac https://developer.apple.com/wwdc20/10654 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Discover how to download and play HLS offline https://developer.apple.com/wwdc20/10655 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Beyond counting steps https://developer.apple.com/wwdc20/10656 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Make apps smarter with Natural Language https://developer.apple.com/wwdc20/10657 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in education https://developer.apple.com/wwdc20/10658 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Introducing StoreKit Testing in Xcode https://developer.apple.com/wwdc20/10659 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in location https://developer.apple.com/wwdc20/10660 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Whatโ€™s new with in-app purchase https://developer.apple.com/wwdc20/10661 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in Wallet and Apple Pay https://developer.apple.com/wwdc20/10662 Presenter: _Stacey Abrams_ - Use Apple Pay to get into public transit and acadamic buildings - **API Enhancements** - PKSecureElementPass replaces PKPaymentPass fom now - New Apple Pay Button types: `.reload` , `.addMoney`, `.topUp`, `.order`, `.rent`, `.support`, `.contribute`, `.tip` - See how to declare a Apple Pay Button on a website at [2:16](https://developer.apple.com/wwdc20/10662?time=136) - PKPaymentButton style `.automatic` automatically switches between light and dark mode - **Apple Pay in App Clips** - Could revolutionize everydays payment experience when you can e.g. just tap an NFC tag on a gas station to pay your gas - Guest checkouts using Apple Pay do not require to setup an account anymore and if it is necessary seamless Sign in with Apple is used. - **Enhancing Apple Pay experience across platforms** - Merchants can receive redacted billing address - Lower risk of chargebacks for merchnts - Price transparency leads to higher conversion rates - **Apple Pay for Catalyst** - Brings great payment experiences to more mac apps - Brings the newly announced APIs, including the Apple Pay button, to the mac - Improvements in WKWebView will allow more pages to allow Apple Pay transactions now - **Contacts Formatting Improvements** to prevent invalid shipping addresses - Street and city fields contain vaild characters only - State is a two letter code - US: Zip code is 5 or 9 digit code - ISO country code is upper case two letter code - Improved experience when correcting information - Raise formatting errors earlier in the payment flow - Users can correct information prior to authentication - Error APIs improved and aligned to new formatting options - Only rolles out in some Australia, Canada, UK, US for now - **Adding cards to Apple Pay** - **Issuer Extensions** to improve discoverability from within the Wallet app - needs installatioon of an **Issuer** app - App requires non-UI extension - Extension principal object must subclass `PKIssuerProvisioningExtensionHandler` - Requires non-UI extension entitlement - Added support for a UI extension - Needs to handle re-authentications if required by conforming principal object to `PKIssuerProvisioningExtensionAuthorizationProviding` - Requires UI extension entitlement ## What's new for web developers https://developer.apple.com/wwdc20/10663 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Getting started with HealthKit https://developer.apple.com/wwdc20/10664 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Meet Safari Web Extensions https://developer.apple.com/wwdc20/10665 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## One-tap account security upgrades https://developer.apple.com/wwdc20/10666 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Custom app distribution with Apple Business Manager https://developer.apple.com/wwdc20/10667 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Meet Nearby Interaction https://developer.apple.com/wwdc20/10668 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Handling FHIR without getting burned https://developer.apple.com/wwdc20/10669 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Meet Face ID and Touch ID for the web https://developer.apple.com/wwdc20/10670 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Architecting for subscriptions https://developer.apple.com/wwdc20/10671 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## What's new in ClassKit https://developer.apple.com/wwdc20/10672 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore Computer Vision APIs https://developer.apple.com/wwdc20/10673 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build trust through better privacy https://developer.apple.com/wwdc20/10676 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Build customized ML models with the Metal Performance Shaders Graph https://developer.apple.com/wwdc20/10677 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Refine Objective-C frameworks for Swift https://developer.apple.com/wwdc20/10680 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Explore the new system architecture of Apple Silicon Macs https://developer.apple.com/wwdc20/10686 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md) ## Triage test failures with XCTIssue https://developer.apple.com/wwdc20/10687 Presenters: _Example Guy, Another Person_ ##### TO-DO! You can contribute to this session, please see [CONTRIBUTING.md](CONTRIBUTING.md)
193
โšก๏ธ Lightweight full-featured Promises, Async & Await Library in Swift
<p align="center" > <img src="banner.png" width=300px alt="Hydra" title="Hydra"> </p> <p align="center"><strong>Lightweight full-featured Promises, Async & Await Library in Swift</strong></p> ## What's this? Hydra is full-featured lightweight library which allows you to write better async code in Swift 3.x/4.x. It's partially based on [JavaScript A+](https://promisesaplus.com) specs and also implements modern construct like `await` (as seen in [Async/Await specification in ES8 (ECMAScript 2017)](https://github.com/tc39/ecmascript-asyncawait) or C#) which allows you to write async code in sync manner. Hydra supports all sexiest operators like always, validate, timeout, retry, all, any, pass, recover, map, zip, defer and retry. Starts writing better async code with Hydra! A more detailed look at how Hydra works can be found in [ARCHITECTURE](https://github.com/malcommac/Hydra/blob/master/ARCHITECTURE.md) file or on [Medium](https://medium.com/@danielemargutti/hydra-promises-swift-c6319f6a6209). ## โค๏ธ Your Support *Hi fellow developer!* You know, maintaing and developing tools consumes resources and time. While I enjoy making them **your support is foundamental to allow me continue its development**. If you are using SwiftLocation or any other of my creations please consider the following options: - [**Make a donation with PayPal**](https://www.paypal.com/paypalme/danielemargutti/20) - [**Become a Sponsor**](https://github.com/sponsors/malcommac) - [Follow Me](https://github.com/malcommac) ## Introduction * **[What's a Promise](#whatspromise)** * **[Updating to >=0.9.7](#updating097)** * **[Create a Promise](#createpromise)** * **[How to use a Promise](#howtousepromise)** * **[Chaining Multiple Promises](#chaining)** * **[Cancellable Promises](#cancellablepromises)** * **[Await & Async: async code in sync manner](#awaitasync)** * **[Await an `zip` operator to resolve all promises](#allawait)** * **[All Features](#allfeatures)** * **[always](#always)** * **[validate](#validate)** * **[timeout](#timeout)** * **[all](#all)** * **[any](#any)** * **[pass](#pass)** * **[recover](#recover)** * **[map](#map)** * **[zip](#zip)** * **[defer](#defer)** * **[retry](#retry)** * **[cancel](#cancel)** * **[Chaining Promises with different `Value` types](#chainingdifferentpromises)** * **[Installation (CocoaPods, SwiftPM and Carthage)](#installation)** * **[Requirements](#requirements)** * **[Credits](#credits)** <a name="whatspromise" /> ## What's a Promise? A Promise is a way to represent a value that will exists, or will fail with an error, at some point in the future. You can think about it as a Swift's `Optional`: it may or may not be a value. A more detailed article which explain how Hydra was implemented can be [found here](https://github.com/malcommac/Hydra/blob/master/ARCHITECTURE.md). Each Promise is strong-typed: this mean you create it with the value's type you are expecting for and you will be sure to receive it when Promise will be resolved (the exact term is `fulfilled`). A Promise is, in fact, a proxy object; due to the fact the system knows what success value look like, composing asynchronous operation is a trivial task; with Hydra you can: - create a chain of dependent async operation with a single completion task and a single error handler. - resolve many independent async operations simultaneously and get all values at the end - retry or recover failed async operations - write async code as you may write standard sync code - resolve dependent async operations by passing the result of each value to the next operation, then get the final result - avoid callbacks, pyramid of dooms and make your code cleaner! <a name="updating097" /> ## Updating to >=0.9.7 Since 0.9.7 Hydra implements Cancellable Promises. In order to support this new feature we have slightly modified the `Body` signature of the `Promise`; in order to make your source code compatible you just need to add the third parameter along with `resolve`,`reject`: `operation`. `operation` encapsulate the logic to support `Invalidation Token`. It's just and object of type `PromiseStatus` you can query to see if a Promise is marked to be cancelled from the outside. If you are not interested in using it in your Promise declaration just mark it as `_`. To sum up your code: ```swift return Promise<Int>(in: .main, token: token, { resolve, reject in ... ``` needs to be: ```swift return Promise<Int>(in: .main, token: token, { resolve, reject, operation in // or resolve, reject, _ ``` <a name="createpromise" /> ## Create a Promise Creating a Promise is trivial; you need to specify the `context` (a GCD Queue) in which your async operations will be executed in and add your own async code as `body` of the Promise. This is a simple async image downloader: ```swift func getImage(url: String) -> Promise<UIImage> { return Promise<UIImage>(in: .background, { resolve, reject, _ in self.dataTask(with: request, completionHandler: { data, response, error in if let error = error { reject(error) } else if let data = data, let response = response as? HTTPURLResponse { resolve((data, response)) } else { reject("Image cannot be decoded") } }).resume() }) } ``` You need to remember only few things: - a Promise is created with a type: this is the object's type you are expecting from it once fulfilled. In our case we are expecting an `UIImage` so our Promise is `Promise<UIImage>` (if a promise fail returned error must be conform to Swift's `Error` protocol) - your async code (defined into the Promise's `body`) must alert the promise about its completion; if you have the fulfill value you will call `resolve(yourValue)`; if an error has occurred you can call `reject(occurredError)` or throw it using Swift's `throw occurredError`. - the `context` of a Promise define the Grand Central Dispatch's queue in which the async code will be executed in; you can use one of the defined queues (`.background`,`.userInitiated` etc. [Here you can found](http://www.appcoda.com/grand-central-dispatch/) a nice tutorial about this topic) <a name="howtousepromise" /> ## How to use a Promise Using a Promise is even easier. You can get the result of a promise by using `then` function; it will be called automatically when your Promise fullfill with expected value. So: ```swift getImage(url).then(.main, { image in myImageView.image = image }) ``` As you can see even `then` may specify a context (by default - if not specified - is the main thread): this represent the GCD queue in which the code of the then's block will be executed (in our case we want to update an UI control so we will need to execute it in `.main` thread). But what happened if your Promise fail due to a network error or if the image is not decodable? `catch` func allows you to handle Promise's errors (with multiple promises you may also have a single errors entry point and reduce the complexity). ```swift getImage(url).then(.main, { image in myImageView.image = image }).catch(.main, { error in print("Something bad occurred: \(error)") }) ``` <a name="chaining" /> ## Chaining Multiple Promises Chaining Promises is the next step thought mastering Hydra. Suppose you have defined some Promises: ```swift func loginUser(_ name:String, _ pwd: String)->Promise<User> func getFollowers(user: User)->Promise<[Follower]> func unfollow(followers: [Follower])->Promise<Int> ``` Each promise need to use the fulfilled value of the previous; plus an error in one of these should interrupt the entire chain. Doing it with Hydra is pretty straightforward: ```swift loginUser(username,pass).then(getFollowers).then(unfollow).then { count in print("Unfollowed \(count) users") }.catch { err in // Something bad occurred during these calls } ``` Easy uh? (Please note: in this example context is not specified so the default `.main` is used instead). <a name="cancellablepromises" /> ## Cancellable Promises Cancellable Promises are a very sensitive task; by default Promises are not cancellable. Hydra allows you to cancel a promise from the outside by implementing the `InvalidationToken`. `InvalidationToken` is a concrete open class which is conform to the `InvalidatableProtocol` protocol. It must implement at least one `Bool` property called `isCancelled`. When `isCancelled` is set to `true` it means someone outside the promise want to cancel the task. It's your responsibility to check from inside the `Promise`'s body the status of this variable by asking to `operation.isCancelled`. If `true` you can do all your best to cancel the operation; at the end of your operations just call `cancel()` and stop the workflow. Your promise must be also initialized using this token instance. This is a concrete example with `UITableViewCell`: working with table cells, often the result of a promise needs to be ignored. To do this, each cell can hold on to an `InvalidationToken`. An `InvalidationToken` is an execution context that can be invalidated. If the context is invalidated, then the block that is passed to it will be discarded and not executed. To use this with table cells, the queue should be invalidated and reset on `prepareForReuse()`. ```swift class SomeTableViewCell: UITableViewCell { var token = InvalidationToken() func setImage(atURL url: URL) { downloadImage(url).then(in: .main, { image in self.imageView.image = image }) } override func prepareForReuse() { super.prepareForReuse() token.invalidate() // stop current task and ignore result token = InvalidationToken() // new token } func downloadImage(url: URL) -> Promise<UIImage> { return Promise<Something>(in: .background, token: token, { (resolve, reject, operation) in // ... your async operation // somewhere in your Promise's body, for example in download progression // you should check for the status of the operation. if operation.isCancelled { // operation should be cancelled // do your best to cancel the promise's task operation.cancel() // request to mark the Promise as cancelled return // stop the workflow! it's important } // ... your async operation }) } } ``` <a name="awaitasync" /> ## Await & Async: async code in sync manner Have you ever dream to write asynchronous code like its synchronous counterpart? Hydra was heavily inspired by [Async/Await specification in ES8 (ECMAScript 2017) ](https://github.com/tc39/ecmascript-asyncawait) which provides a powerful way to write async doe in a sequential manner. Using `async` and `await` is pretty simple. > NOTE: Since Hydra 2.0.6 the await function is available under Hydra.await() function in order to supress the Xcode 12.5+ warning (await will become a Swift standard function soon!) For example the code above can be rewritten directly as: ```swift // With `async` we have just defined a Promise which will be executed in a given // context (if omitted `background` thread is used) and return an Int value. let asyncFunc = async({ _ -> Int in // you must specify the return of the Promise, here an Int // With `await` the async code is resolved in a sync manner let loggedUser = try Hydra.await(loginUser(username,pass)) // one promise... let followersList = try Hydra.await(getFollowers(loggedUser)) // after another... let countUnfollowed = try Hydra.await(unfollow(followersList)) // ... linearly // Then our async promise will be resolved with the end value return countUnfollowed }).then({ value in // ... and, like a promise, the value is returned print("Unfollowed \(value) users") }) ``` Like magic! Your code will run in `.background` thread and you will get the result of each call only when it will be fulfilled. Async code in sync sauce! **Important Note**: `await` is a blocking/synchronous function implemented using semaphore. Therefore, it should never be called in main thread; this is the reason we have used `async` to encapsulate it. Doing it in main thread will also block the UI. `async` func can be used in two different options: - it can create and return a promise (as you have seen above) - it can be used to simply execute a block of code (as you will see below) As we said we can also use `async` with your own block (without using promises); `async` accepts the context (a GCD queue) and optionally a start delay interval. Below an example of the async function which will be executed without delay in background: ```swift async({ print("And now some intensive task...") let result = try! Hydra.await(.background, { resolve,reject, _ in delay(10, context: .background, closure: { // jut a trick for our example resolve(5) }) }) print("The result is \(result)") }) ``` There is also an await operator: * **await with throw**: `..` followed by a Promise instance: this operator must be prefixed by `try` and should use `do/catch` statement in order to handle rejection of the Promise. * **await without throw**: `..!` followed by a Promise instance: this operator does not throw exceptions; in case of promise's rejection result is nil instead. Examples: ```swift async({ // AWAIT OPERATOR WITH DO/CATCH: `..` do { let result_1 = try ..asyncOperation1() let result_2 = try ..asyncOperation2(result_1) // result_1 is always valid } catch { // something goes bad with one of these async operations } }) // AWAIT OPERATOR WITH NIL-RESULT: `..!` async({ let result_1 = ..!asyncOperation1() // may return nil if promise fail. does not throw! let result_2 = ..!asyncOperation2(result_1) // you must handle nil case manually }) ``` When you use these methods and you are doing asynchronous, be careful to do nothing in the main thread, otherwise you risk to enter in a deadlock situation. The last example show how to use cancellable `async`: ```swift func test_invalidationTokenWithAsyncOperator() { // create an invalidation token let invalidator: InvalidationToken = InvalidationToken() async(token: invalidator, { status -> String in Thread.sleep(forTimeInterval: 2.0) if status.isCancelled { print("Promise cancelled") } else { print("Promise resolved") } return "" // read result }).then { _ in // read result } // Anytime you can send a cancel message to invalidate the promise invalidator.invalidate() } ``` <a name="allawait" /> ## Await an `zip` operator to resolve all promises Await can be also used in conjuction with zip to resolve all promises from a list: ```swift let (resultA,resultB) = Hydra.await(zip(promiseA,promiseB)) print(resultA) print(resultB) ``` <a name="allfeature" /> ## All Features Because promises formalize how success and failure blocks look, it's possible to build behaviors on top of them. Hydra supports: - `always`: allows you to specify a block which will be always executed both for `fulfill` and `reject` of the Promise - `validate`: allows you to specify a predica block; if predicate return `false` the Promise fails. - `timeout`: add a timeout timer to the Promise; if it does not fulfill or reject after given interval it will be marked as rejected. - `all`: create a Promise that resolved when the list of passed Promises resolves (promises are resolved in parallel). Promise also reject as soon as a promise reject for any reason. - `any`: create a Promise that resolves as soon as one passed from list resolves. It also reject as soon as a promise reject for any reason. - `pass`: Perform an operation in the middle of a chain that does not affect the resolved value but may reject the chain. - `recover`: Allows recovery of a Promise by returning another Promise if it fails. - `map`: Transform items to Promises and resolve them (in paralle or in series) - `zip`: Create a Promise tuple of a two promises - `defer`: defer the execution of a Promise by a given time interval. - `cancel`: cancel is called when a promise is marked as `cancelled` using `operation.cancel()` <a name="always" /> ### always `always` func is very useful if you want to execute code when the promise fulfills โ€” regardless of whether it succeeds or fails. ```swift showLoadingHUD("Logging in...") loginUser(username,pass).then { user in print("Welcome \(user.username)") }.catch { err in print("Cannot login \(err)") }.always { hideLoadingHUD() } ``` <a name="validate" /> ### validate `validate` is a func that takes a predicate, and rejects the promise chain if that predicate fails. ```swift getAllUsersResponse().validate { httpResponse in guard let httpResponse.statusCode == 200 else { return false } return true }.then { usersList in // do something }.catch { error in // request failed, or the status code was != 200 } ``` <a name="timeout" /> ### timeout `timeout` allows you to attach a timeout timer to a Promise; if it does not resolve before elapsed interval it will be rejected with `.timeoutError`. ```swift loginUser(username,pass).timeout(.main, 10, .MyCustomTimeoutError).then { user in // logged in }.catch { err in // an error has occurred, may be `MyCustomTimeoutError } ``` <a name="all" /> ### all `all` is a static method that waits for all the promises you give it to fulfill, and once they have, it fulfills itself with the array of all fulfilled values (in order). If one Promise fail the chain fail with the same error. Execution of all promises is done in parallel. ```swift let promises = usernameList.map { return getAvatar(username: $0) } all(promises).then { usersAvatars in // you will get an array of UIImage with the avatars of input // usernames, all in the same order of the input. // Download of the avatar is done in parallel in background! }.catch { err in // something bad has occurred } ``` If you add promise execution concurrency restriction to `all` operator to avoid many usage of resource, `concurrency` option is it. ```swift let promises = usernameList.map { return getAvatar(username: $0) } all(promises, concurrency: 4).then { usersAvatars in // results of usersAvatars is same as `all` without concurrency. }.catch { err in // something bad has occurred } ``` <a name="any" /> ### any `any` easily handle race conditions: as soon as one Promise of the input list resolves the handler is called and will never be called again. ```swift let mirror_1 = "https://mirror1.mycompany.com/file" let mirror_2 = "https://mirror2.mycompany.com/file" any(getFile(mirror_1), getFile(mirror_2)).then { data in // the first fulfilled promise also resolve the any Promise // handler is called exactly one time! } ``` <a name="pass" /> ### pass `pass` is useful for performing an operation in the middle of a promise chain without changing the type of the Promise. You may also reject the entire chain. You can also return a Promise from the tap handler and the chain will wait for that promise to resolve (see the second `then` in the example below). ```swift loginUser(user,pass).pass { userObj in print("Fullname is \(user.fullname)") }.then { userObj in updateLastActivity(userObj) }.then { userObj in print("Login succeded!") } ``` <a name="recover" /> ### recover `recover` allows you to recover a failed Promise by returning another. ```swift let promise = Promise<Int>(in: .background, { fulfill, reject in reject(AnError) }).recover({ error in return Promise(in: .background, { (fulfill, reject) in fulfill(value) }) }) ``` <a name="map" /> ### map Map is used to transform a list of items into promises and resolve them in parallel or serially. ```swift [urlString1,urlString2,urlString3].map { return self.asyncFunc2(value: $0) }.then(.main, { dataArray in // get the list of all downloaded data from urls }).catch({ // something bad has occurred }) ``` <a name="zip" /> ### zip `zip` allows you to join different promises (2,3 or 4) and return a tuple with the result of them. Promises are resolved in parallel. ```swift zip(a: getUserProfile(user), b: getUserAvatar(user), c: getUserFriends(user)) .then { profile, avatar, friends in // ... let's do something }.catch { // something bad as occurred. at least one of given promises failed } ``` <a name="defer" /> ### defer As name said, `defer` delays the execution of a Promise chain by some number of seconds from current time. ```swift asyncFunc1().defer(.main, 5).then... ``` ### retry `retry` operator allows you to execute source chained promise if it ends with a rejection. If reached the attempts the promise still rejected chained promise is also rejected along with the same source error. Retry also support `delay` parameter which specify the number of seconds to wait before a new attempt (2.0.4+). ```swift // try to execute myAsyncFunc(); if it fails the operator try two other times // If there is not luck for you the promise itself fails with the last catched error. myAsyncFunc(param).retry(3).then { value in print("Value \(value) got at attempt #\(currentAttempt)") }.catch { err in print("Failed to get a value after \(currentAttempt) attempts with error: \(err)") } ``` Conditional retry allows you to control retryable if it ends with a rejection. ```swift // If myAsyncFunc() fails the operator execute the condition block to check retryable. // If return false in condition block, promise state rejected with last catched error. myAsyncFunc(param).retry(3) { (remainAttempts, error) -> Bool in return error.isRetryable }.then { value in print("Value \(value) got at attempt #\(currentAttempt)") }.catch { err in print("Failed to get a value after \(currentAttempt) attempts with error: \(err)") } ``` <a name="cancel" /> ### cancel `cancel` is called when a promise is marked as `cancelled` from the Promise's body by calling the `operation.cancel()` function. See the **[Cancellable Promises](#cancellablepromises)** for more info. ```swift asyncFunc1().cancel(.main, { // promise is cancelled, do something }).then... ``` <a name="chainingdifferentpromises" /> ## Chaining Promises with different `Value` types Sometimes you may need to chain (using one of the available operators, like `all` or `any`) promises which returns different kind of values. Due to the nature of Promise you are not able to create an array of promises with different result types. However thanks to `void` property you are able to transform promise instances to generic `void` result type. So, for example, you can execute the following `Promises` and return final values directly from the Promise's `result` property. ```swift let op_1: Promise<User> = asyncGetCurrentUserProfile() let op_2: Promise<UIImage> = asyncGetCurrentUserAvatar() let op_3: Promise<[User]> = asyncGetCUrrentUserFriends() all(op_1.void,op_2.void,op_3.void).then { _ in let userProfile = op_1.result let avatar = op_2.result let friends = op_3.result }.catch { err in // do something } ``` <a name="installation" /> ## Installation You can install Hydra using CocoaPods, Carthage and Swift package manager - **Swift 3.x**: Latest compatible is 1.0.2 `pod 'HydraAsync', ~> '1.0.2'` - **Swift 4.x**: 1.2.1 or later `pod 'HydraAsync'` ### CocoaPods use_frameworks! pod 'HydraAsync' ### Carthage github 'malcommac/Hydra' ### Swift Package Manager Add Hydra as dependency in your `Package.swift` ``` import PackageDescription let package = Package(name: "YourPackage", dependencies: [ .Package(url: "https://github.com/malcommac/Hydra.git", majorVersion: 0), ] ) ``` **Consider โค๏ธ [support the development](#support) of this library!** <a name="requirements" /> ## Requirements Current version is compatible with: * Swift 5.x * iOS 9.0 or later * tvOS 9.0 or later * macOS 10.10 or later * watchOS 2.0 or later * Linux compatible environments <a name="credits" /> ## Contributing - If you **need help** or you'd like to **ask a general question**, open an issue. - If you **found a bug**, open an issue. - If you **have a feature request**, open an issue. - If you **want to contribute**, submit a pull request. ## Copyright & Acknowledgements SwiftLocation is currently owned and maintained by Daniele Margutti. You can follow me on Twitter [@danielemargutti](http://twitter.com/danielemargutti). My web site is [https://www.danielemargutti.com](https://www.danielemargutti.com) This software is licensed under [MIT License](LICENSE.md). ***Follow me on:*** - ๐Ÿ’ผ [Linkedin](https://www.linkedin.com/in/danielemargutti/) - ๐Ÿฆ [Twitter](https://twitter.com/danielemargutti) ```
194
A sliding Sheet from the bottom of the Screen with 3 States build with SwiftUI.
# BottomSheet [![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg)](https://swift.org/package-manager/) [![GitHub version](https://img.shields.io/github/v/release/lucaszischka/BottomSheet?sort=semver)](https://github.com/lucaszischka/BottomSheet/releases) [![CocoaPods compatible](https://img.shields.io/badge/CocoaPods-compatible-brightgreen)](http://cocoapods.org/) [![CocoaPods version](https://img.shields.io/cocoapods/v/BottomSheetSwiftUI.svg)](https://cocoapods.org/pods/BottomSheetSwiftUI) [![License](https://img.shields.io/github/license/lucaszischka/BottomSheet)](https://github.com/lucaszischka/BottomSheet/blob/main/LICENSE.txt) [![Issues](https://img.shields.io/github/issues/lucaszischka/BottomSheet)](https://github.com/lucaszischka/BottomSheet/issues) A sliding sheet from the bottom of the screen with custom states build with SwiftUI. # Version 3 is out now! Please look [here](https://github.com/lucaszischka/BottomSheet/pull/79) and read the README for more information on the changes. ## Why There have been many different attempts to recreate the BottomSheet from Apple Maps, Shortcuts and Apple Music, because Apple unfortunately does not provide it in their SDK. (*Update: It was more or less added in iOS 16*) However, most previous attempts share a common problem: The **height does not change** in the different states. Thus, the BottomSheet is always the same size (e.g. 800px) and thus remains 800px, even if you only see e.g. 400px - the rest is **inaccessible** unless you pull the BottomSheet up to the very top. There are also many implementations out there that **only have 2 states** - **not 3** like e.g. Apple Maps. ### Features - Very **easy to use** - Build in **header/title** (see [Parameters](#Parameters)) - Many view modifiers for **customisation** (see [Modifiers](#Modifiers)) - Fully customisable States (**any number of states at any height**) (see [BottomSheetPosition](#BottomSheetPosition)) - States can have the height of their content, absolute pixel values or percentages of the screen height (see [BottomSheetPosition](#BottomSheetPosition)) - Support for **SearchBar** in the header - It works with `ScrollView`, `List` and **every** other view - Can hide the content when in `...Bottom` position like Apple does - Imbedded `.appleScrollBehaviour()` modifier, to replicate Apple's ScrollView behaviour - Completely animated - And much more... ## Requirements - iOS 13, macCatalyst 13, macOS 10.15 - Swift 5.5 - Xcode 12 ## Installation ### Swift Package Manager The preferred way of installing BottomSheet is via the [Swift Package Manager](https://swift.org/package-manager/). >Xcode 11 integrates with libSwiftPM to provide support for iOS, watchOS, and tvOS platforms. 1. In Xcode, open your project and navigate to **File** โ†’ **Add Packages** 2. Paste the repository URL (`https://github.com/lucaszischka/BottomSheet`) and click **Next**. 3. For **Rules**, select **Up to Next Major Version**. 4. Click **Add Package**. ### CocoaPods BottomSheet is available through [CocoaPods](https://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod 'BottomSheetSwiftUI' ``` Now run `pod install` in the Terminal to install this dependency. ## Usage **WARNING:** This is Sample Code for visualisation where and how to use, without a working initializer. Please see [Examples](#Examples) for working code. BottomSheet is similar to the built-in Sheet: ```swift struct ContentView: View { @State var bottomSheetPosition: BottomSheetPosition = .middle //1 var body: some View { Map() //2 .bottomSheet() //3 } } ``` `//1` The current State of the BottomSheet. - For more information about the possible positions see [BottomSheetPosition](#BottomSheetPosition). - If you don't want the BottomSheet to be drag-able and the state to be switchable, you can use the `.isResizable(false)` modifier. `//2` The view which the BottomSheet overlays. - **Important:** If you want to overlay a `TabBar` or a `NavigationView`, you need to add the BottomSheet on a higher level. `//3` This is how you add the BottomSheet - easy right? ## Parameters ### Title as Header Content ```swift .bottomSheet( bottomSheetPosition: Binding<BottomSheetPosition>, switchablePositions: [BottomSheetPosition], title: String?, content: () -> MContent ) ``` `bottomSheetPosition`: A binding that holds the current position/state of the BottomSheet. - If you don't want the BottomSheet to be drag-able and the state to be switchable, you can use the `.isResizable(false)` modifier. - For more information about the possible positions see [BottomSheetPosition](#BottomSheetPosition). `switchablePositions`: An array that contains the positions/states of the BottomSheet. - Only the positions/states contained in the array can be switched into (via tapping the drag indicator or swiping the BottomSheet). - For more information about the possible positions see [BottomSheetPosition](#BottomSheetPosition). `title`: A `String` that is displayed as title. - You can use a view that is used as header content instead. `content`: A view that is used as main content for the BottomSheet. ### Custom Header Content ```swift .bottomSheet( bottomSheetPosition: Binding<BottomSheetPosition>, switchablePositions: [BottomSheetPosition], headerContent: () -> HContent?, mainContent: () -> MContent ) ``` `bottomSheetPosition`: A binding that holds the current position/state of the BottomSheet. - If you don't want the BottomSheet to be drag-able and the state to be switchable, you can use the `.isResizable(false)` modifier. - For more information about the possible positions see [BottomSheetPosition](#BottomSheetPosition). `switchablePositions`: An array that contains the positions/states of the BottomSheet. - Only the positions/states contained in the array can be switched into (via tapping the drag indicator or swiping the BottomSheet). - For more information about the possible positions see [BottomSheetPosition](#BottomSheetPosition). `headerContent`: A view that is used as header content for the BottomSheet. - You can use a `String` that is displayed as title instead. `mainContent`: A view that is used as main content for the BottomSheet. ## Modifiers The ViewModifiers are used to customise the look and feel of the BottomSheet. `.enableAccountingForKeyboardHeight(Bool)`: Adds padding to the bottom of the main content when the keyboard appears so all of the main content is visible. - If the height of the sheet is smaller than the height of the keyboard, this modifier will not make the content visible. - This modifier is not available on Mac, because it would not make sense there. `.enableAppleScrollBehavior(Bool)`: Packs the mainContent into a ScrollView. - Behaviour on the iPhone: - The ScrollView is only enabled (scrollable) when the BottomSheet is in a `...Top` position. - If the offset of the ScrollView becomes less than or equal to 0, the BottomSheet is pulled down instead of scrolling. - In every other position the BottomSheet will be dragged instead - This behaviour is not active on Mac and iPad, because it would not make sense there. - Please note, that this feature has sometimes weird flickering, when the content of the ScrollView is smaller than itself. If you have experience with UIKit and UIScrollViews, you are welcome to open a pull request to fix this. `.enableBackgroundBlur(Bool)`: Adds a fullscreen blur layer below the BottomSheet. - The opacity of the layer is proportional to the height of the BottomSheet. - The material can be changed using the `.backgroundBlurMaterial()` modifier. `.backgroundBlurMaterial(VisualEffect)`: Changes the material of the blur layer. - Changing the material does not affect whether the blur layer is shown. - To toggle the blur layer please use the `.enableBackgroundBlur()` modifier. `.showCloseButton(Bool)`: Adds a close button to the headerContent on the trailing side. - To perform a custom action when the BottomSheet is closed (not only via the close button), please use the `.onDismiss()` option. `.enableContentDrag(Bool)`: Makes it possible to resize the BottomSheet by dragging the mainContent. - Due to imitations in the SwiftUI framework, this option has no effect or even makes the BottomSheet glitch if the mainContent is packed into a ScrollView or a List. `.customAnimation(Animation?)`: Applies the given animation to the BottomSheet when any value changes. `.customBackground(...)`: Changes the background of the BottomSheet. - This works exactly like the native SwiftUI `.background(...)` modifier. - Using offset or shadow may break the hiding transition. `.onDragChanged((DragGesture.Value) -> Void)`: Adds an action to perform when the gestureโ€™s value changes. `.onDragEnded((DragGesture.Value))`: Adds an action to perform when the gesture ends. `.dragPositionSwitchAction((GeometryProxy, DragGesture.Value) -> Void)`: Replaces the action that will be performed when the user drags the sheet down. - The `GeometryProxy` and `DragGesture.Value` parameter can be used for calculations. - You need to switch the positions, account for the reversed drag direction on iPad and Mac and dismiss the keyboard yourself. - Also the `swipeToDismiss` and `flickThrough` features are triggered via this method. By replacing it, you will need to handle both yourself. - The `GeometryProxy`'s height contains the bottom safe area inserts on iPhone. - The `GeometryProxy`'s height contains the top safe area inserts on iPad and Mac. `.showDragIndicator(Bool)`: Adds a drag indicator to the BottomSheet. - On iPhone it is centered above the headerContent. - On Mac and iPad it is centered above the mainContent, - To change the color of the drag indicator please use the `.dragIndicatorColor()` modifier. `.dragIndicatorColor(Color)`: Changes the color of the drag indicator. - Changing the color does not affect whether the drag indicator is shown. - To toggle the drag indicator please use the `.showDragIndicator()` modifier. `.dragIndicatorAction((GeometryProxy) -> Void)`: Replaces the action that will be performed when the drag indicator is tapped. - The `GeometryProxy` parameter can be used for calculations. - You need to switch the positions and dismiss the keyboard yourself. - The `GeometryProxy`'s height contains the bottom safe area inserts on iPhone. - The `GeometryProxy`'s height contains the top safe area inserts on iPad and Mac. `.enableFlickThrough(Bool)`: Makes it possible to switch directly to the top or bottom position by long swiping. `.enableFloatingIPadSheet(Bool)`: Makes it possible to make the sheet appear like on iPhone. `.onDismiss(() -> Void)`: A action that will be performed when the BottomSheet is dismissed. - Please note that when you dismiss the BottomSheet yourself, by setting the bottomSheetPosition to .hidden, the action will not be called. `.isResizable(Bool)`: Makes it possible to resize the BottomSheet. - When disabled the drag indicator disappears. `.sheetWidth(BottomSheetWidth)`: Makes it possible to configure a custom sheet width. - Can be relative through `BottomSheetWidth.relative(x)`. - Can be absolute through `BottomSheetWidth.absolute(x)`. - Set to `BottomSheetWidth.platformDefault` to let the library decide the width. `.enableSwipeToDismiss(Bool)`: Makes it possible to dismiss the BottomSheet by long swiping. `.enableTapToDismiss(Bool)`: Makes it possible to dismiss the BottomSheet by tapping somewhere else. `.customThreshold(Double)`: Sets a custom threshold which determines, when to trigger swipe to dismiss or flick through. - The threshold must be positive and higher than 10% (0.1). - Changing the threshold does not affect whether either option is enabled. - The default threshold is 30% (0.3). ## BottomSheetPosition The `BottomSheetPosition` enum holds all states you can switch into. There are 3 mayor types: - `.dynamic...`, where the height of the BottomSheet is equal to its content height - `.relative...`, where the height of the BottomSheet is a percentage of the screen height - `.absolute...`, where the height of the BottomSheet is a pixel value You can combine those types as much as you want. You can also use multiple instances of one case (for example `.relative(0.4)` and `.relative(0.6)`). The positions/states in detail: ```swift /// The state where the BottomSheet is hidden. case hidden /// The state where only the headerContent is visible. case dynamicBottom /// The state where the height of the BottomSheet is equal to its content size. /// Only makes sense for views that don't take all available space (like ScrollVIew, Color, ...). case dynamic /// The state where the height of the BottomSheet is equal to its content size. /// It functions as top position for appleScrollBehaviour, /// although it doesn't make much sense to use it with dynamic. /// Only makes sense for views that don't take all available space (like ScrollVIew, Color, ...). case dynamicTop /// The state where only the headerContent is visible. /// The height of the BottomSheet is x%. /// Only values between 0 and 1 make sense. /// Instead of 0 please use `.hidden`. case relativeBottom(CGFloat) /// The state where the height of the BottomSheet is equal to x%. /// Only values between 0 and 1 make sense. /// Instead of 0 please use `.hidden`. case relative(CGFloat) /// The state where the height of the BottomSheet is equal to x%. /// It functions as top position for appleScrollBehaviour. /// Only values between 0 and 1 make sense. /// Instead of 0 please use `.hidden`. case relativeTop(CGFloat) /// The state where only the headerContent is visible /// The height of the BottomSheet is x. /// Only values above 0 make sense. /// Instead of 0 please use `.hidden`. case absoluteBottom(CGFloat) /// The state where the height of the BottomSheet is equal to x. /// Only values above 0 make sense. /// Instead of 0 please use `.hidden`. case absolute(CGFloat) /// The state where the height of the BottomSheet is equal to x. /// It functions as top position for appleScrollBehaviour. /// Only values above 0 make sense. /// Instead of 0 please use `.hidden`. case absoluteTop(CGFloat) ``` ## Examples **PLEASE NOTE:** When installed via Cocoapods, please keep in mind that the pod is called `BottomSheetSwiftUI` and not `BottomSheet`; so please use `import BottomSheetSwiftUI` instead. ### Book Detail View This BottomSheet shows additional information about a book. You can close it by swiping it away, by tapping on the background or the close button. The drag indicator is hidden. The content can be used for resizing the sheet. <img src="https://user-images.githubusercontent.com/63545066/132514316-c0d723c6-37fc-4104-b04c-6cf7bbcb0899.gif" height="600" width="278"> <details> <summary>Source Code</summary> ```swift import SwiftUI import BottomSheet struct BookDetailView: View { @State var bottomSheetPosition: BottomSheetPosition = .absolute(325) let backgroundColors: [Color] = [Color(red: 0.2, green: 0.85, blue: 0.7), Color(red: 0.13, green: 0.55, blue: 0.45)] let readMoreColors: [Color] = [Color(red: 0.70, green: 0.22, blue: 0.22), Color(red: 1, green: 0.32, blue: 0.32)] let bookmarkColors: [Color] = [Color(red: 0.28, green: 0.28, blue: 0.53), Color(red: 0.44, green: 0.44, blue: 0.83)] var body: some View { //A green gradient as a background that ignores the safe area. LinearGradient(gradient: Gradient(colors: self.backgroundColors), startPoint: .topLeading, endPoint: .bottomTrailing) .edgesIgnoringSafeArea(.all) .bottomSheet(bottomSheetPosition: self.$bottomSheetPosition, switchablePositions: [ .dynamicBottom, .absolute(325) ], headerContent: { //The name of the book as the heading and the author as the subtitle with a divider. VStack(alignment: .leading) { Text("Wuthering Heights") .font(.title).bold() Text("by Emily Brontรซ") .font(.subheadline).foregroundColor(.secondary) Divider() .padding(.trailing, -30) } .padding([.top, .leading]) }) { //A short introduction to the book, with a "Read More" button and a "Bookmark" button. VStack(spacing: 0) { Text("This tumultuous tale of life in a bleak farmhouse on the Yorkshire moors is a popular set text for GCSE and A-level English study, but away from the demands of the classroom itโ€™s easier to enjoy its drama and intensity. Populated largely by characters whose inability to control their own emotions...") .fixedSize(horizontal: false, vertical: true) HStack { Button(action: {}, label: { Text("Read More") .padding(.horizontal) }) .buttonStyle(BookButton(colors: self.readMoreColors)).clipShape(Capsule()) Spacer() Button(action: {}, label: { Image(systemName: "bookmark") }) .buttonStyle(BookButton(colors: self.bookmarkColors)).clipShape(Circle()) } .padding(.top) Spacer(minLength: 0) } .padding([.horizontal, .top]) } .showDragIndicator(false) .enableContentDrag() .showCloseButton() .enableSwipeToDismiss() .enableTapToDismiss() } } //The gradient ButtonStyle. struct BookButton: ButtonStyle { let colors: [Color] func makeBody(configuration: Configuration) -> some View { configuration.label .font(.headline) .foregroundColor(.white) .padding() .background(LinearGradient(gradient: Gradient(colors: self.colors), startPoint: .topLeading, endPoint: .bottomTrailing)) } } ``` </details> ### Word Search View This BottomSheet shows nouns which can be filtered by searching. It adapts the scrolling behaviour of apple, so that you can only scroll the `ScrollView` in the `.top` position (else the BottomSheet gets dragged); on iPad and Mac this behaviour is not present and a normal ScrollView is used. The higher the BottomSheet is dragged, the more blurry the background becomes (with the BlurEffect .systemDark) to move the focus to the BottomSheet. <img src="https://user-images.githubusercontent.com/63545066/132514347-57c5397b-ec03-4716-8e01-4e693082e844.gif" height="600" width="278"> <details> <summary>Source Code</summary> ```swift import SwiftUI import BottomSheet struct WordSearchView: View { @State var bottomSheetPosition: BottomSheetPosition = .relative(0.4) @State var searchText: String = "" let backgroundColors: [Color] = [Color(red: 0.28, green: 0.28, blue: 0.53), Color(red: 1, green: 0.69, blue: 0.26)] let words: [String] = ["birthday", "pancake", "expansion", "brick", "bushes", "coal", "calendar", "home", "pig", "bath", "reading", "cellar", "knot", "year", "ink"] var filteredWords: [String] { self.words.filter({ $0.contains(self.searchText.lowercased()) || self.searchText.isEmpty }) } var body: some View { //A green gradient as a background that ignores the safe area. LinearGradient(gradient: Gradient(colors: self.backgroundColors), startPoint: .topLeading, endPoint: .bottomTrailing) .edgesIgnoringSafeArea(.all) .bottomSheet(bottomSheetPosition: self.$bottomSheetPosition, switchablePositions: [ .relativeBottom(0.125), .relative(0.4), .relativeTop(0.975) ], headerContent: { //A SearchBar as headerContent. HStack { Image(systemName: "magnifyingglass") TextField("Search", text: self.$searchText) } .foregroundColor(Color(UIColor.secondaryLabel)) .padding(.vertical, 8) .padding(.horizontal, 5) .background(RoundedRectangle(cornerRadius: 10).fill(Color(UIColor.quaternaryLabel))) .padding([.horizontal, .bottom]) //When you tap the SearchBar, the BottomSheet moves to the .top position to make room for the keyboard. .onTapGesture { self.bottomSheetPosition = .relativeTop(0.975) } }) { //The list of nouns that will be filtered by the searchText. ForEach(self.filteredWords, id: \.self) { word in Text(word) .font(.title) .padding([.leading, .bottom]) .frame(maxWidth: .infinity, alignment: .leading) } .frame(maxWidth: .infinity, alignment: .leading) .transition(.opacity) .animation(.easeInOut, value: self.filteredWords) .padding(.top) } .enableAppleScrollBehavior() .enableBackgroundBlur() .backgroundBlurMaterial(.systemDark) } } ``` </details> ### Artist Songs View This BottomSheet shows the most popular songs by an artist. It has a custom animation and color for the drag indicator and the background, as well as it deactivates the bottom position behaviour and uses a custom corner radius and shadow. <img src="https://user-images.githubusercontent.com/63545066/132514283-b14b2977-c5d1-4b49-96b1-19995cd5a41f.gif" height="600" width="278"> <details> <summary>Source Code</summary> ```swift import SwiftUI import BottomSheet struct ArtistSongsView: View { @State var bottomSheetPosition: BottomSheetPosition = .relative(0.4) let backgroundColors: [Color] = [Color(red: 0.17, green: 0.17, blue: 0.33), Color(red: 0.80, green: 0.38, blue: 0.2)] let songs: [String] = ["One Dance (feat. Wizkid & Kyla)", "God's Plan", "SICKO MODE", "In My Feelings", "Work (feat. Drake)", "Nice For What", "Hotline Bling", "Too Good (feat. Rihanna)", "Life Is Good (feat. Drake)"] var body: some View { //A green gradient as a background that ignores the safe area. LinearGradient(gradient: Gradient(colors: self.backgroundColors), startPoint: .topLeading, endPoint: .bottomTrailing) .edgesIgnoringSafeArea(.all) .bottomSheet(bottomSheetPosition: self.$bottomSheetPosition, switchablePositions: [ .relative(0.125), .relative(0.4), .relativeTop(0.975) ], title: "Drake") { //The list of the most popular songs of the artist. ScrollView { ForEach(self.songs, id: \.self) { song in Text(song) .frame(maxWidth: .infinity, alignment: .leading) .padding([.leading, .bottom]) } } } .customAnimation(.linear.speed(0.4)) .dragIndicatorColor(Color(red: 0.17, green: 0.17, blue: 0.33)) .customBackground( Color.black .cornerRadius(30) .shadow(color: .white, radius: 10, x: 0, y: 0) ) .foregroundColor(.white) // Adding the shadow here does not break the hiding transition, but the shadow may gets added to your other views too // .shadow(color: .white, radius: 10, x: 0, y: 0) } } ``` </details> ## Test project A project to test the BottomSheet can be found [here](https://github.com/lucaszischka/BottomSheetTests). This project is used by me to test new features and to reproduce bugs, but can also be used very well as a demo project. ## Contributing BottomSheet welcomes contributions in the form of GitHub issues and pull-requests. Please check [the Discussions](https://github.com/lucaszischka/BottomSheet/discussions) before opening an issue or pull request. ## License BottomSheet is available under the MIT license. See [the LICENSE file](LICENSE.txt) for more information. ## Credits BottomSheet is a project of [@lucaszischka](https://github.com/lucaszischka).
195
๐Ÿšฉ Allows developers to configure feature flags, run multiple A/B tests or phase feature roll out using a JSON configuration file.
![FeatureFlags](https://raw.githubusercontent.com/rwbutler/FeatureFlags/master/docs/images/feature-flags-banner.png) [![CI Status](http://img.shields.io/travis/rwbutler/FeatureFlags.svg?style=flat)](https://travis-ci.org/rwbutler/FeatureFlags) [![Version](https://img.shields.io/cocoapods/v/FeatureFlags.svg?style=flat)](http://cocoapods.org/pods/Featureflags) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Maintainability](https://api.codeclimate.com/v1/badges/777e0d2788515e5f61a8/maintainability)](https://codeclimate.com/github/rwbutler/FeatureFlags/maintainability) [![License](https://img.shields.io/cocoapods/l/FeatureFlags.svg?style=flat)](http://cocoapods.org/pods/FeatureFlags) [![Platform](https://img.shields.io/cocoapods/p/FeatureFlags.svg?style=flat)](http://cocoapods.org/pods/FeatureFlags) [![Swift 5.0](https://img.shields.io/badge/Swift-5.0-orange.svg?style=flat)](https://swift.org/) [![Reviewed by Hound](https://img.shields.io/badge/Reviewed_by-Hound-8E64B0.svg)](https://houndci.com) FeatureFlags makes it easy to configure feature flags, A/B and MVT tests via a JSON file which may be bundled with your app or hosted remotely. For remotely-hosted configuration files, you may enable / disable features without another release to the App Store, update the percentages of users in A/B test groups or even roll out a feature previously under A/B test to 100% of your users once you have decided that the feature is ready for prime time. To learn more about how to use FeatureFlags, take a look at the [keynote presentation](https://github.com/rwbutler/FeatureFlags/blob/master/docs/presentations/feature-flags.pdf), check out the [blog post](https://medium.com/@rwbutler/feature-flags-a-b-testing-mvt-on-ios-718339ac7aa1), or make use of the table of contents below: - [Features](#features) - [Installation](#installation) - [Cocoapods](#cocoapods) - [Carthage](#carthage) - [Swift Package Manager](#swift-package-manager) - [Usage](#usage) - [Feature Flags](#feature-flags) - [A/B Tests](#ab-tests) - [Feature A/B Tests](#feature-ab-tests) - [Multivariate (MVT) Tests](#multivariate-mvt-tests) - [Development Flags](#development-flags) - [Unlock Flags](#unlock-flags) - [Advanced Usage](#advanced-usage) - [Test Bias](#test-bias) - [Labels](#labels) - [Rolling Out Features](#rolling-out-features) - [QA](#qa) - [Refreshing Configuration](#refreshing-configuration) - [Objective-C](#objective-c) - [Author](#author) - [License](#license) - [Additional Software](#additional-software) - [Frameworks](#frameworks) - [Tools](#tools) ## Features - [x] Feature flags - [x] A/B testing and MVT testing - [x] Feature A/B testing (where a feature is enabled vs a control group without the feature) - [x] Host your feature flags JSON configuration remotely allowing you to enable / disable features without releasing a new version of your app - [x] Use an existing JSON file or host an entirely new configuration - [x] Adjust the percentages of users in each test group remotely - [x] Convert an A/B test into a feature flag once you have decided whether the feature test was a success i.e. rollout a feature to 100% of users - [x] Visualize the state of your flags and tests using FeatureFlagsViewController in debug builds of your app ## What's new in FeatureFlags 2.6.3? When using FeatureFlags 2.6.3 with SPM, import `FeatureFlags` rather than `FeatureFlagsPackage`. ## Installation ### Cocoapods [CocoaPods](http://cocoapods.org) is a dependency manager which integrates dependencies into your Xcode workspace. To install it using [RubyGems](https://rubygems.org/) run: ```bash gem install cocoapods ``` To install FeatureFlags using Cocoapods, simply add the following line to your Podfile: ```ruby pod "FeatureFlags" ``` Then run the command: ```bash pod install ``` For more information [see here](https://cocoapods.org/#getstarted). ### Carthage Carthage is a dependency manager which produces a binary for manual integration into your project. It can be installed via [Homebrew](https://brew.sh/) using the commands: ```bash brew update brew install carthage ``` In order to integrate FeatureFlags into your project via Carthage, add the following line to your project's Cartfile: ```ogdl github "rwbutler/FeatureFlags" ``` From the macOS Terminal run `carthage update --platform iOS` to build the framework then drag `FeatureFlags.framework` into your Xcode project. For more information [see here](https://github.com/Carthage/Carthage#quick-start). ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a dependency manager for Swift modules and is included as part of the build system as of Swift 3.0. It is used to automate the download, compilation and linking of dependencies. To include FeatureFlags as a dependency within a Swift package, add the package to the `dependencies` entry in your `Package.swift` file as follows: ```swift dependencies: [ .package(url: "https://github.com/rwbutler/FeatureFlags.git", from: "2.0.0") ] ``` ## Usage With the framework integrated into your project, the next step is configuration using a JSON file which may be bundled as part of your app or hosted remotely. The JSON file may be newly-created or could be an existing configuration JSON file that you're using already. Simply add a key called `features` at the top level of your file mapping to an array of features as follows: ```json { "features": [] } ``` The contents of the array depends on the feature flags and tests to be configured. To let FeatureFlags know where to find your configuration file: ```swift guard let featuresURL = Bundle.main.url(forResource: "features", withExtension: "json") else { return } FeatureFlags.configurationURL = featuresURL ``` Or: ```swift guard let featuresURL = URL(string: "https://www.exampledomain.com/features.json") else { return } FeatureFlags.configurationURL = featuresURL ``` In the event that you opt to host your JSON file remotely, you may provide a bundled fallback as part of your app bundle: ```swift guard let fallbackURL = Bundle.main.url(forResource: "features", withExtension: "json") else { return } FeatureFlags.localFallbackConfigurationURL = fallbackURL ``` Your remotely-hosted JSON file will always take precedence over bundled settings and remotely-defined settings will be cached so that in the eventuality that the user is offline, the last settings retrieved from the network will be applied. ### Feature Flags In order to configure a feature flag add a feature object to the features array in your JSON configuration. ```json { "features": [{ "name": "Example Feature Flag", "enabled": false }] } ``` Then add an extension on `Feature.Name` to import your feature flag in code as follows: ```swift import FeatureFlags extension Feature.Name { static let exampleFeatureFlag = Feature.Name(rawValue: "Example Feature Flag") } ``` Make sure that the raw value matches the string in your JSON file. Then call the following to check whether the feature flag is enabled: ```swift Feature.isEnabled(.exampleFeatureFlag)) ``` If the string specified in your `Feature.Name` extension doesn't match the value in your JSON file, the default value returned is `false`. If you need to check the feature exists, you can write: ```swift if let feature = Feature.named(.exampleFeatureFlag) { print("Feature name -> \(feature.name)") print("Feature enabled -> \(feature.isEnabled())") } ``` ### A/B Tests To configure an A/B test, add the following feature object to the features array in your JSON file: ```json { "name": "Example A/B Test", "enabled": true, "test-variations": ["Group A", "Group B"] } ``` * `enabled` indicates whether or not the A/B test is enabled. The only difference between a feature flag and an A/B test involves adding an array of test variations. FeatureFlags will assume that you are configuring an A/B test if you add two test variations to the array - add any more and the test will automatically become a multivariate test (MVT). Import your feature into code with an extension on `Feature.Name`: ```swift extension Feature.Name { static let exampleABTest = Feature.Name(rawValue: "Example A/B Test") } ``` And then use the following to check which group the user has been assigned to: ```swift if let test = ABTest(rawValue: .exampleABTest) { print("Is in group A? -> \(test.isGroupA())") print("Is in group B? -> \(test.isGroupB())") } ``` Alternatively, you may prefer the following syntax: ```swift if let feature = Feature.named(.exampleABTest) { print("Feature name -> \(feature.name)") print("Is group A? -> \(feature.isTestVariation(.groupA))") print("Is group B? -> \(feature.isTestVariation(.groupB))") print("Test variation -> \(feature.testVariation())") } ``` ### Feature A/B Tests A feature A/B test is a subtle variation on (and subtype of) an A/B test. In a generic A/B test you may want to check whether a user has been placed in the blue background or red background test variation. A feature A/B test specifically tests whether the introduction of a new feature is an improvement over a control group without the feature. Thus in a feature A/B test - the feature is either off or on. To configure a feature A/B test use the following JSON: ```json { "name": "Example Feature A/B Test", "enabled": true, "test-variations": ["Enabled", "Disabled"] } ``` * `enabled` indicates whether or not the A/B test is enabled. ```swift extension Feature.Name { static let exampleFeatureABTest = Feature.Name(rawValue: "Example Feature A/B Test") } ``` By naming the test variations `Enabled` and `Disabled`, FeatureFlags knows that your intention is to set up a feature A/B test. Configuring a feature A/B test has the advantage over a generic A/B test in that instead of having to write: ```swift if let feature = Feature.named(.exampleFeatureABTest) { print("Feature name -> \(feature.name)") print("Is group A? -> \(feature.isTestVariation(.enabled))") print("Is group B? -> \(feature.isTestVariation(.disabled))") print("Test variation -> \(feature.testVariation())") } ``` You may simply use the following to determine which test group the user has been assigned to: ```swift Feature.isEnabled(.exampleFeatureABTest)) ``` Ordinarily using the `Feature.enabled()` method tests to see whether a feature is globally enabled; in this specific instance it will return `true` if the user belongs to the group receiving the new feature and `false` if the user belongs to the control group. Note that this method also return `false` if the `enabled` property is set to `false` in the JSON for this feature i.e. the test is globally disabled. ### Multivariate (MVT) Tests Configuration of a multivariate test follows much the same pattern as that of an A/B test. Add the following feature object to the features array in your JSON file: ```json { "name": "Example MVT Test", "enabled": true, "test-variations": ["Group A", "Group B", "Group C"] } ``` * `enabled` indicates whether or not the MVT test is enabled. FeatureFlags knows that you are configuring a MVT test if you add more than two test variations to the array. Again, import your feature into code with an extension on `Feature.Name`: ```swift extension Feature.Name { static let exampleMVTTest = Feature.Name(rawValue: "Example MVT Test") } ``` Using the following to check which group the user has been assigned to: ```swift if let feature = Feature.named(.exampleMVTTest) { print("Feature name -> \(feature.name)") print("Is group A? -> \(feature.isTestVariation(.groupA))") print("Is group B? -> \(feature.isTestVariation(.groupB))โ€) print("Is group C? -> \(feature.isTestVariation(.groupC))โ€) print("Test variation -> \(feature.testVariation())โ€) } ``` You are free to name your test variations whatever you wish: ```json { "name": "Example MVT Test", "enabled": true, "test-variations": ["Red", "Green", "Blue"] } ``` * `enabled` indicates whether or not the MVT test is enabled. Simply create an extension on `Test.Variation` to map your test variations in code: ```swift extension Test.Variation { static let red = Test.Variation(rawValue: "Red") static let green = Test.Variation(rawValue: "Green") static let blue = Test.Variation(rawValue: "Blue") } ``` Then check which group the user has been assigned to: ```swift if let feature = Feature.named(.exampleMVTTest) { print("Feature name -> \(feature.name)") print("Is red? -> \(feature.isTestVariation(.red))") print("Is green? -> \(feature.isTestVariation(.green))") print("Is blue? -> \(feature.isTestVariation(.blue))") print("Test variation -> \(feature.testVariation())") } ``` ### Development Flags When developers speak of feature flags they are often referring to one of two things: - Remote flags: Allow us to remotely toggle a finished feature on or off and roll it out to a specific group of users. - Development flags: Allow to us hide features in development in order to keep code shippable. With development flags we never want the code under development to be released to users. Consider if we were to use a remote feature flag to toggle off an unfinished feature allowing us to release version 1 of our app without the feature present. If subsequently we were to finish the feature as part of version 2 of the app and toggle the feature on then users of version one would experience a partially complete feature as the under development version 1 code is enabled. This is a situation we never want to arise hence FeatureFlags caters for development flags as well as remote flags. To mark a feature flag as a development flag, first of all include a bundled JSON file as part of your app containing the `features` key. The JSON file may be an existing file or an entirely new file. Next, having defined your feature flags as part of this file, set the configuration URL to reference this file: ```swift guard let featuresURL = Bundle.main.url(forResource: "features", withExtension: "json") else { return } FeatureFlags.configurationURL = featuresURL ``` Or, if you are already using a remote configuration URL then set the fallback configuration URL instead: ```swift guard let fallbackURL = Bundle.main.url(forResource: "features", withExtension: "json") else { return } FeatureFlags.localFallbackConfigurationURL = fallbackURL ``` Set up your feature flag in JSON as you would do normally but setting the `development` property to `true`: ```json { "features": [{ "name": "Example Feature Flag", "development": true, "enabled": true }] } ``` And that's it! From now on this feature flag will be considered a development flag and the code behind it will never be released to users even if `enabled` is set. Development flag code will be shown in the following cases: - If the `#DEBUG` preprocessor flag is set and the flag is `enabled`. - If `FeatureFlags.isDevelopment` is set to `true` (it is up to the developer to set this to `true` when the app is in development - the default value is `false`) and the flag is `enabled`. If you need more granular control over code that is in development then you may pass the `isDevelopment` flag when checking whether or not a feature is enabled e.g.: ```swift if let feature = Feature.named(.exampleFeatureFlag, isDevelopment: true) { print("Feature name -> \(feature.name)") print("Feature enabled -> \(feature.isEnabled())") } ``` In this example, the `print` statements will only be executed if `exampleFeatureFlag` is enabled and the app is development (i.e. either `#DEBUG` or `FeatureFlags.isDevelopment` is set). ### Unlock Flags Regardless of whether a feature flag is controlled locally or remotely, the types of flag above operate at global level i.e. they will enable or disable a feature for all users. But if we want to unlock a feature for individual users following an in-app purchase or as a reward for the completion of some goal then we need a way to unlock the feature and have it remain unlocked - we achieve this with *unlock flags*. To configure an unlock flag in your configuration JSON file add the following: ``` { "features": [{ "name": "Example Unlock Flag", "enabled": true, "unlocked": false }] } ``` The `unlocked` property indicates to FeatureFlags that this is to be an unlock flag whose default value is `false` i.e. the feature will be locked to begin with. Note that if `enabled` property is set to `false` then the feature will be disabled for all users regardless of whether the feature has been unlocked for a particular user as this property operates at a global level. It is possible to query whether or not an unlock flag is unlocked as follows: ``` if let feature = Feature.named(.exampleUnlockFlag) { print("Is unlocked? -> \(feature.isUnlocked())") } ``` When you wish to unlock a feature for the user, call `feature.unlock()`. Conversely, if you only wish to unlock a feature for a certain period of time e.g. to allow the user to trial a feature, you may later call `feature.lock()` to make the feature unavailable again. Both methods return a `Bool` to indicate whether or not the feature has been unlocked / locked. ``` if let feature = Feature.named(.exampleUnlockFlag) { print("Is unlocked? -> \(feature.unlock())") } ``` Note that a feature may not be unlocked if: * The feature flag is not an unlock flag i.e. the `unlocked` property was not defined in JSON. * The `enabled` property is set to `false`. ## Advanced Usage ### Test Bias By default for any A/B or MVT test, the user is equally likely to be assigned each of the specified test variations i.e. for an A/B test, there's a 50%/50% chance of being assigned one group or another. For a MVT test with four variations, the chance of being assigned to each is 25%. It is possible to configure a test bias such that the likelihood of being assigned to each test variation is not equal. To do so, simply add the following JSON to your feature object: ```json { "features": [{ "name": "Example A/B Test", "enabled": true, "test-biases": [80, 20], "test-variations": ["Group A", "Group B"] }] } ``` The number of weightings specified in the `test-biases` array must be equal to the number of test variations and must amount to 100 otherwise the weightings will be ignored and default to equal weightings. ### Labels It is possible to attach labels to test variations in case you wish to send analytics respective to the test group to which a user has been assigned. To do so, define an array of `labels` of equal length to the number of test variations specified: ```json { "features": [{ "name": "Example A/B Test", "enabled": true, "test-biases": [50, 50], "test-variations": ["Group A", "Group B"], "labels": ["label1-for-analytics", "label2-for-analytics"] }] } ``` Then to retrieve your labels in code you would write the following: ```swift if let feature = Feature.named(.exampleABTest) { print("Group A label -> \(feature.label(.groupA))") print("Group B label -> \(feature.label(.groupB))") } ``` ### Rolling Out Features The most powerful feature of the FeatureFlags framework is the ability to adjust the test biases in your remote JSON configuration file and have the users automatically be re-assigned to new test groups. For example, you might decide to roll out a feature using a 10%/90% (whereby 10% of users receive the new feature) split in the first week, 20%/80% in the second week and so on. Simply update the weightings in the `test-biases` array and the next time the framework checks your JSON configuration, groups will be re-assigned. When you are done A/B or MVT testing a feature you will have gathered enough analytics to decide whether or not to roll out the feature to your entire user base. At this point, you may decide to disable the feature entirely by setting the `enabled` flag to `false` in your JSON file or in the case of a successful test, you may decide to roll out the feature to all users by adjusting the feature object in your JSON file from: ```json { "features": [{ "name": "Example A/B Test", "enabled": true, "test-biases": [50, 50], "test-variations": ["Group A", "Group B"], "labels": ["label1-for-analytics", "label2-for-analytics"] }] } ``` To a feature flag globally enabled for all users as follows: ```json { "features": [{ "name": "Example A/B Test", "enabled": true }] } ``` ### QA In order to test that both variations of your new feature work correctly you may need to adjust the status of your feature flags / tests at runtime. To this end FeatureFlags provides the `FeatureFlagsViewController` which allows you to toggle features flags on/off in debug builds of your app or cycle A/B testing or MVT testing variations. To display the view controller specify the navigational preferences desired and then push the view controller by providing a `UINavigationController`: ```swift let navigationSettings = FeatureFlagsViewControllerNavigationSettings(autoClose: true, closeButtonAlignment: .right, closeButton: .save, isNavigationBarHidden: false) FeatureFlags.pushFeatureFlags(delegate: self, navigationController: navigationController, navigationSettings: navigationSettings) ``` ![FeatureFlagsViewController](https://raw.githubusercontent.com/rwbutler/FeatureFlags/master/docs/images/feature-flags-view-controller.png) Should you need further information on the state of each feature flag / test, you may use 3D Touch to peek / pop more information. ![FeatureDetailsViewController](https://raw.githubusercontent.com/rwbutler/FeatureFlags/master/docs/images/feature-details-view-controller.png) ### Refreshing Configuration Should you need to refresh your configuration at any time you may call `FeatureFlags.refresh()` which optionally accepts a completion closure to notify you when the refresh is complete. If you have opted to include your feature flag information as part of an existing JSON file which your app has already fetched you may wish to use the following method passing the JSON file data to avoid repeated network calls: ```swift FeatureFlags.refreshWithData(_:completion:) ``` ## Objective-C Whilst FeatureFlags is primarily intended for use by Swift apps, should the need arise to check whether a feature flag is enabled in Objective-C it is possible to do so as follows: ```objc static NSString *const kMyNewFeatureFlag = @"My New Feature Flag"; if (FEATURE_IS_ENABLED(kMyNewFeatureFlag)) { ... } ``` ## Author [Ross Butler](https://github.com/rwbutler) ## License FeatureFlags is available under the MIT license. See the [LICENSE file](./LICENSE) for more info. ## Additional Software ### Controls * [AnimatedGradientView](https://github.com/rwbutler/AnimatedGradientView) - Powerful gradient animations made simple for iOS. |[AnimatedGradientView](https://github.com/rwbutler/AnimatedGradientView) | |:-------------------------:| |[![AnimatedGradientView](https://raw.githubusercontent.com/rwbutler/AnimatedGradientView/master/docs/images/animated-gradient-view-logo.png)](https://github.com/rwbutler/AnimatedGradientView) ### Frameworks * [Cheats](https://github.com/rwbutler/Cheats) - Retro cheat codes for modern iOS apps. * [Connectivity](https://github.com/rwbutler/Connectivity) - Improves on Reachability for determining Internet connectivity in your iOS application. * [FeatureFlags](https://github.com/rwbutler/FeatureFlags) - Allows developers to configure feature flags, run multiple A/B or MVT tests using a bundled / remotely-hosted JSON configuration file. * [FlexibleRowHeightGridLayout](https://github.com/rwbutler/FlexibleRowHeightGridLayout) - A UICollectionView grid layout designed to support Dynamic Type by allowing the height of each row to size to fit content. * [Hash](https://github.com/rwbutler/Hash) - Lightweight means of generating message digests and HMACs using popular hash functions including MD5, SHA-1, SHA-256. * [Skylark](https://github.com/rwbutler/Skylark) - Fully Swift BDD testing framework for writing Cucumber scenarios using Gherkin syntax. * [TailorSwift](https://github.com/rwbutler/TailorSwift) - A collection of useful Swift Core Library / Foundation framework extensions. * [TypographyKit](https://github.com/rwbutler/TypographyKit) - Consistent & accessible visual styling on iOS with Dynamic Type support. * [Updates](https://github.com/rwbutler/Updates) - Automatically detects app updates and gently prompts users to update. |[Cheats](https://github.com/rwbutler/Cheats) |[Connectivity](https://github.com/rwbutler/Connectivity) | [FeatureFlags](https://github.com/rwbutler/FeatureFlags) | [Skylark](https://github.com/rwbutler/Skylark) | [TypographyKit](https://github.com/rwbutler/TypographyKit) | [Updates](https://github.com/rwbutler/Updates) | |:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:|:-------------------------:| |[![Cheats](https://raw.githubusercontent.com/rwbutler/Cheats/master/docs/images/cheats-logo.png)](https://github.com/rwbutler/Cheats) |[![Connectivity](https://github.com/rwbutler/Connectivity/raw/master/ConnectivityLogo.png)](https://github.com/rwbutler/Connectivity) | [![FeatureFlags](https://raw.githubusercontent.com/rwbutler/FeatureFlags/master/docs/images/feature-flags-logo.png)](https://github.com/rwbutler/FeatureFlags) | [![Skylark](https://github.com/rwbutler/Skylark/raw/master/SkylarkLogo.png)](https://github.com/rwbutler/Skylark) | [![TypographyKit](https://raw.githubusercontent.com/rwbutler/TypographyKit/master/docs/images/typography-kit-logo.png)](https://github.com/rwbutler/TypographyKit) | [![Updates](https://raw.githubusercontent.com/rwbutler/Updates/master/docs/images/updates-logo.png)](https://github.com/rwbutler/Updates) ### Tools * [Clear DerivedData](https://github.com/rwbutler/ClearDerivedData) - Utility to quickly clear your DerivedData directory simply by typing `cdd` from the Terminal. * [Config Validator](https://github.com/rwbutler/ConfigValidator) - Config Validator validates & uploads your configuration files and cache clears your CDN as part of your CI process. * [IPA Uploader](https://github.com/rwbutler/IPAUploader) - Uploads your apps to TestFlight & App Store. * [Palette](https://github.com/rwbutler/TypographyKitPalette) - Makes your [TypographyKit](https://github.com/rwbutler/TypographyKit) color palette available in Xcode Interface Builder. |[Config Validator](https://github.com/rwbutler/ConfigValidator) | [IPA Uploader](https://github.com/rwbutler/IPAUploader) | [Palette](https://github.com/rwbutler/TypographyKitPalette)| |:-------------------------:|:-------------------------:|:-------------------------:| |[![Config Validator](https://raw.githubusercontent.com/rwbutler/ConfigValidator/master/docs/images/config-validator-logo.png)](https://github.com/rwbutler/ConfigValidator) | [![IPA Uploader](https://raw.githubusercontent.com/rwbutler/IPAUploader/master/docs/images/ipa-uploader-logo.png)](https://github.com/rwbutler/IPAUploader) | [![Palette](https://raw.githubusercontent.com/rwbutler/TypographyKitPalette/master/docs/images/typography-kit-palette-logo.png)](https://github.com/rwbutler/TypographyKitPalette)
196
List of Machine Learning, AI, NLP solutions for iOS. The most recent version of this article can be found on my blog.
# Machine Learning for iOS **Last Update: January 12, 2018.** Curated list of resources for iOS developers in following topics: - [Core ML](#coreml) - [Machine Learning Libraries](#gpmll) - [Deep Learning Libraries](#dll) - [Deep Learning: Model Compression](#dlmc) - [Computer Vision](#cv) - [Natural Language Processing](#nlp) - [Speech Recognition (TTS) and Generation (STT)](#tts) - [Text Recognition (OCR)](#ocr) - [Other AI](#ai) - [Machine Learning Web APIs](#web) - [Opensource ML Applications](#mlapps) - [Game AI](#gameai) - Other related staff - [Linear algebra](#la) - [Statistics, random numbers](#stat) - [Mathematical optimization](#mo) - [Feature extraction](#fe) - [Data Visualization](#dv) - [Bioinformatics (kinda)](#bio) - [Big Data (not really)](#bd) - [iOS ML Blogs](#blogs) - [Mobile ML books](#books) - [GPU Computing Blogs](#gpublogs) - [Learn Machine Learning](#learn) - [Other Lists](#lists) Most of the de-facto standard tools in AI-related domains are written in iOS-unfriendly languages (Python/Java/R/Matlab) so finding something appropriate for your iOS application may be a challenging task. This list consists mainly of libraries written in Objective-C, Swift, C, C++, JavaScript and some other languages that can be easily ported to iOS. Also, I included links to some relevant web APIs, blog posts, videos and learning materials. Resources are sorted alphabetically or randomly. The order doesn't reflect my personal preferences or anything else. Some of the resources are awesome, some are great, some are fun, and some can serve as an inspiration. Have fun! **Pull-requests are welcome [here](https://github.com/alexsosn/iOS_ML)**. # <a name="coreml"/>Core ML * [coremltools](https://pypi.python.org/pypi/coremltools) is a Python package. It contains converters from some popular machine learning libraries to the Apple format. * [Core ML](https://developer.apple.com/documentation/coreml) is an Apple framework to run inference on device. It is highly optimized to Apple hardware. Currently CoreML is compatible (partially) with the following machine learning packages via [coremltools python package](https://apple.github.io/coremltools/): - [Caffe](http://caffe.berkeleyvision.org) - [Keras](https://keras.io/) - [libSVM](https://www.csie.ntu.edu.tw/~cjlin/libsvm/) - [scikit-learn](http://scikit-learn.org/) - [XGBoost](https://xgboost.readthedocs.io/en/latest/) Third-party converters to [CoreML format](https://apple.github.io/coremltools/coremlspecification/) are also available for some models from: - [Turicreate](https://github.com/apple/turicreate) - [TensorFlow](https://github.com/tf-coreml/tf-coreml) - [MXNet](https://github.com/apache/incubator-mxnet/tree/master/tools/coreml) - [Torch7](https://github.com/prisma-ai/torch2coreml) - [CatBoost](https://tech.yandex.com/catboost/doc/dg/features/export-model-to-core-ml-docpage/) There are many curated lists of pre-trained neural networks in Core ML format: [\[1\]](https://github.com/SwiftBrain/awesome-CoreML-models), [\[2\]](https://github.com/cocoa-ai/ModelZoo), [\[3\]](https://github.com/likedan/Awesome-CoreML-Models). Core ML currently doesn't support training models, but still, you can replace model by downloading a new one from a server in runtime. [Here is a demo](https://github.com/zedge/DynamicCoreML) of how to do it. It uses generator part of MNIST GAN as Core ML model. # <a name="gpmll"/>General-Purpose Machine Learning Libraries <p></p> <table rules="groups"> <thead> <tr> <th style="text-align: center">Library</th> <th style="text-align: center">Algorithms</th> <th style="text-align: center">Language</th> <th style="text-align: center">License</th> <th style="text-align: center">Code</th> <th style="text-align: center">Dependency manager</th> </tr> </thead> <tr> <td style="text-align: center"><a href="https://github.com/KevinCoble/AIToolbox">AIToolbox</a></td> <td> <ul> <li>Graphs/Trees</li> <ul> <li>Depth-first search</li> <li>Breadth-first search</li> <li>Hill-climb search</li> <li>Beam Search</li> <li>Optimal Path search</li> </ul> <li>Alpha-Beta (game tree)</li> <li>Genetic Algorithms</li> <li>Constraint Propogation</li> <li>Linear Regression</li> <li>Non-Linear Regression</li> <ul> <li>parameter-delta</li> <li>Gradient-Descent</li> <li>Gauss-Newton</li> </ul> <li>Logistic Regression</li> <li>Neural Networks</li> <ul> <li>multiple layers, several non-linearity models</li> <li>on-line and batch training</li> <li>feed-forward or simple recurrent layers can be mixed in one network</li> <li>LSTM network layer implemented - needs more testing</li> <li>gradient check routines</li> </ul> <li>Support Vector Machine</li> <li>K-Means</li> <li>Principal Component Analysis</li> <li>Markov Decision Process</li> <ul> <li>Monte-Carlo (every-visit, and first-visit)</li> <li>SARSA</li> </ul> <li>Single and Multivariate Gaussians</li> <li>Mixture Of Gaussians</li> <li>Model validation</li> <li>Deep Network</li> <ul> <li>Convolution layers</li> <li>Pooling layers</li> <li>Fully-connected NN layers</li> </ul> </ul> </td> <td>Swift</td> <td>Apache 2.0</td> <td><p><a href="https://github.com/KevinCoble/AIToolbox">GitHub</a></p></td> <td> </td> </tr> <tr> <td style="text-align: center"> <a href="http://dlib.net/"> <img src="http://dlib.net/dlib-logo.png" width="100" > <br>dlib</a> </td> <td> <ul> <li>Deep Learning</li> <li>Support Vector Machines</li> <li>Reduced-rank methods for large-scale classification and regression</li> <li>Relevance vector machines for classification and regression</li> <li>A Multiclass SVM</li> <li>Structural SVM</li> <li>A large-scale SVM-Rank</li> <li>An online kernel RLS regression</li> <li>An online SVM classification algorithm</li> <li>Semidefinite Metric Learning</li> <li>An online kernelized centroid estimator/novelty detector and offline support vector one-class classification</li> <li>Clustering algorithms: linear or kernel k-means, Chinese Whispers, and Newman clustering</li> <li>Radial Basis Function Networks</li> <li>Multi layer perceptrons</li> </ul> </td> <td>C++</td> <td>Boost</td> <td><a href="https://github.com/davisking/dlib">GitHub</a></td> <td></td> </tr> <tr> <td style="text-align: center"><a href="http://leenissen.dk/fann/wp/">FANN</a></td> <td> <ul> <li>Multilayer Artificial Neural Network</li> <li>Backpropagation (RPROP, Quickprop, Batch, Incremental)</li> <li>Evolving topology training</li> </ul> </td> <td>C++</td> <td>GNU LGPL 2.1</td> <td><a href="https://github.com/libfann/fann">GitHub</a></td> <td><a href="https://cocoapods.org/pods/FANN">Cocoa Pods</a></td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/lemire/lbimproved">lbimproved</a></td> <td>k-nearest neighbors and Dynamic Time Warping</td> <td>C++</td> <td>Apache 2.0</td> <td><a href="https://github.com/lemire/lbimproved">GitHub</a> </td> <td> </td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/gianlucabertani/MAChineLearning">MAChineLearning</a></td> <td> <ul> <li>Neural Networks</li> <ul> <li>Activation functions: Linear, ReLU, Step, sigmoid, TanH</li> <li>Cost functions: Squared error, Cross entropy</li> <li>Backpropagation: Standard, Resilient (a.k.a. RPROP).</li> <li>Training by sample or by batch.</li> </ul> <li>Bag of Words</li> <li>Word Vectors</li> </ul> </td> <td>Objective-C</td> <td>BSD 3-clause</td> <td><a href="https://github.com/gianlucabertani/MAChineLearning">GitHub</a> </td> <td> </td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/Somnibyte/MLKit"><img width="100" src="https://github.com/Somnibyte/MLKit/raw/master/MLKitSmallerLogo.png"><br>MLKit</a></td> <td> <ul> <li>Linear Regression: simple, ridge, polynomial</li> <li>Multi-Layer Perceptron, & Adaline ANN Architectures</li> <li>K-Means Clustering</li> <li>Genetic Algorithms</li> </ul> </td> <td>Swift</td> <td>MIT</td> <td><a href="https://github.com/Somnibyte/MLKit">GitHub</a></td> <td><a href="https://cocoapods.org/pods/MachineLearningKit">Cocoa Pods</a></td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/saniul/Mendel"><img width="100" src="https://github.com/saniul/Mendel/raw/master/[email protected]"><br>Mendel</a></td> <td>Evolutionary/genetic algorithms</td> <td>Swift</td> <td>?</td> <td><a href="https://github.com/saniul/Mendel">GitHub</a></td> <td></td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/vincentherrmann/multilinear-math">multilinear-math</a></td> <td> <ul> <li>Linear algebra and tensors</li> <li>Principal component analysis</li> <li>Multilinear subspace learning algorithms for dimensionality reduction</li> <li>Linear and logistic regression</li> <li>Stochastic gradient descent</li> <li>Feedforward neural networks</li> <ul> <li>Sigmoid</li> <li>ReLU</li> <li>Softplus activation functions</li> </ul> </ul> </td> <td>Swift</td> <td>Apache 2.0</td> <td><a href="https://github.com/vincentherrmann/multilinear-math">GitHub</a> </td> <td>Swift Package Manager</td> </tr> <tr> <td style="text-align: center"><a href="http://opencv.org/"><img width="100" src="http://opencv.org/assets/theme/logo.png">OpenCV</a></td> <td> <ul> <li>Multi-Layer Perceptrons</li> <li>Boosted tree classifier</li> <li>decision tree</li> <li>Expectation Maximization</li> <li>K-Nearest Neighbors</li> <li>Logistic Regression</li> <li>Bayes classifier</li> <li>Random forest</li> <li>Support Vector Machines</li> <li>Stochastic Gradient Descent SVM classifier</li> <li>Grid search</li> <li>Hierarchical k-means</li> <li>Deep neural networks</li> </ul> </td> <td>C++</td> <td>3-clause BSD</td> <td><a href="https://github.com/opencv">GitHub</a> </td> <td> <a href="https://cocoapods.org/pods/OpenCV">Cocoa Pods</a></td> </tr> <tr> <td style="text-align: center"><a href="http://image.diku.dk/shark/sphinx_pages/build/html/index.html"><img width="100" src="http://image.diku.dk/shark/sphinx_pages/build/html/_static/SharkLogo.png"><br>Shark</a></td> <td> <ul> <li><b>Supervised:</b> </li> <ul> <li>Linear discriminant analysis (LDA)</li> <li>Fisherโ€“LDA</li> <li>Linear regression</li> <li>SVMs</li> <li>FF NN</li> <li>RNN</li> <li>Radial basis function networks</li> <li>Regularization networks</li> <li>Gaussian processes for regression</li> <li>Iterative nearest neighbor classification and regression</li> <li>Decision trees</li> <li>Random forest</li> </ul> <li><b>Unsupervised:</b> </li> <ul> <li>PCA</li> <li>Restricted Boltzmann machines</li> <li>Hierarchical clustering</li> <li>Data structures for efficient distance-based clustering</li> </ul> <li><b>Optimization:</b> </li> <ul> <li>Evolutionary algorithms</li> <li>Single-objective optimization (e.g., CMAโ€“ES)</li> <li>Multi-objective optimization</li> <li>Basic linear algebra and optimization algorithms</li> </ul> </ul> </td> <td>C++</td> <td>GNU LGPL</td> <td><a href="https://github.com/lemire/lbimproved">GitHub</a> </td> <td><a href="https://cocoapods.org/pods/Shark-SDK">Cocoa Pods</a></td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/yconst/YCML"><img width="100" src="https://raw.githubusercontent.com/yconst/YCML/master/Logo.png"><br>YCML</a></td> <td> <ul> <li>Gradient Descent Backpropagation</li> <li>Resilient Backpropagation (RProp)</li> <li>Extreme Learning Machines (ELM)</li> <li>Forward Selection using Orthogonal Least Squares (for RBF Net), also with the PRESS statistic</li> <li>Binary Restricted Boltzmann Machines (CD & PCD)</li> <li><b>Optimization algorithms</b>: </li> <ul> <li>Gradient Descent (Single-Objective, Unconstrained)</li> <li>RProp Gradient Descent (Single-Objective, Unconstrained)</li> <li>NSGA-II (Multi-Objective, Constrained)</li> </ul> </ul> </td> <td>Objective-C</td> <td>GNU GPL 3.0</td> <td><a href="https://github.com/yconst/ycml/">GitHub</a> </td> <td> </td> </tr> <tr> <td style="text-align: center"><a href="https://github.com/Kalvar"><img width="100" src="https://avatars2.githubusercontent.com/u/1835631?v=4&s=460"><br>Kalvar Lin's libraries</a></td> <td> <ul> <li><a href="https://github.com/Kalvar/ios-KRHebbian-Algorithm">ios-KRHebbian-Algorithm</a> - <a href="https://en.wikipedia.org/wiki/Hebbian_theory">Hebbian Theory</a></li> <li><a href="https://github.com/Kalvar/ios-KRKmeans-Algorithm">ios-KRKmeans-Algorithm</a> - <a href="https://en.wikipedia.org/wiki/K-means_clustering">K-Means</a> clustering method.</li> <li><a href="https://github.com/Kalvar/ios-KRFuzzyCMeans-Algorithm">ios-KRFuzzyCMeans-Algorithm</a> - <a href="https://en.wikipedia.org/wiki/Fuzzy_clustering">Fuzzy C-Means</a>, the fuzzy clustering algorithm.</li> <li><a href="https://github.com/Kalvar/ios-KRGreyTheory">ios-KRGreyTheory</a> - <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.678.3477&amp;rep=rep1&amp;type=pdf">Grey Theory</a> / <a href="http://www.mecha.ee.boun.edu.tr/Prof.%20Dr.%20Okyay%20Kaynak%20Publications/c%20Journal%20Papers(appearing%20in%20SCI%20or%20SCIE%20or%20CompuMath)/62.pdf">Grey system theory-based models in time series prediction</a></li> <li><a href="https://github.com/Kalvar/ios-KRSVM">ios-KRSVM</a> - Support Vector Machine and SMO.</li> <li><a href="https://github.com/Kalvar/ios-KRKNN">ios-KRKNN</a> - kNN implementation.</li> <li><a href="https://github.com/Kalvar/ios-KRRBFNN">ios-KRRBFNN</a> - Radial basis function neural network and OLS.</li> </ul> </td> <td>Objective-C</td> <td>MIT</td> <td><a href="https://github.com/Kalvar">GitHub</a></td> <td></td> </tr> </table> **Multilayer perceptron implementations:** - [Brain.js](https://github.com/harthur/brain) - JS - [SNNeuralNet](https://github.com/devongovett/SNNeuralNet) - Objective-C port of brain.js - [MLPNeuralNet](https://github.com/nikolaypavlov/MLPNeuralNet) - Objective-C, Accelerate - [Swift-AI](https://github.com/Swift-AI/Swift-AI) - Swift - [SwiftSimpleNeuralNetwork](https://github.com/davecom/SwiftSimpleNeuralNetwork) - Swift - <a href="https://github.com/Kalvar/ios-BPN-NeuralNetwork">ios-BPN-NeuralNetwork</a> - Objective-C - <a href="https://github.com/Kalvar/ios-Multi-Perceptron-NeuralNetwork">ios-Multi-Perceptron-NeuralNetwork</a>- Objective-C - <a href="https://github.com/Kalvar/ios-KRDelta">ios-KRDelta</a> - Objective-C - [ios-KRPerceptron](https://github.com/Kalvar/ios-KRPerceptron) - Objective-C # <a name="dll"/>Deep Learning Libraries: ### On-Device training and inference * [Birdbrain](https://github.com/jordenhill/Birdbrain) - RNNs and FF NNs on top of Metal and Accelerate. Not ready for production. * [BrainCore](https://github.com/aleph7/BrainCore) - simple but fast neural network framework written in Swift. It uses Metal framework to be as fast as possible. ReLU, LSTM, L2 ... * [Caffe](http://caffe.berkeleyvision.org) - A deep learning framework developed with cleanliness, readability, and speed in mind. [GitHub](https://github.com/BVLC/caffe). [BSD] * [iOS port](https://github.com/aleph7/caffe) * [caffe-mobile](https://github.com/solrex/caffe-mobile) - another iOS port. * C++ examples: [Classifying ImageNet](http://caffe.berkeleyvision.org/gathered/examples/cpp_classification.html), [Extracting Features](http://caffe.berkeleyvision.org/gathered/examples/feature_extraction.html) * [Caffe iOS sample](https://github.com/noradaiko/caffe-ios-sample) * [Caffe2](https://caffe2.ai/) - a cross-platform framework made with expression, speed, and modularity in mind. * [Cocoa Pod](https://github.com/RobertBiehl/caffe2-ios) * [iOS demo app](https://github.com/KleinYuan/Caffe2-iOS) * [Convnet.js](http://cs.stanford.edu/people/karpathy/convnetjs/) - ConvNetJS is a Javascript library for training Deep Learning models by [Andrej Karpathy](https://twitter.com/karpathy). [GitHub](https://github.com/karpathy/convnetjs) * [ConvNetSwift](https://github.com/alexsosn/ConvNetSwift) - Swift port [work in progress]. * [Deep Belief SDK](https://github.com/jetpacapp/DeepBeliefSDK) - The SDK for Jetpac's iOS Deep Belief image recognition framework * [TensorFlow](http://www.tensorflow.org/) - an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API. * [iOS examples](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/ios_examples) * [another example](https://github.com/hollance/TensorFlow-iOS-Example) * [Perfect-TensorFlow](https://github.com/PerfectlySoft/Perfect-TensorFlow) - TensorFlow binding for [Perfect](http://perfect.org/) (server-side Swift framework). Includes only C TF API. * [tiny-dnn](https://github.com/tiny-dnn/tiny-dnn) - header only, dependency-free deep learning framework in C++11. * [iOS example](https://github.com/tiny-dnn/tiny-dnn/tree/d4fff53fa0d01f59eb162de2ec32c652a1f6f467/examples/ios) * [Torch](http://torch.ch/) is a scientific computing framework with wide support for machine learning algorithms. * [Torch4iOS](https://github.com/jhondge/torch4ios) * [Torch-iOS](https://github.com/clementfarabet/torch-ios) ### Deep Learning: Running pre-trained models on device These libraries doesn't support training, so you need to pre-train models in some ML framework. * [Bender](https://github.com/xmartlabs/Bender) - Framework for building fast NNs. Supports TensorFlow models. It uses Metal under the hood. * [Core ML](#coreml) * [DeepLearningKit](http://deeplearningkit.org/) - Open Source Deep Learning Framework from Memkite for Apple's tvOS, iOS and OS X. * [Espresso](https://github.com/codinfox/espresso) - A minimal high performance parallel neural network framework running on iOS. * [Forge](https://github.com/hollance/Forge) - A neural network toolkit for Metal. * [Keras.js](https://transcranial.github.io/keras-js/#/) - run [Keras](https://keras.io/) models in a web view. * [KSJNeuralNetwork](https://github.com/woffle/KSJNeuralNetwork) - A Neural Network Inference Library Built atop BNNS and MPS * [Converter for Torch models](https://github.com/woffle/torch2ios) * [MXNet](https://mxnet.incubator.apache.org/) - MXNet is a deep learning framework designed for both efficiency and flexibility. * [Deploying pre-trained mxnet model to a smartphone](https://mxnet.incubator.apache.org/how_to/smart_device.html) * [Quantized-CNN](https://github.com/jiaxiang-wu/quantized-cnn) - compressed convolutional neural networks for Mobile Devices * [WebDNN](https://mil-tokyo.github.io/webdnn/) - You can run deep learning model in a web view if you want. Three modes: WebGPU acceleration, WebAssembly acceleration and pure JS (on CPU). No training, inference only. ### Deep Learning: Low-level routines libraries * [BNNS](https://developer.apple.com/reference/accelerate/1912851-bnns) - Apple Basic neural network subroutines (BNNS) is a collection of functions that you use to implement and run neural networks, using previously obtained training data. * [BNNS usage examples](https://github.com/shu223/iOS-10-Sampler) in iOS 10 sampler. * [An example](https://github.com/bignerdranch/bnns-cocoa-example) of a neural network trained by tensorflow and executed using BNNS * [MetalPerformanceShaders](https://developer.apple.com/reference/metalperformanceshaders) - CNNs on GPU from Apple. * [MetalCNNWeights](https://github.com/kakugawa/MetalCNNWeights) - a Python script to convert Inception v3 for MPS. * [MPSCNNfeeder](https://github.com/kazoo-kmt/MPSCNNfeeder) - Keras to MPS models conversion. * [NNPACK](https://github.com/Maratyszcza/NNPACK) - Acceleration package for neural networks on multi-core CPUs. Prisma [uses](http://prisma-ai.com/libraries.html) this library in the mobile app. * [STEM](https://github.com/abeschneider/stem) - Swift Tensor Engine for Machine-learning * [Documentation](http://stem.readthedocs.io/en/latest/) ### <a name="dlmc"/>Deep Learning: Model Compression * TensorFlow implementation of [knowledge distilling](https://github.com/chengshengchan/model_compression) method * [MobileNet-Caffe](https://github.com/shicai/MobileNet-Caffe) - Caffe Implementation of Google's MobileNets * [keras-surgeon](https://github.com/BenWhetton/keras-surgeon) - Pruning for trained Keras models. # <a name="cv"/>Computer Vision * [ccv](http://libccv.org) - C-based/Cached/Core Computer Vision Library, A Modern Computer Vision Library * [iOS demo app](https://github.com/liuliu/klaus) * [OpenCV](http://opencv.org) โ€“ Open Source Computer Vision Library. [BSD] * [OpenCV crash course](http://www.pyimagesearch.com/free-opencv-crash-course/) * [OpenCVSwiftStitch](https://github.com/foundry/OpenCVSwiftStitch) * [Tutorial: using and building openCV on iOS devices](http://maniacdev.com/2011/07/tutorial-using-and-building-opencv-open-computer-vision-on-ios-devices) * [A Collection of OpenCV Samples For iOS](https://github.com/woffle/OpenCV-iOS-Demos) * [OpenFace](https://github.com/TadasBaltrusaitis/OpenFace) โ€“ a state-of-the art open source tool intended for facial landmark detection, head pose estimation, facial action unit recognition, and eye-gaze estimation. * [iOS port](https://github.com/FaceAR/OpenFaceIOS) * [iOS demo](https://github.com/FaceAR/OpenFaceIOS) * [trackingjs](http://trackingjs.com/) โ€“ Object tracking in JS * [Vision](https://developer.apple.com/documentation/vision) is an Apple framework for computer vision. # <a name="nlp"/>Natural Language Processing * [CoreLinguistics](https://github.com/rxwei/CoreLinguistics) - POS tagging (HMM), ngrams, Naive Bayes, IBM alignment models. * [GloVe](https://github.com/rxwei/GloVe-swift) Swift package. Vector words representations. * [NSLinguisticTagger](http://nshipster.com/nslinguistictagger/) * [Parsimmon](https://github.com/ayanonagon/Parsimmon) * [Twitter text](https://github.com/twitter/twitter-text-objc) - An Objective-C implementation of Twitter's text processing library. The library includes methods for extracting user names, mentions headers, hashtags, and more โ€“ all the tweet specific language syntax you could ever want. * [Verbal expressions for Swift](https://github.com/VerbalExpressions/SwiftVerbalExpressions), like regexps for humans. * [Word2Vec](https://code.google.com/p/word2vec/) - Original C implementation of Word2Vec Deep Learning algorithm. Works on iPhone like a charm. # <a name="tts"/>Speech Recognition (TTS) and Generation (STT) * [Kaldi-iOS framework](http://keenresearch.com/) - on-device speech recognition using deep learning. * [Proof of concept app](https://github.com/keenresearch/kaldi-ios-poc) * [MVSpeechSynthesizer](https://github.com/vimalmurugan89/MVSpeechSynthesizer) * [OpenEarsโ„ข: free speech recognition and speech synthesis for the iPhone](http://www.politepix.com/openears/) - OpenEarsโ„ข makes it simple for you to add offline speech recognition and synthesized speech/TTS to your iPhone app quickly and easily. It lets everyone get the great results of using advanced speech UI concepts like statistical language models and finite state grammars in their app, but with no more effort than creating an NSArray or NSDictionary. * [Tutorial (Russian)](http://habrahabr.ru/post/237589/) * [TLSphinx](https://github.com/tryolabs/TLSphinx), [Tutorial](http://blog.tryolabs.com/2015/06/15/tlsphinx-automatic-speech-recognition-asr-in-swift/) # <a name="ocr"/>Text Recognition (OCR) * [ocrad.js](https://github.com/antimatter15/ocrad.js) - JS OCR * **Tesseract** * [Install and Use Tesseract on iOS](http://lois.di-qual.net/blog/install-and-use-tesseract-on-ios-with-tesseract-ios/) * [tesseract-ios-lib](https://github.com/ldiqual/tesseract-ios-lib) * [tesseract-ios](https://github.com/ldiqual/tesseract-ios) * [Tesseract-OCR-iOS](https://github.com/gali8/Tesseract-OCR-iOS) * [OCR-iOS-Example](https://github.com/robmathews/OCR-iOS-Example) # <a name="ai"/>Other AI * [Axiomatic](https://github.com/JadenGeller/Axiomatic) - Swift unification framework for logic programming. * [Build Your Own Lisp In Swift](https://github.com/hollance/BuildYourOwnLispInSwift) * [Logician](https://github.com/mdiep/Logician) - Logic programming in Swift * [Swiftlog](https://github.com/JadenGeller/Swiftlog) - A simple Prolog-like language implemented entirely in Swift. # <a name="web"/>Machine Learning Web APIs * [**IBM** Watson](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/) - Enable Cognitive Computing Features In Your App Using IBM Watson's Language, Vision, Speech and Data APIs. * [Introducing the (beta) IBM Watson iOS SDK](https://developer.ibm.com/swift/2015/12/18/introducing-the-new-watson-sdk-for-ios-beta/) * [AlchemyAPI](http://www.alchemyapi.com/) - Semantic Text Analysis APIs Using Natural Language Processing. Now part of IBM Watson. * [**Microsoft** Project Oxford](https://www.projectoxford.ai/) * [**Google** Prediction engine](https://cloud.google.com/prediction/docs) * [Objective-C API](https://code.google.com/p/google-api-objectivec-client/wiki/Introduction) * [Google Translate API](https://cloud.google.com/translate/docs) * [Google Cloud Vision API](https://cloud.google.com/vision/) * [**Amazon** Machine Learning](http://aws.amazon.com/documentation/machine-learning/) - Amazon ML is a cloud-based service for developers. It provides visualization tools to create machine learning models. Obtain predictions for application using APIs. * [iOS developer guide](https://docs.aws.amazon.com/mobile/sdkforios/developerguide/getting-started-machine-learning.html). * [iOS SDK](https://github.com/aws/aws-sdk-ios) * [**PredictionIO**](https://prediction.io/) - opensource machine learning server for developers and ML engineers. Built on Apache Spark, HBase and Spray. * [Swift SDK](https://github.com/minhtule/PredictionIO-Swift-SDK) * [Tapster iOS Demo](https://github.com/minhtule/Tapster-iOS-Demo) - This demo demonstrates how to use the PredictionIO Swift SDK to integrate an iOS app with a PredictionIO engine to make your mobile app more interesting. * [Tutorial](https://github.com/minhtule/Tapster-iOS-Demo/blob/master/TUTORIAL.md) on using Swift with PredictionIO. * [**Wit.AI**](https://wit.ai/) - NLP API * [**Yandex** SpeechKit](https://tech.yandex.com/speechkit/mobilesdk/) Text-to-speech and speech-to-text for Russian language. iOS SDK available. * [**Abbyy** OCR SDK](http://www.abbyy.com/mobile-ocr/iphone-ocr/) * [**Clarifai**](http://www.clarifai.com/#) - deep learning web api for image captioning. [iOS starter project](https://github.com/Clarifai/clarifai-ios-starter) * [**MetaMind**](https://www.metamind.io/) - deep learning web api for image captioning. * [Api.AI](https://api.ai/) - Build intelligent speech interfaces for apps, devices, and web * [**CloudSight.ai**](https://cloudsight.ai/) - deep learning web API for fine grained object detection or whole screen description, including natural language object captions. [Objective-C](https://github.com/cloudsight/cloudsight-objc) API client is available. # <a name="mlapps"/>Opensource ML Applications ### Deep Learning * [DeepDreamer](https://github.com/johndpope/deepdreamer) - Deep Dream application * [DeepDreamApp](https://github.com/johndpope/DeepDreamApp) - Deep Dream Cordova app. * [Texture Networks](https://github.com/DmitryUlyanov/texture_nets), Lua implementation * [Feedforward style transfer](https://github.com/jcjohnson/fast-neural-style), Lua implementation * [TensorFlow implementation of Neural Style](https://github.com/cysmith/neural-style-tf) * [Corrosion detection app](https://github.com/jmolayem/corrosionapp) * [ios_camera_object_detection](https://github.com/yjmade/ios_camera_object_detection) - Realtime mobile visualize based Object Detection based on TensorFlow and YOLO model * [TensorFlow MNIST iOS demo](https://github.com/mattrajca/MNIST) - Getting Started with Deep MNIST and TensorFlow on iOS * [Drummer App](https://github.com/hollance/RNN-Drummer-Swift) with RNN and Swift * [What'sThis](https://github.com/pppoe/WhatsThis-iOS) * [enVision](https://github.com/IDLabs-Gate/enVision) - Deep Learning Models for Vision Tasks on iOS\ * [GoogLeNet on iOS demo](https://github.com/krasin/MetalDetector) * [Neural style in Android](https://github.com/naman14/Arcade) * [mnist-bnns](https://github.com/paiv/mnist-bnns) - TensorFlow MNIST demo port to BNNS * [Benchmark of BNNS vs. MPS](https://github.com/hollance/BNNS-vs-MPSCNN) * [VGGNet on Metal](https://github.com/hollance/VGGNet-Metal) * A [Sudoku Solver](https://github.com/waitingcheung/deep-sudoku-solver) that leverages TensorFlow and iOS BNNS for deep learning. * [HED CoreML Implementation](https://github.com/s1ddok/HED-CoreML) is a demo with tutorial on how to use Holistically-Nested Edge Detection on iOS with CoreML and Swift ### Traditional Computer Vision * [SwiftOCR](https://github.com/garnele007/SwiftOCR) * [GrabCutIOS](https://github.com/naver/grabcutios) - Image segmentation using GrabCut algorithm for iOS ### NLP * [Classical ELIZA chatbot in Swift](https://gist.github.com/hollance/be70d0d7952066cb3160d36f33e5636f) * [InfiniteMonkeys](https://github.com/craigomac/InfiniteMonkeys) - A Keras-trained RNN to emulate the works of a famous poet, powered by BrainCore ### Other * [Swift implementation of Joel Grus's "Data Science from Scratch"](https://github.com/graceavery/LearningMachineLearning) * [Neural Network built in Apple Playground using Swift](https://github.com/Luubra/EmojiIntelligence) # <a name="gameai"/>Game AI * [Introduction to AI Programming for Games](http://www.raywenderlich.com/24824/introduction-to-ai-programming-for-games) * [dlib](http://dlib.net/) is a library which has many useful tools including machine learning. * [MicroPather](http://www.grinninglizard.com/MicroPather/) is a path finder and A* solver (astar or a-star) written in platform independent C++ that can be easily integrated into existing code. * Here is a [list](http://www.ogre3d.org/tikiwiki/List+Of+Libraries#Artificial_intelligence) of some AI libraries suggested on OGRE3D website. Seems they are mostly written in C++. * [GameplayKit Programming Guide](https://developer.apple.com/library/content/documentation/General/Conceptual/GameplayKit_Guide/) # Other related staff ### <a name="la"/>Linear algebra * [Accelerate-in-Swift](https://github.com/hyperjeff/Accelerate-in-Swift) - Swift example codes for the Accelerate.framework * [cuda-swift](https://github.com/rxwei/cuda-swift) - Swift binding to CUDA. Not iOS, but still interesting. * [Dimensional](https://github.com/JadenGeller/Dimensional) - Swift matrices with friendly semantics and a familiar interface. * [Eigen](http://eigen.tuxfamily.org/) - A high-level C++ library of template headers for linear algebra, matrix and vector operations, numerical solvers and related algorithms. [MPL2] * [Matrix](https://github.com/hollance/Matrix) - convenient matrix type with different types of subscripts, custom operators and predefined matrices. A fork of Surge. * [NDArray](https://github.com/t-ae/ndarray) - Float library for Swift, accelerated with Accelerate Framework. * [Swift-MathEagle](https://github.com/rugheid/Swift-MathEagle) - A general math framework to make using math easy. Currently supports function solving and optimisation, matrix and vector algebra, complex numbers, big int, big frac, big rational, graphs and general handy extensions and functions. * [SwiftNum](https://github.com/donald-pinckney/SwiftNum) - linear algebra, fft, gradient descent, conjugate GD, plotting. * [Swix](https://github.com/scottsievert/swix) - Swift implementation of NumPy and OpenCV wrapper. * [Surge](https://github.com/mattt/Surge) from Mattt * [Upsurge](https://github.com/aleph7/Upsurge) - generic tensors, matrices on top of Accelerate. A fork of Surge. * [YCMatrix](https://github.com/yconst/YCMatrix) - A flexible Matrix library for Objective-C and Swift (OS X / iOS) ### <a name="stat"/>Statistics, random numbers * [SigmaSwiftStatistics](https://github.com/evgenyneu/SigmaSwiftStatistics) - A collection of functions for statistical calculation written in Swift. * [SORandom](https://github.com/SebastianOsinski/SORandom) - Collection of functions for generating psuedorandom variables from various distributions * [RandKit](https://github.com/aidangomez/RandKit) - Swift framework for random numbers & distributions. ### <a name="mo"/>Mathematical optimization * [fmincg-c](https://github.com/gautambhatrcb/fmincg-c) - Conjugate gradient implementation in C * [libLBFGS](https://github.com/chokkan/liblbfgs) - a C library of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) * [SwiftOptimizer](https://github.com/haginile/SwiftOptimizer) - QuantLib Swift port. ### <a name="fe"/>Feature extraction * [IntuneFeatures](https://github.com/venturemedia/intune-features) framework contains code to generate features from audio files and feature labels from the respective MIDI files. * [matchbox](https://github.com/hfink/matchbox) - Mel-Frequency-Cepstral-Coefficients and Dynamic-Time-Warping for iOS/OSX. **Warning: the library was updated last time when iOS 4 was still hot.** * [LibXtract](https://github.com/jamiebullock/LibXtract) is a simple, portable, lightweight library of audio feature extraction functions. ### <a name="dv"/>Data Visualization * [Charts](https://github.com/danielgindi/Charts) - The Swift port of the MPAndroidChart. * [iOS-Charts](https://github.com/danielgindi/ios-charts) * [Core Plot](https://github.com/core-plot/core-plot) * [Awesome iOS charts](https://github.com/sxyx2008/awesome-ios-chart) * [JTChartView](https://github.com/kubatru/JTChartView) * [VTK](http://www.vtk.org/gallery/) * [VTK in action](http://www.vtk.org/vtk-in-action/) * [D3.js iOS binding](https://github.com/lee-leonardo/iOS-D3) ### <a name="bio"/>Bioinformatics (kinda) * [BioJS](http://biojs.net/) - a set of tools for bioinformatics in the browser. BioJS builds a infrastructure, guidelines and tools to avoid the reinvention of the wheel in life sciences. Community builds modules than can be reused by anyone. * [BioCocoa](http://www.bioinformatics.org/biococoa/wiki/pmwiki.php) - BioCocoa is an open source OpenStep (GNUstep/Cocoa) framework for bioinformatics written in Objective-C. [Dead project]. * [iBio](https://github.com/Lizhen0909/iBio) - A Bioinformatics App for iPhone. ### <a name="bd"/>Big Data (not really) * [HDF5Kit](https://github.com/aleph7/HDF5Kit) - This is a Swift wrapper for the HDF5 file format. HDF5 is used in the scientific comunity for managing large volumes of data. The objective is to make it easy to read and write HDF5 files from Swift, including playgrounds. ### <a name="ip"/>IPython + Swift * [iSwift](https://github.com/KelvinJin/iSwift) - Swift kernel for IPython notebook. # <a name="blogs"/>iOS ML Blogs ### Regular mobile ML * **[The "Machine, think!" blog](http://machinethink.net/blog/) by Matthijs Hollemans** * [The โ€œhello worldโ€ of neural networks](http://matthijshollemans.com/2016/08/24/neural-network-hello-world/) - Swift and BNNS * [Convolutional neural networks on the iPhone with VGGNet](http://matthijshollemans.com/2016/08/30/vggnet-convolutional-neural-network-iphone/) * **[Pete Warden's blog](https://petewarden.com/)** * [How to Quantize Neural Networks with TensorFlow](https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/) ### Accidental mobile ML * **[Google research blog](https://research.googleblog.com)** * **[Apple Machine Learning Journal](https://machinelearning.apple.com/)** * **[Invasive Code](https://www.invasivecode.com/weblog/) blog** * [Machine Learning for iOS](https://www.invasivecode.com/weblog/machine-learning-swift-ios/) * [Convolutional Neural Networks in iOS 10 and macOS](https://www.invasivecode.com/weblog/convolutional-neural-networks-ios-10-macos-sierra/) * **Big Nerd Ranch** - [Use TensorFlow and BNNS to Add Machine Learning to your Mac or iOS App](https://www.bignerdranch.com/blog/use-tensorflow-and-bnns-to-add-machine-learning-to-your-mac-or-ios-app/) ### Other * [Intelligence in Mobile Applications](https://medium.com/@sadmansamee/intelligence-in-mobile-applications-ca3be3c0e773#.lgk2gt6ik) * [An exclusive inside look at how artificial intelligence and machine learning work at Apple](https://backchannel.com/an-exclusive-look-at-how-ai-and-machine-learning-work-at-apple-8dbfb131932b) * [Presentation on squeezing DNNs for mobile](https://www.slideshare.net/mobile/anirudhkoul/squeezing-deep-learning-into-mobile-phones) * [Curated list of papers on deep learning models compression and acceleration](https://handong1587.github.io/deep_learning/2015/10/09/acceleration-model-compression.html) # <a name="gpublogs"/>GPU Computing Blogs * [OpenCL for iOS](https://github.com/linusyang/opencl-test-ios) - just a test. * Exploring GPGPU on iOS. * [Article](http://ciechanowski.me/blog/2014/01/05/exploring_gpgpu_on_ios/) * [Code](https://github.com/Ciechan/Exploring-GPGPU-on-iOS) * GPU-accelerated video processing for Mac and iOS. [Article](http://www.sunsetlakesoftware.com/2010/10/22/gpu-accelerated-video-processing-mac-and-ios0). * [Concurrency and OpenGL ES](https://developer.apple.com/library/ios/documentation/3ddrawing/conceptual/opengles_programmingguide/ConcurrencyandOpenGLES/ConcurrencyandOpenGLES.html) - Apple programming guide. * [OpenCV on iOS GPU usage](http://stackoverflow.com/questions/10704916/opencv-on-ios-gpu-usage) - SO discussion. ### Metal * Simon's Gladman \(aka flexmonkey\) [blog](http://flexmonkey.blogspot.com/) * [Talk on iOS GPU programming](https://realm.io/news/altconf-simon-gladman-ios-gpu-programming-with-swift-metal/) with Swift and Metal at Realm Altconf. * [The Supercomputer In Your Pocket: Metal & Swift](https://realm.io/news/swift-summit-simon-gladman-metal/) - a video from the Swift Summit Conference 2015 * https://github.com/FlexMonkey/MetalReactionDiffusion * https://github.com/FlexMonkey/ParticleLab * [Memkite blog](http://memkite.com/) - startup intended to create deep learning library for iOS. * [Swift and Metal example for General Purpose GPU Processing on Apple TVOS 9.0](https://github.com/memkite/MetalForTVOS) * [Data Parallel Processing with Swift and Metal on GPU for iOS8](https://github.com/memkite/SwiftMetalGPUParallelProcessing) * [Example of Sharing Memory between GPU and CPU with Swift and Metal for iOS8](http://memkite.com/blog/2014/12/30/example-of-sharing-memory-between-gpu-and-cpu-with-swift-and-metal-for-ios8/) * [Metal by Example blog](http://metalbyexample.com/) * [objc-io article on Metal](https://www.objc.io/issues/18-games/metal/) # <a name="books"/>Mobile ML Books * <b>Building Mobile Applications with TensorFlow</b> by Pete Warden. [Book page](http://www.oreilly.com/data/free/building-mobile-applications-with-tensorflow.csp). <b>[Free download](http://www.oreilly.com/data/free/building-mobile-applications-with-tensorflow.csp?download=true)</b> # <a name="learn"/>Learn Machine Learning <i>Please note that in this section, I'm not trying to collect another list of ALL machine learning study resources, but only composing a list of things that I found useful.</i> * <b>[Academic Torrents](http://academictorrents.com/browse.php?cat=7)</b>. Sometimes awesome courses or datasets got deleted from their sites. But this doesn't mean, that they are lost. * [Arxiv Sanity Preserver](http://www.arxiv-sanity.com/) - a tool to keep pace with the ML research progress. ## Free Books * Immersive Linear Algebra [interactive book](http://immersivemath.com/ila/index.html) by J. Strรถm, K. ร…strรถm, and T. Akenine-Mรถller. * ["Natural Language Processing with Python"](http://www.nltk.org/book/) - free online book. * [Probabilistic Programming & Bayesian Methods for Hackers](http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/) - An intro to Bayesian methods and probabilistic programming from a computation/understanding-first, mathematics-second point of view. * ["Deep learning"](http://www.deeplearningbook.org/) - the book by Ian Goodfellow and Yoshua Bengio and Aaron Courville ## Free Courses * [Original Machine Learning Coursera course](https://www.coursera.org/learn/machine-learning/home/info) by Andrew Ng. * [Machine learning playlist on Youtube](https://www.youtube.com/playlist?list=PLD0F06AA0D2E8FFBA). * Free online interactive book ["Neural Networks and Deep Learning"](http://neuralnetworksanddeeplearning.com/). * [Heterogeneous Parallel Programming](https://www.coursera.org/course/hetero) course. * [Deep Learning for Perception](https://computing.ece.vt.edu/~f15ece6504/) by Virginia Tech, Electrical and Computer Engineering, Fall 2015: ECE 6504 * [CAP 5415 - Computer Vision](http://crcv.ucf.edu/courses/CAP5415/Fall2014/index.php) by UCF * [CS224d: Deep Learning for Natural Language Processing](http://cs224d.stanford.edu/syllabus.html) by Stanford * [Machine Learning: 2014-2015 Course materials](https://www.cs.ox.ac.uk/people/nando.defreitas/machinelearning/) by Oxford * [Stanford CS class CS231n: Convolutional Neural Networks for Visual Recognition.](http://cs231n.stanford.edu/) * [Deep Learning for Natural Language Processing \(without Magic\)](http://nlp.stanford.edu/courses/NAACL2013/) * [Videos](http://videolectures.net/deeplearning2015_montreal/) from Deep Learning Summer School, Montreal 2015. * [Deep Learning Summer School, Montreal 2016](http://videolectures.net/deeplearning2016_montreal/) # <a name="lists"/>Other Lists * [Awesome Machine Learning](https://github.com/josephmisiti/awesome-machine-learning) * [Machine Learning Courses](https://github.com/prakhar1989/awesome-courses#machine-learning) * [Awesome Data Science](https://github.com/okulbilisim/awesome-datascience) * [Awesome Computer Vision](https://github.com/jbhuang0604/awesome-computer-vision) * [Speech and language processing](https://github.com/edobashira/speech-language-processing) * [The Rise of Chat Bots:](https://stanfy.com/blog/the-rise-of-chat-bots-useful-links-articles-libraries-and-platforms/) Useful Links, Articles, Libraries and Platforms by Pavlo Bashmakov. * [Awesome Machine Learning for Cyber Security](https://github.com/jivoi/awesome-ml-for-cybersecurity)
197
Good ideas for iOS development, by Futurice developers.
iOS Good Practices ================== _Just like software, this document will rot unless we take care of it. We encourage everyone to help us on that โ€“ just open an issue or send a pull request!_ Interested in other mobile platforms? Our [Best Practices in Android Development][android-best-practices] and [Windows App Development Best Practices][windows-app-development-best-practices] documents have got you covered. [android-best-practices]: https://github.com/futurice/android-best-practices [windows-app-development-best-practices]: https://github.com/futurice/windows-app-development-best-practices ## Why? Getting on board with iOS can be intimidating. Neither Swift nor Objective-C are widely used elsewhere, the platform has its own names for almost everything, and it's a bumpy road for your code to actually make it onto a physical device. This living document is here to help you, whether you're taking your first steps in Cocoaland or you're curious about doing things "the right way". Everything below is just suggestions, so if you have a good reason to do something differently, by all means go for it! ## Contents If you are looking for something specific, you can jump right into the relevant section from here. 1. [Getting Started](#getting-started) 1. [Common Libraries](#common-libraries) 1. [Architecture](#architecture) 1. [Stores](#stores) 1. [Assets](#assets) 1. [Coding Style](#coding-style) 1. [Security](#security) 1. [Diagnostics](#diagnostics) 1. [Analytics](#analytics) 1. [Building](#building) 1. [Deployment](#deployment) 1. [In-App Purchases (IAP)](#in-app-purchases-iap) 1. [License](#license) ## Getting Started ### Human Interface Guidelines If you're coming from another platform, do take some time to familiarize yourself with Apple's [Human Interface Guidelines][ios-hig] for the platform. There is a strong emphasis on good design in the iOS world, and your app should be no exception. The guidelines also provide a handy overview of native UI elements, technologies such as 3D Touch or Wallet, and icon dimensions for designers. [ios-hig]: https://developer.apple.com/ios/human-interface-guidelines/ ### Xcode [Xcode][xcode] is the IDE of choice for most iOS developers, and the only one officially supported by Apple. There are some alternatives, of which [AppCode][appcode] is arguably the most famous, but unless you're already a seasoned iOS person, go with Xcode. Despite its shortcomings, it's actually quite usable nowadays! To install, simply download [Xcode on the Mac App Store][xcode-app-store]. It comes with the newest SDK and simulators, and you can install more stuff under _Preferences > Downloads_. [xcode]: https://developer.apple.com/xcode/ [appcode]: https://www.jetbrains.com/objc/ [xcode-app-store]: https://itunes.apple.com/us/app/xcode/id497799835 ### Project Setup A common question when beginning an iOS project is whether to write all views in code or use Interface Builder with Storyboards or XIB files. Both are known to occasionally result in working software. However, there are a few considerations: #### Why code? * Storyboards are more prone to version conflicts due to their complex XML structure. This makes merging much harder than with code. * It's easier to structure and reuse views in code, thereby keeping your codebase [DRY][dry]. * All information is in one place. In Interface Builder you have to click through all the inspectors to find what you're looking for. * Storyboards introduce coupling between your code and UI, which can lead to crashes e.g. when an outlet or action is not set up correctly. These issues are not detected by the compiler. [dry]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself #### Why Storyboards? * For the less technically inclined, Storyboards can be a great way to contribute to the project directly, e.g. by tweaking colors or layout constraints. However, this requires a working project setup and some time to learn the basics. * Iteration is often faster since you can preview certain changes without building the project. * Custom fonts and UI elements are represented visually in Storyboards, giving you a much better idea of the final appearance while designing. * For [size classes][size-classes], Interface Builder gives you a live layout preview for the devices of your choice, including iPad split-screen multitasking. [size-classes]: http://futurice.com/blog/adaptive-views-in-ios-8 #### Why not both? To get the best of both worlds, you can also take a hybrid approach: Start off by sketching the initial design with Storyboards, which are great for tinkering and quick changes. You can even invite designers to participate in this process. As the UI matures and reliability becomes more important, you then transition into a code-based setup that's easier to maintain and collaborate on. ### Ignores A good first step when putting a project under version control is to have a decent `.gitignore` file. That way, unwanted files (user settings, temporary files, etc.) will never even make it into your repository. Luckily, GitHub has us covered for both [Swift][swift-gitignore] and [Objective-C][objc-gitignore]. [swift-gitignore]: https://github.com/github/gitignore/blob/master/Swift.gitignore [objc-gitignore]: https://github.com/github/gitignore/blob/master/Objective-C.gitignore ### Dependency Management #### CocoaPods If you're planning on including external dependencies (e.g. third-party libraries) in your project, [CocoaPods][cocoapods] offers easy and fast integration. Install it like so: sudo gem install cocoapods To get started, move inside your iOS project folder and run pod init This creates a Podfile, which will hold all your dependencies in one place. After adding your dependencies to the Podfile, you run pod install to install the libraries and include them as part of a workspace which also holds your own project. For reasons stated [here][committing-pods-cocoapods] and [here][committing-pods], we recommend committing the installed dependencies to your own repo, instead of relying on having each developer run `pod install` after a fresh checkout. Note that from now on, you'll need to open the `.xcworkspace` file instead of `.xcproject`, or your code will not compile. The command pod update will update all pods to the newest versions permitted by the Podfile. You can use a wealth of [operators][cocoapods-pod-syntax] to specify your exact version requirements. [cocoapods]: https://cocoapods.org/ [cocoapods-pod-syntax]: http://guides.cocoapods.org/syntax/podfile.html#pod [committing-pods]: https://www.dzombak.com/blog/2014/03/including-pods-in-source-control.html [committing-pods-cocoapods]: https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control #### Carthage [Carthage][carthage] takes the ["simple, not easy"][simple-made-easy] approach by building your dependencies into binary frameworks, without magically integrating them with your project in any way. This also greatly reduces build times, because your dependencies have already been compiled by the time you start building. There is no centralized repository of projects, which means any library that can be compiled into a framework supports Carthage out of the box. To get started, follow the [instructions][carthage-instructions] in Carthage's documentation. [carthage]: https://github.com/Carthage/Carthage [simple-made-easy]: http://www.infoq.com/presentations/Simple-Made-Easy [carthage-instructions]: https://github.com/Carthage/Carthage#installing-carthage ### Project Structure To keep all those hundreds of source files from ending up in the same directory, it's a good idea to set up some folder structure depending on your architecture. For instance, you can use the following: โ”œโ”€ Models โ”œโ”€ Views โ”œโ”€ Controllers (or ViewModels, if your architecture is MVVM) โ”œโ”€ Stores โ”œโ”€ Helpers First, create them as groups (little yellow "folders") within the group with your project's name in Xcode's Project Navigator. Then, for each of the groups, link them to an actual directory in your project path by opening their File Inspector on the right, hitting the little gray folder icon, and creating a new subfolder with the name of the group in your project directory. #### Localization Keep all user strings in localization files right from the beginning. This is good not only for translations, but also for finding user-facing text quickly. You can add a launch argument to your build scheme to launch the app in a certain language, e.g. -AppleLanguages (Finnish) For more complex translations such as plural forms that depending on a number of items (e.g. "1 person" vs. "3 people"), you should use the [`.stringsdict` format][stringsdict-format] instead of a regular `localizable.strings` file. As soon as you've wrapped your head around the crazy syntax, you have a powerful tool that knows how to make plurals for "one", some", "few" and "many" items, as needed [e.g. in Russian or Arabic][language-plural-rules]. Find more information about localization in [these presentation slides][l10n-slides] from the February 2012 HelsinkiOS meetup. Most of the talk is still relevant. [stringsdict-format]: https://developer.apple.com/library/prerelease/ios/documentation/MacOSX/Conceptual/BPInternational/StringsdictFileFormat/StringsdictFileFormat.html [language-plural-rules]: http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html [l10n-slides]: https://speakerdeck.com/hasseg/localization-practicum #### Constants Keep your constants' scope as small as possible. For instance, when you only need it inside a class, it should live in that class. Those constants that need to be truly app-wide should be kept in one place. In Swift, you can use enums defined in a `Constants.swift` file to group, store and access your app-wide constants in a clean way: ```swift enum Config { static let baseURL = NSURL(string: "http://www.example.org/")! static let splineReticulatorName = "foobar" } enum Color { static let primaryColor = UIColor(red: 0.22, green: 0.58, blue: 0.29, alpha: 1.0) static let secondaryColor = UIColor.lightGray // A visual way to define colours within code files is to use #colorLiteral // This syntax will present you with colour picker component right on the code line static let tertiaryColor = #colorLiteral(red: 0.22, green: 0.58, blue: 0.29, alpha: 1.0) } ``` When using Objective-C, keep app-wide constants in a `Constants.h` file that is included in the prefix header. Instead of preprocessor macro definitions (via `#define`), use actual constants: static CGFloat const XYZBrandingFontSizeSmall = 12.0f; static NSString * const XYZAwesomenessDeliveredNotificationName = @"foo"; Actual constants are type-safe, have more explicit scope (theyโ€™re not available in all imported/included files until undefined), cannot be redefined or undefined in later parts of the code, and are available in the debugger. ### Branching Model Especially when distributing an app to the public (e.g. through the App Store), it's a good idea to isolate releases to their own branch with proper tags. Also, feature work that involves a lot of commits should be done on its own branch. [`git-flow`][gitflow-github] is a tool that helps you follow these conventions. It is simply a convenience wrapper around Git's branching and tagging commands, but can help maintain a proper branching structure especially for teams. Do all development on feature branches (or on `develop` for smaller work), tag releases with the app version, and commit to master only via git flow release finish <version> [gitflow-github]: https://github.com/nvie/gitflow ### Minimum iOS Version Requirement Itโ€™s useful to make an early decision on the minimum iOS version you want to support in your project: knowing which OS versions you need to develop and test against, and which system APIs you can rely on, helps you estimate your workload, and enables you to determine whatโ€™s possible and whatโ€™s not. Use these resources to gather the data necessary for making this choice: * Official โ€œfirst-partyโ€ resources: * [Appleโ€™s world-wide iOS version penetration statistics](https://developer.apple.com/support/app-store/): The primary public source for version penetration stats. Prefer more localized and domain-specific statistics, if available. * Third-party resources: * [iOS Support Matrix](http://iossupportmatrix.com): Useful for determining which specific device models are ruled out by a given minimum OS version requirement. * [DavidSmith: iOS Version Stats](https://david-smith.org/iosversionstats/): Version penetration stats for David Smithโ€™s Audiobooks apps. * [Mixpanel Trends: iOS versions](https://mixpanel.com/trends/#report/ios_frag): Version penetration stats from Mixpanel. ## Common Libraries Generally speaking, make it a conscious decision to add an external dependency to your project. Sure, this one neat library solves your problem now, but maybe later gets stuck in maintenance limbo, with the next OS version that breaks everything being just around the corner. Another scenario is that a feature only achievable with external libraries suddenly becomes part of the official APIs. In a well-designed codebase, switching out the implementation is a small effort that pays off quickly. Always consider solving the problem using Apple's extensive (and mostly excellent) frameworks first! Therefore this section has been deliberately kept rather short. The libraries featured here tend to reduce boilerplate code (e.g. Auto Layout) or solve complex problems that require extensive testing, such as date calculations. As you become more proficient with iOS, be sure to dive into the source here and there, and acquaint yourself with their underlying Apple frameworks. You'll find that those alone can do a lot of the heavy lifting. ### AFNetworking/Alamofire The majority of iOS developers use one of these network libraries. While `NSURLSession` is surprisingly powerful by itself, [AFNetworking][afnetworking-github] and [Alamofire][alamofire-github] remain unbeaten when it comes to actually managing queues of requests, which is pretty much a requirement of any modern app. We recommend AFNetworking for Objective-C projects and Alamofire for Swift projects. While the two frameworks have subtle differences, they share the same ideology and are published by the same foundation. [afnetworking-github]: https://github.com/AFNetworking/AFNetworking [alamofire-github]: https://github.com/Alamofire/Alamofire ### DateTools As a general rule, [don't write your date calculations yourself][timezones-youtube]. Luckily, in [DateTools][datetools-github] you get an MIT-licensed, thoroughly tested library that covers pretty much all your calendar needs. [timezones-youtube]: https://www.youtube.com/watch?v=-5wpm-gesOY [datetools-github]: https://github.com/MatthewYork/DateTools ### Auto Layout Libraries If you prefer to write your views in code, chances are you've heard of either Apple's awkward syntaxes โ€“ the regular `NSLayoutConstraint` factory or the so-called [Visual Format Language][visual-format-language]. The former is extremely verbose and the latter based on strings, which effectively prevents compile-time checking. Fortunately, they've addressed the issue in iOS 9, allowing [a more concise specification of constraints][nslayoutanchor]. If you're stuck with an earlier iOS version, [Masonry/SnapKit][snapkit-github] remedies the problem by introducing its own [DSL][dsl-wikipedia] to make, update and replace constraints. [PureLayout][purelayout-github] solves the same problem using Cocoa API style. For Swift, there is also [Cartography][cartography-github], which builds on the language's powerful operator overloading features. For the more conservative, [FLKAutoLayout][flkautolayout-github] offers a clean, but rather non-magical wrapper around the native APIs. [visual-format-language]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html [nslayoutanchor]: https://developer.apple.com/library/prerelease/ios/documentation/AppKit/Reference/NSLayoutAnchor_ClassReference/index.html [snapkit-github]: https://github.com/SnapKit/ [purelayout-github]: https://github.com/PureLayout/PureLayout [dsl-wikipedia]: https://en.wikipedia.org/wiki/Domain-specific_language [cartography-github]: https://github.com/robb/Cartography [flkautolayout-github]: https://github.com/floriankugler/FLKAutoLayout ## Architecture * [Model-View-Controller-Store (MVCS)][mvcs] * This is the default Apple architecture (MVC), extended by a Store layer that vends Model instances and handles the networking, caching etc. * Every Store exposes to the view controllers either `signals` or `void` methods with custom completion blocks. * [Model-View-ViewModel (MVVM)][mvvm] * Motivated by "massive view controllers": MVVM considers `UIViewController` subclasses part of the View and keeps them slim by maintaining all state in the ViewModel. * To learn more about it, check out Bob Spryn's [fantastic introduction][sprynthesis-mvvm]. * [View-Interactor-Presenter-Entity-Routing (VIPER)][viper] * Rather exotic architecture that might be worth looking into in larger projects, where even MVVM feels too cluttered and testability is a major concern. [mvcs]: http://programmers.stackexchange.com/questions/184396/mvcs-model-view-controller-store [mvvm]: https://www.objc.io/issues/13-architecture/mvvm/ [sprynthesis-mvvm]: http://www.sprynthesis.com/2014/12/06/reactivecocoa-mvvm-introduction/ [viper]: https://www.objc.io/issues/13-architecture/viper/ ### โ€œEventโ€ Patterns These are the idiomatic ways for components to notify others about things: * __Delegation:__ _(one-to-one)_ Apple uses this a lot (some would say, too much). Use when you want to communicate stuff back e.g. from a modal view. * __Callback blocks:__ _(one-to-one)_ Allow for a more loose coupling, while keeping related code sections close to each other. Also scales better than delegation when there are many senders. * __Notification Center:__ _(one-to-many)_ Possibly the most common way for objects to emit โ€œeventsโ€ to multiple observers. Very loose coupling โ€” notifications can even be observed globally without reference to the dispatching object. * __Key-Value Observing (KVO):__ _(one-to-many)_ Does not require the observed object to explicitly โ€œemit eventsโ€ as long as it is _Key-Value Coding (KVC)_ compliant for the observed keys (properties). Usually not recommended due to its implicit nature and the cumbersome standard library API. * __Signals:__ _(one-to-many)_ The centerpiece of [ReactiveCocoa][reactivecocoa-github], they allow chaining and combining to your heart's content, thereby offering a way out of "callback hell". ### Models Keep your models immutable, and use them to translate the remote API's semantics and types to your app. For Objective-C projects, Github's [Mantle](https://github.com/Mantle/Mantle) is a good choice. In Swift, you can use structs instead of classes to ensure immutability, and use Swift's [Codable][codableLink] to do the JSON-to-model mapping. There are also few third party libraries available. [SwiftyJSON][swiftyjson] and [Argo][argo] are the popular among them. [swiftyjson]: https://github.com/SwiftyJSON/SwiftyJSON [argo]: https://github.com/thoughtbot/Argo [codableLink]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types ### Views With today's wealth of screen sizes in the Apple ecosystem and the advent of split-screen multitasking on iPad, the boundaries between devices and form factors become increasingly blurred. Much like today's websites are expected to adapt to different browser window sizes, your app should handle changes in available screen real estate in a graceful way. This can happen e.g. if the user rotates the device or swipes in a secondary iPad app next to your own. Instead of manipulating view frames directly, you should use [size classes][size-classes] and Auto Layout to declare constraints on your views. The system will then calculate the appropriate frames based on these rules, and re-evaluate them when the environment changes. Apple's [recommended approach][wwdc-autolayout-mysteries] for setting up your layout constraints is to create and activate them once during initialization. If you need to change your constraints dynamically, hold references to them and then deactivate/activate them as required. The main use case for `UIView`'s `updateConstraints` (or its `UIViewController` counterpart, `updateViewConstraints`) is when you want the system to perform batch updates for better performance. However, this comes at the cost of having to call `setNeedsUpdateConstraints` elsewhere in your code, increasing its complexity. If you override `updateConstraints` in a custom view, you should explicitly state that your view requires a constraint-based layout: Swift: ```swift override class var requiresConstraintBasedLayout: Bool { return true } ``` Objective-C: ```objective-c + (BOOL)requiresConstraintBasedLayout { return YES } ``` Otherwise, you may encounter strange bugs when the system doesn't call `updateConstraints()` as you would expect it to. [This blog post][edward-huynh-requiresconstraintbasedlayout] by Edward Huynh offers a more detailed explanation. [wwdc-autolayout-mysteries]: https://developer.apple.com/videos/wwdc/2015/?id=219 [edward-huynh-requiresconstraintbasedlayout]: http://www.edwardhuynh.com/blog/2013/11/24/the-mystery-of-the-requiresconstraintbasedlayout/ ### Controllers Use dependency injection, i.e. pass any required objects in as parameters, instead of keeping all state around in singletons. The latter is okay only if the state _really_ is global. Swift: ```swift let fooViewController = FooViewController(withViewModel: fooViewModel) ``` Objective-C: ```objective-c FooViewController *fooViewController = [[FooViewController alloc] initWithViewModel:fooViewModel]; ``` Try to avoid bloating your view controllers with logic that can safely reside in other places. Soroush Khanlou has a [good writeup][khanlou-destroy-massive-vc] of how to achieve this, and architectures like [MVVM](#architecture) treat view controllers as views, thereby greatly reducing their complexity. [khanlou-destroy-massive-vc]: http://khanlou.com/2014/09/8-patterns-to-help-you-destroy-massive-view-controller/ ## Stores At the "ground level" of a mobile app is usually some kind of model storage, that keeps its data in places such as on disk, in a local database, or on a remote server. This layer is also useful to abstract away any activities related to the vending of model objects, such as caching. Whether it means kicking off a backend request or deserializing a large file from disk, fetching data is often asynchronous in nature. Your store's API should reflect this by offering some kind of deferral mechanism, as synchronously returning the data would cause the rest of your app to stall. If you're using [ReactiveCocoa][reactivecocoa-github], `SignalProducer` is a natural choice for the return type. For instance, fetching gigs for a given artist would yield the following signature: Swift + ReactiveSwift: ```swift func fetchGigs(for artist: Artist) -> SignalProducer<[Gig], Error> { // ... } ``` ObjectiveC + ReactiveObjC: ```objective-c - (RACSignal<NSArray<Gig *> *> *)fetchGigsForArtist:(Artist *)artist { // ... } ``` Here, the returned `SignalProducer` is merely a "recipe" for getting a list of gigs. Only when started by the subscriber, e.g. a view model, will it perform the actual work of fetching the gigs. Unsubscribing before the data has arrived would then cancel the network request. If you don't want to use signals, futures or similar mechanisms to represent your future data, you can also use a regular callback block. Keep in mind that chaining or nesting such blocks, e.g. in the case where one network request depends on the outcome of another, can quickly become very unwieldy โ€“ a condition generally known as "callback hell". ## Assets [Asset catalogs][asset-catalogs] are the best way to manage all your project's visual assets. They can hold both universal and device-specific (iPhone 4-inch, iPhone Retina, iPad, etc.) assets and will automatically serve the correct ones for a given name. Teaching your designer(s) how to add and commit things there (Xcode has its own built-in Git client) can save a lot of time that would otherwise be spent copying stuff from emails or other channels to the codebase. It also allows them to instantly try out their changes and iterate if needed. [asset-catalogs]: http://help.apple.com/xcode/mac/8.0/#/dev10510b1f7 ### Using Bitmap Images Asset catalogs expose only the names of image sets, abstracting away the actual file names within the set. This nicely prevents asset name conflicts, as files such as `[email protected]` are now namespaced inside their image sets. Appending the modifiers `-568h`, `@2x`, `~iphone` and `~ipad` are not required per se, but having them in the file name when dragging the file to an image set will automatically place them in the right "slot", thereby preventing assignment mistakes that can be hard to hunt down. ### Using Vector Images You can include the original [vector graphics (PDFs)][vector-assets] produced by designers into the asset catalogs, and have Xcode automatically generate the bitmaps from that. This reduces the complexity of your project (the number of files to manage.) [vector-assets]: http://martiancraft.com/blog/2014/09/vector-images-xcode6/ ### Image optimisation Xcode automatically tries to optimise resources living in asset catalogs (yet another reason to use them). Developers can choose from lossless and lossy compression algorithms. App icons are an exception: Apps with large or unoptimised app icons are known to be rejected by Apple. For app icons and more advanced optimisation of PNG files we recommend using [pngcrush][pngcrush-website] or [ImageOptim][imageoptim-website], its GUI counterpart. [pngcrush-website]: http://pmt.sourceforge.net/pngcrush/ [imageoptim-website]:https://imageoptim.com/mac ## Coding Style ### Naming Apple pays great attention to keeping naming consistent. Adhering to their [coding guidelines for Objective-C][cocoa-coding-guidelines] and [API design guidelines for Swift][swift-api-design-guidelines] makes it much easier for new people to join the project. [cocoa-coding-guidelines]: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html [swift-api-design-guidelines]: https://swift.org/documentation/api-design-guidelines/ Here are some basic takeaways you can start using right away: A method beginning with a _verb_ indicates that it performs some side effects, but won't return anything: `- (void)loadView;` `- (void)startAnimating;` Any method starting with a _noun_, however, returns that object and should do so without side effects: `- (UINavigationItem *)navigationItem;` `+ (UILabel *)labelWithText:(NSString *)text;` It pays off to keep these two as separated as possible, i.e. not perform side effects when you transform data, and vice versa. That will keep your side effects contained to smaller sections of the code, which makes it more understandable and facilitates debugging. ### Structure `MARK:` comments (Swift) and [pragma marks][nshipster-pragma-marks] (Objective-C) are a great way to group your methods, especially in view controllers. Here is a Swift example for a common structure that works with almost any view controller: ```swift import SomeExternalFramework class FooViewController : UIViewController, FoobarDelegate { let foo: Foo private let fooStringConstant = "FooConstant" private let floatConstant = 1234.5 // MARK: Lifecycle // Custom initializers go here // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() // ... } // MARK: Layout private func makeViewConstraints() { // ... } // MARK: User Interaction func foobarButtonTapped() { // ... } // MARK: FoobarDelegate func foobar(foobar: Foobar, didSomethingWithFoo foo: Foo) { // ... } // MARK: Additional Helpers private func displayNameForFoo(foo: Foo) { // ... } } ``` The most important point is to keep these consistent across your project's classes. [nshipster-pragma-marks]: http://nshipster.com/pragma/ ### External Style Guides Futurice does not have company-level guidelines for coding style. It can however be useful to peruse the style guides of other software companies, even if some bits can be quite company-specific or opinionated. * GitHub: [Swift](https://github.com/github/swift-style-guide) and [Objective-C](https://github.com/github/objective-c-style-guide) * Ray Wenderlich: [Swift](https://github.com/raywenderlich/swift-style-guide) and [Objective-C](https://github.com/raywenderlich/objective-c-style-guide) * Google: [Objective-C](https://google.github.io/styleguide/objcguide.xml) * The New York Times: [Objective-C](https://github.com/NYTimes/objective-c-style-guide) * Sam Soffes: [Objective-C](https://gist.github.com/soffes/812796) * Luke Redpath: [Objective-C](http://lukeredpath.co.uk/blog/2011/06/28/my-objective-c-style-guide/) ## Security Even in an age where we trust our portable devices with the most private data, app security remains an often-overlooked subject. Try to find a good trade-off given the nature of your data; following just a few simple rules can go a long way here. A good resource to get started is Apple's own [iOS Security Guide][apple-security-guide]. ### Data Storage If your app needs to store sensitive data, such as a username and password, an authentication token or some personal user details, you need to keep these in a location where they cannot be accessed from outside the app. Never use `NSUserDefaults`, other plist files on disk or Core Data for this, as they are not encrypted! In most such cases, the iOS Keychain is your friend. If you're uncomfortable working with the C APIs directly, you can use a wrapper library such as [SSKeychain][sskeychain] or [UICKeyChainStore][uickeychainstore]. When storing files and passwords, be sure to set the correct protection level, and choose it conservatively. If you need access while the device is locked (e.g. for background tasks), use the "accessible after first unlock" variety. In other cases, you should probably require that the device is unlocked to access the data. Only keep sensitive data around while you need it. ### Networking Keep any HTTP traffic to remote servers encrypted with TLS at all times. To avoid man-in-the-middle attacks that intercept your encrypted traffic, you can set up [certificate pinning][certificate-pinning]. Popular networking libraries such as [AFNetworking][afnetworking-github] and [Alamofire][alamofire-github] support this out of the box. ### Logging Take extra care to set up proper log levels before releasing your app. Production builds should never log passwords, API tokens and the like, as this can easily cause them to leak to the public. On the other hand, logging the basic control flow can help you pinpoint issues that your users are experiencing. ### User Interface When using `UITextField`s for password entry, remember to set their `secureTextEntry` property to `true` to avoid showing the password in cleartext. You should also disable auto-correction for the password field, and clear the field whenever appropriate, such as when your app enters the background. When this happens, it's also good practice to clear the Pasteboard to avoid passwords and other sensitive data from leaking. As iOS may take screenshots of your app for display in the app switcher, make sure to clear any sensitive data from the UI _before_ returning from `applicationDidEnterBackground`. [apple-security-guide]: https://www.apple.com/business/docs/iOS_Security_Guide.pdf [sskeychain]: https://github.com/soffes/sskeychain [uickeychainstore]: https://github.com/kishikawakatsumi/UICKeyChainStore [certificate-pinning]: https://possiblemobile.com/2013/03/ssl-pinning-for-increased-app-security/ [alamofire-github]: https://github.com/Alamofire/Alamofire ## Diagnostics ### Compiler warnings Enable as many compiler warnings as possible and treat those warnings as errors -- [it will be worth it in the long run][warnings-slides]. For Objective-C code, add these values to the _โ€œOther Warning Flagsโ€_ build setting: - `-Wall` _(enables lots of additional warnings)_ - `-Wextra` _(enables more additional warnings)_ and then enable the _โ€œTreat warnings as errorsโ€_ build setting. To treat warnings as errors for Swift code, add `-warnings-as-errors` to the _"Other Swift Flags"_ build setting. [warnings-slides]: https://speakerdeck.com/hasseg/the-compiler-is-your-friend ### Clang Static Analyzer The Clang compiler (which Xcode uses) has a _static analyzer_ that performs control and data flow analysis on your code and checks for lots of errors that the compiler cannot. You can manually run the analyzer from the _Product โ†’ Analyze_ menu item in Xcode. The analyzer can work in either โ€œshallowโ€ or โ€œdeepโ€ mode. The latter is much slower but may find more issues due to cross-function control and data flow analysis. Recommendations: - Enable _all_ of the checks in the analyzer (by enabling all of the options in the โ€œStatic Analyzerโ€ build setting sections). - Enable the _โ€œAnalyze during โ€˜Buildโ€™โ€_ build setting for your release build configuration to have the analyzer run automatically during release builds. (Seriously, do this โ€” youโ€™re not going to remember to run it manually.) - Set the _โ€œMode of Analysis for โ€˜Analyzeโ€™โ€_ build setting to _Shallow (faster)_. - Set the _โ€œMode of Analysis for โ€˜Buildโ€™โ€_ build setting to _Deep_. ### [Faux Pas](http://fauxpasapp.com/) Created by our very own [Ali Rantakari][ali-rantakari-twitter], Faux Pas is a fabulous static error detection tool. It analyzes your codebase and finds issues you had no idea even existed. There is no Swift support yet, but the tool also offers plenty of language-agnostic rules. Be sure to run it before shipping any iOS (or Mac) app! _(Note: all Futurice employees get a free license to this โ€” just ask Ali.)_ [ali-rantakari-twitter]: https://twitter.com/AliRantakari ### Debugging When your app crashes, Xcode does not break into the debugger by default. To achieve this, add an exception breakpoint (click the "+" at the bottom of Xcode's Breakpoint Navigator) to halt execution whenever an exception is raised. In many cases, you will then see the line of code responsible for the exception. This catches any exception, even handled ones. If Xcode keeps breaking on benign exceptions in third party libraries e.g., you might be able to mitigate this by choosing _Edit Breakpoint_ and setting the _Exception_ drop-down to _Objective-C_. For view debugging, [Reveal][reveal] and [Spark Inspector][spark-inspector] are two powerful visual inspectors that can save you hours of time, especially if you're using Auto Layout and want to locate views that are collapsed or off-screen. Xcode also has integrated [view debugger][xcode-view-debugging] which is good enough and free to use. [reveal]: http://revealapp.com/ [spark-inspector]: http://sparkinspector.com [xcode-view-debugging]: https://developer.apple.com/library/prerelease/content/documentation/DeveloperTools/Conceptual/debugging_with_xcode/chapters/special_debugging_workflows.html ### Profiling Xcode comes with a profiling suite called Instruments. It contains a myriad of tools for profiling memory usage, CPU, network communications, graphics and much more. It's a complex beast, but one of its more straight-forward use cases is tracking down memory leaks with the Allocations instrument. Simply choose _Product_ > _Profile_ in Xcode, select the Allocations instrument, hit the Record button and filter the Allocation Summary on some useful string, like the prefix of your own app's class names. The count in the Persistent column then tells you how many instances of each object you have. Any class for which the instance count increases indiscriminately indicates a memory leak. Pay extra attention to how and where you create expensive classes. `NSDateFormatter`, for instance, is very expensive to create and doing so in rapid succession, e.g. inside a `tableView:cellForRowAtIndexPath:` method, can really slow down your app. Instead, keep a static instance of it around for each date format that you need. ## Analytics Including some analytics framework in your app is strongly recommended, as it allows you to gain insights on how people actually use it. Does feature X add value? Is button Y too hard to find? To answer these, you can send events, timings and other measurable information to a service that aggregates and visualizes them โ€“ for instance, [Google Tag Manager][google-tag-manager]. The latter is more versatile than Google Analytics in that it inserts a data layer between app and Analytics, so that the data logic can be modified through a web service without having to update the app. [google-tag-manager]: https://www.google.com/analytics/tag-manager/ A good practice is to create a slim helper class, e.g. `AnalyticsHelper`, that handles the translation from app-internal models and data formats (`FooModel`, `NSTimeInterval`, โ€ฆ) to the mostly string-based data layer: ```swift func pushAddItemEvent(with item: Item, editMode: EditMode) { let editModeString = name(for: editMode) pushToDataLayer([ "event": "addItem", "itemIdentifier": item.identifier, "editMode": editModeString ]) } ``` This has the additional advantage of allowing you to swap out the entire Analytics framework behind the scenes if needed, without the rest of the app noticing. ### Crash Logs First you should make your app send crash logs onto a server somewhere so that you can access them. You can implement this manually (using [PLCrashReporter][plcrashreporter] and your own backend) but itโ€™s recommended that you use an existing service instead โ€” for example one of the following: * [Fabric](https://get.fabric.io) * [HockeyApp](http://hockeyapp.net) * [Crittercism](https://www.crittercism.com) * [Splunk MINTexpress](https://mint.splunk.com) * [Instabug](https://instabug.com/) [plcrashreporter]: https://www.plcrashreporter.org Once you have this set up, ensure that you _save the Xcode archive (`.xcarchive`)_ of every build you release. The archive contains the built app binary and the debug symbols (`dSYM`) which you will need to symbolicate crash reports from that particular version of your app. ## Building This section contains an overview of this topic โ€” please refer here for more comprehensive information: - [iOS Developer Library: Xcode Concepts][apple-xcode-concepts] - [Samantha Marshall: Managing Xcode][pewpew-managing-xcode] [apple-xcode-concepts]: https://developer.apple.com/library/ios/featuredarticles/XcodeConcepts/ [pewpew-managing-xcode]: http://pewpewthespells.com/blog/managing_xcode.html ### Build Configurations Even simple apps can be built in different ways. The most basic separation that Xcode gives you is that between _debug_ and _release_ builds. For the latter, there is a lot more optimization going on at compile time, at the expense of debugging possibilities. Apple suggests that you use the _debug_ build configuration for development, and create your App Store packages using the _release_ build configuration. This is codified in the default scheme (the dropdown next to the Play and Stop buttons in Xcode), which commands that _debug_ be used for Run and _release_ for Archive. However, this is a bit too simple for real-world applications. You might โ€“ no, [_should!_][futurice-environments] โ€“ have different environments for testing, staging and other activities related to your service. Each might have its own base URL, log level, bundle identifier (so you can install them side-by-side), provisioning profile and so on. Therefore a simple debug/release distinction won't cut it. You can add more build configurations on the "Info" tab of your project settings in Xcode. [futurice-environments]: http://futurice.com/blog/five-environments-you-cannot-develop-without #### `xcconfig` files for build settings Typically build settings are specified in the Xcode GUI, but you can also use _configuration settings files_ (โ€œ`.xcconfig` filesโ€) for them. The benefits of using these are: - You can add comments to explain things. - You can `#include` other build settings files, which helps you avoid repeating yourself: - If you have some settings that apply to all build configurations, add a `Common.xcconfig` and `#include` it in all the other files. - If you e.g. want to have a โ€œDebugโ€ build configuration that enables compiler optimizations, you can just `#include "MyApp_Debug.xcconfig"` and override one of the settings. - Conflict resolution and merging becomes easier. Find more information about this topic in [these presentation slides][xcconfig-slides]. [xcconfig-slides]: https://speakerdeck.com/hasseg/xcode-configuration-files ### Targets A target resides conceptually below the project level, i.e. a project can have several targets that may override its project settings. Roughly, each target corresponds to "an app" within the context of your codebase. For instance, you could have country-specific apps (built from the same codebase) for different countries' App Stores. Each of these will need development/staging/release builds, so it's better to handle those through build configurations, not targets. It's not uncommon at all for an app to only have a single target. ### Schemes Schemes tell Xcode what should happen when you hit the Run, Test, Profile, Analyze or Archive action. Basically, they map each of these actions to a target and a build configuration. You can also pass launch arguments, such as the language the app should run in (handy for testing your localizations!) or set some diagnostic flags for debugging. A suggested naming convention for schemes is `MyApp (<Language>) [Environment]`: MyApp (English) [Development] MyApp (German) [Development] MyApp [Testing] MyApp [Staging] MyApp [App Store] For most environments the language is not needed, as the app will probably be installed through other means than Xcode, e.g. TestFlight, and the launch argument thus be ignored anyway. In that case, the device language should be set manually to test localization. ## Deployment Deploying software on iOS devices isn't exactly straightforward. That being said, here are some central concepts that, once understood, will help you tremendously with it. ### Signing Whenever you want to run software on an actual device (as opposed to the simulator), you will need to sign your build with a __certificate__ issued by Apple. Each certificate is linked to a private/public keypair, the private half of which resides in your Mac's Keychain. There are two types of certificates: * __Development certificate:__ Every developer on a team has their own, and it is generated upon request. Xcode might do this for you, but it's better not to press the magic "Fix issue" button and understand what is actually going on. This certificate is needed to deploy development builds to devices. * __Distribution certificate:__ There can be several, but it's best to keep it to one per organization, and share its associated key through some internal channel. This certificate is needed to ship to the App Store, or your organization's internal "enterprise app store". ### Provisioning Besides certificates, there are also __provisioning profiles__, which are basically the missing link between devices and certificates. Again, there are two types to distinguish between development and distribution purposes: * __Development provisioning profile:__ It contains a list of all devices that are authorized to install and run the software. It is also linked to one or more development certificates, one for each developer that is allowed to use the profile. The profile can be tied to a specific app or use a wildcard App ID (*). The latter is [discouraged][jared-sinclair-signing-tips], because Xcode is notoriously bad at picking the correct files for signing unless guided in the right direction. Also, certain capabilities like Push Notifications or App Groups require an explicit App ID. * __Distribution provisioning profile:__ There are three different ways of distribution, each for a different use case. Each distribution profile is linked to a distribution certificate, and will be invalid when the certificate expires. * __Ad-Hoc:__ Just like development profiles, it contains a whitelist of devices the app can be installed to. This type of profile can be used for beta testing on 100 devices per year. For a smoother experience and up to 1000 distinct users, you can use Apple's newly acquired [TestFlight][testflight] service. Supertop offers a good [summary of its advantages and issues][testflight-discussion]. * __App Store:__ This profile has no list of allowed devices, as anyone can install it through Apple's official distribution channel. This profile is required for all App Store releases. * __Enterprise:__ Just like App Store, there is no device whitelist, and the app can be installed by anyone with access to the enterprise's internal "app store", which can be just a website with links. This profile is available only on Enterprise accounts. [jared-sinclair-signing-tips]: http://blog.jaredsinclair.com/post/116436789850/ [testflight]: https://developer.apple.com/testflight/ [testflight-discussion]: http://blog.supertop.co/post/108759935377/app-developer-friends-try-testflight To sync all certificates and profiles to your machine, go to Accounts in Xcode's Preferences, add your Apple ID if needed, and double-click your team name. There is a refresh button at the bottom, but sometimes you just need to restart Xcode to make everything show up. #### Debugging Provisioning Sometimes you need to debug a provisioning issue. For instance, Xcode may refuse to install the build to an attached device, because the latter is not on the (development or ad-hoc) profile's device list. In those cases, you can use Craig Hockenberry's excellent [Provisioning][provisioning] plugin by browsing to `~/Library/MobileDevice/Provisioning Profiles`, selecting a `.mobileprovision` file and hitting Space to launch Finder's Quick Look feature. It will show you a wealth of information such as devices, entitlements, certificates, and the App ID. When dealing with an existing app archive (`.ipa`), you can inspect its provisioning profile in a similar fashion: Simply rename the `*.ipa` to `*.zip`, unpack it and find the `.app` package within. From its Finder context menu, choose "Show Package Contents" to see a file called `embedded.mobileprovision` that you can examine with the above method. [provisioning]: https://github.com/chockenberry/Provisioning ### Uploading [App Store Connect][appstore-connect] is Apple's portal for managing your apps on the App Store. To upload a build, Xcode requires an Apple ID that is part of the developer account used for signing. Nowadays Apple has allowed for single Apple IDs to be part of multiple App Store Connect accounts (i.e. client organizations) in both Apple's developer portal as well as App Store Connect. After uploading the build, be patient as it can take up to an hour for it to show up under the Builds section of your app version. When it appears, you can link it to the app version and submit your app for review. [appstore-connect]: https://appstoreconnect.apple.com ## In-App Purchases (IAP) When validating in-app purchase receipts, remember to perform the following checks: - __Authenticity:__ That the receipt comes from Apple - __Integrity:__ That the receipt has not been tampered with - __App match:__ That the app bundle ID in the receipt matches your appโ€™s bundle identifier - __Product match:__ That the product ID in the receipt matches your expected product identifier - __Freshness:__ That you havenโ€™t seen the same receipt ID before. Whenever possible, design your IAP system to store the content for sale server-side, and provide it to the client only in exchange for a valid receipt that passes all of the above checks. This kind of a design thwarts common piracy mechanisms, and โ€” since the validation is performed on the server โ€” allows you to use Appleโ€™s HTTP receipt validation service instead of interpreting the receipt `PKCS #7` / `ASN.1` format yourself. For more information on this topic, check out the [Futurice blog: Validating in-app purchases in your iOS app][futu-blog-iap]. [futu-blog-iap]: http://futurice.com/blog/validating-in-app-purchases-in-your-ios-app ## License [Futurice][futurice] โ€ข Creative Commons Attribution 4.0 International (CC BY 4.0) [futurice]: http://futurice.com/ ## More Ideas - Add list of suggested compiler warnings - Ask IT about automated Jenkins build machine - Add section on Testing - Add "proven don'ts" [reactivecocoa-github]: https://github.com/ReactiveCocoa/ReactiveCocoa
198
A library of fragment shaders you can use in any SpriteKit project.
<p align="center"> <img src="https://www.hackingwithswift.com/files/shaderkit/shaderkit-logo.png" alt="ShaderKit logo" width="271" height="272" /> </p> <p align="center"> <img src="https://img.shields.io/badge/iOS-10.0+-blue.svg" /> <img src="https://img.shields.io/badge/macOS-10.12+-brightgreen.svg" /> <img src="https://img.shields.io/badge/GLSL-2.0-orange.svg" /> <img src="https://img.shields.io/badge/Swift-5.0-ff69b4.svg" /> <a href="https://twitter.com/twostraws"> <img src="https://img.shields.io/badge/[email protected]?style=flat" alt="Twitter: @twostraws" /> </a> </p> ShaderKit is an open-source collection of fragment shaders designed for use in SpriteKit games. The shaders are designed to be easy to read and understand, even for relative beginners, so youโ€™ll find each line of code is rephrased in plain English as well as an overall explanation of the algorithm used at the top of each file. If youโ€™re already comfortable with shaders then please download one or more that interest you and get going. If not, most of the the remainder of this README acts as a primer for using shaders in SpriteKit. ## See it in action [![Show a video of the shaders in action](https://www.hackingwithswift.com/files/shaderkit/shaderkit-play.png)](https://www.hackingwithswift.com/files/shaderkit/shaderkit-example.mp4) ## TL;DR If you use SpriteKit, you can add special effects from ShaderKit to add water ripples, spinning black holes, flashing lights, embossing, noise, gradients, and more โ€“ย all done on the GPU for maximum speed. ## Credits ShaderKit was made by [Paul Hudson](https://twitter.com/twostraws), who writes [free Swift tutorials over at Hacking with Swift](https://www.hackingwithswift.com). Itโ€™s available under the MIT license, which permits commercial use, modification, distribution, and private use. ## What are shaders? Fragment shaders are tiny programs that operate on individual elements of a spriteโ€™s texture. They are sometimes called โ€œpixel shadersโ€ โ€“ย itโ€™s not a wholly accurate name, but it does make them easier to understand. Effectively, a fragment shader gets run on every pixel in a texture, and can transform that pixel however it wants. That might sound slow, but it isnโ€™t โ€“ย all the fragment shaders here run at 60fps on iPhone 6 and newer, and 120fps on iPad Pro. The transformation process can recolor the pixel however it wants. Users can customize the process by passing fixed values in to the shader (known as โ€œuniformsโ€) and by assigning values to nodes that use the shader (known as โ€œattributesโ€). SpriteKit also provides a few built-in values for us to work with, such as the texture co-ordinate for the pixel being modified and the current time. ## How are they written? Shaders are written in OpenGL ES 2.0 shading language (GLSL), which is a simple, fast, and extremely efficient C-like language that is optimized for high-performance GPU operations. When you activate a shader in your app, it gets loaded and compiled at runtime, and in doing so should be optimized for whatever device the user has. In each shader youโ€™ll find a `main()` function, which is run when the shader activates. This must at some point assign a value to the pre-defined variable `gl_FragColor`, which represents the final color that will be used to draw the pixel. GLSL comes with a wide variety of built-in data types and functions, many of which operate on more than one data types. The data types are nice and simple: - `bool`: a boolean, i.e. true or false. - `float`: a floating-point number. GLSL lets you request various precisions, but this isnโ€™t used in ShaderKit. `float` numbers must be written using a decimal place โ€“ย 1 is considered an integer, whereas `1.` or `1.0` will be considered a `float`. - `vec2`: a two-component floating-point array. Itโ€™s used to hold things like X and Y co-ordinates or width and height. - `vec3`: a three-component floating-point array. Itโ€™s used to hold things like RGB values. - `vec4`: a four-component floating-point array. Itโ€™s used to hold things like RGBA values. - `void` is used to mark the `main()` function as not returning a value. Shaders commonly move fluidly between `float`, `vec2`, `vec3`, and `vec4` as needed. For example, if you create a `vec4` from a `float` then the number will just get repeated for each component in the vector. Youโ€™ll also frequently see code to create a `vec4` by using a `vec3` for the first three values (usually RGB) and specifying a fourth value as a `float`. Here are the functions used in ShaderKit: - `cos()` calculates the cosine of a value in radians. The cosine will always fall between -1 and 1. If you provide `cos()` with a vector (e.g. `vec3`) it will calculate the cosine of each component in the vector and return a vector of the same size containing the results. - `distance()` calculates the distance between two values. For example, if you provide it with a pair `vec2` youโ€™ll get the length of the vector created by subtracting one from the other. This always returns a single number no matter what data type you give it. - `dot()` calculates the dot product of two values. This means multiplying each component of the first value by the respective component in the second value, then adding the result. - `floor()` rounds a number down to its nearest integer. If you pass it a vector this will be done for each component. - `fract()` returns the fractional component of a value. For example, `fract(12.5)` is 0.5. If you pass this a vector then the operation will be performed component-wise, and a new vector will be returning containing the results. - `min()` is used to find the lower of two values. If you pass vectors this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the lowest in the resulting vector. - `max()` is used to find the higher of two values. If you pass vectors this is done component-wise, meaning that the resulting vector will evaluate each component in the vector and place the highest in the resulting vector. - `mix()` smooth interpolates between two values based on a third value thatโ€™s specified between 0 and 1, providing a linear curve. - `mod()` is the modulus function, and calculates remainder after integer division. For example, 10 divides into 3 a total of three times, with remainder 1, so 10 modulo 3 is 1. - `pow()` calculates one value raised to the power of another, for example `pow(2.0, 3.0)` evaluates to 2.0 * 2.0 * 2.0, giving 8.0. As well as operating on a `float`, `pow()` can also calculate component-wise exponents โ€“ย it raises the first item in the first vector to the power of the first item in the second vector, and so on. - `sin()` calculates the sine of a value in radians. The sine will always fall between -1 and 1. If you provide `sin()` with a vector (e.g. `vec3`) it will calculate the sine of each component in the vector and return a vector of the same size containing the results. - `smoothstep()` interpolates between two values based on a third value thatโ€™s specified between 0 and 1, providing an S-curve shape. That is, the interpolation starts slow (values near 0.0), picks up speed (values near 0.5), then slows down towards the end (values near 1.0). - `texture2D()` provides the color value of a texture at a specific location. This is most commonly used to read the current pixelโ€™s color. (Technically this reads *texels*, but itโ€™s easier to think about pixels while youโ€™re learning.) There is one further special function worth mentioning, which is `SKDefaultShading()`. This provides the default color SpriteKit was planning to render for the current fragment. ## Attributes and uniforms Many shaders can operate without any special input from the user โ€“ย it can manipulate the color data it was sent by SpriteKit, then send back new data. However, often youโ€™ll want to customize the way shaders work, a bit like passing in parameters to a function. Shaders are a little more complicated because these values need to be uploaded to the GPU, but the principle is the same. ShaderKit uses two approaches for customizing shader behavior: uniforms and attributes. They are very similar, but the difference is that uniforms are attached to shaders and attributes are attached to nodes. Almost everything is declared as a uniform in ShaderKit. So, if you want to customize the colors for your gradient, the strength of your water rippling, or the size of your interlacing lines, these are all specified as uniforms. However, one thing is consistently specified as an attribute, which is *node size*. Some shaders (see below) require the size of the node they are operating on, and although this *could* be specified as a uniform it would stop you from using the same shader on multiple nodes. So, instead itโ€™s specified as an attribute: each sprite tells the shader how big it is, and that value combines with the uniforms inside the shader to produce the final result. By convention, uniform names start with โ€œuโ€ and attribute names start with โ€œaโ€. So, when you see โ€œu_strengthโ€ you know itโ€™s a uniform, and when you see โ€œa_sizeโ€ you know itโ€™s an attribute. **Please note note:** there is a performance cost to uploading uniform and attribute data to the GPU. As a result, you should only specify values that are actually used inside the shader. This repository also contains ShaderKitExtensions.swift. This adds a handful of convenience initializers for setting uniforms and attributes from common types: `CGSize`, `CGPoint`, and `SKColor`. (NB: `SKColor` is either `UIColor` or `NSColor` depending on whether youโ€™re using iOS/tvOS/watchOS or macOS.) Although these extensions arenโ€™t required, they will make it significantly easier to use the shaders provided here โ€“ย you should add ShaderKitExtensions.swift to your own project alongside whichever shaders you want. One of these extensions adds a new initializer for `SKShader` that loads a shader file into a string then creates an `SKShader` from that string, and assigns any uniforms or attribute settings. This is helpful while debugging, because shaders loaded from strings get debug information printed inside Xcode, so if you modify a shader incorrectly Xcode will help you understand the problem. **All Swift code examples below use this initializer.** As stated above, the only attribute you need to specify in any of the ShaderKit shaders is the spriteโ€™s size. This is only required in some shaders (see below), and with ShaderKitExtension.swift is done like this: ```swift yourSprite.setValue(SKAttributeValue(size: yourSprite.size), forAttribute: "a_size") ``` ## Built-in values SpriteKit provides several built-in values that are useful when building shaders: - `u_texture`: the texture that is being rendered. You can read individual color values from this. - `u_time`: how much time has elapsed in the game. - `v_tex_coord`: the position of the current pixel in the texture. These are normalized to the bottom-left corner, meaning that (0.0, 0.0) is the bottom-left corner and (1.0, 1.0) is the top-right corner. - `v_color_mix`: the color of the node being rendered. ## Reading the shaders All the shaders in ShaderKit were specifically written for readability. Specifically, they: 1. All start with a brief comment outlining what each shader does. 2. List all input attributes and uniforms (where they are used), along with ranges and a suggested starting point. 3. An explanation of the algorithm used. 4. Detailed line-by-line English translations of what the code means. The combination of what the code *does* (the interlinear comments) and what the code *means* (the algorithm introduction) should hopefully make these shaders comprehensible to everyone. One small note: you will commonly see the final fragment color multiplied both by the original colorโ€™s alpha and the alpha value of `v_color_mix`. The former ensures the new color takes into account the alpha value of the original, which keeps edges smooth; the latter ensures the new color takes into account the alpha of the whole node, so that it can be faded in or out smoothly. ## Shaders included in ShaderKit ShaderKit provides a selection of shaders, most of which allow some customization using uniforms. Some shaders are merely variations of others, provided separately to avoid too much of a performance hit. ### Checkerboard Renders a checkerboard with user-defined row/column count and colors. **Parameters:** - Uniform: `u_rows`, how many rows to generate. Should be at least 1. - Uniform: `u_cols`, how many columns to generate. Should be at least 1. - Uniform: `u_first_color`, an `SKColor` to use for half of the squares. - Uniform: `u_second_color`, an `SKColor` to use for the other half of the squares. Example code: ```swift func createCheckerboard() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_rows", float: 12), SKUniform(name: "u_cols", float: 12), SKUniform(name: "u_first_color", color: .white), SKUniform(name: "u_second_color", color: .black), ] return SKShader(fromFile: "SHKCheckerboard", uniforms: uniforms) } ``` ### Circle Wave Renders a circular pulsating wave effect. This comes in four variants: 1. Circle Wave generates a fixed-color wave while ignoring existing pixel colors. 2. Circle Wave (Blended) generates a fixed-color wave while blending with existing pixel colors. 3. Circle Wave Rainbow generates a fluctuating-color wave while ignoring existing pixel colors. 4. Circle Wave Rainbow (Blended) generates a fluctuating-color wave while blending with existing pixel colors. **Parameters for Circle Wave and Circle Wave Blended:** - Uniform: `u_speed`, how fast the wave should travel. Ranges from -2 to 2 work best, where negative numbers cause waves to come inwards; try starting with 1. - Uniform: `u_brightness`, how bright the colors should be. Ranges from 0 to 5 work best; try starting with 0.5 and experiment. - Uniform: `u_strength`, how intense the waves should be. Ranges from 0.02 to 5 work best; try starting with 2. - Uniform: `u_density`, how large each wave should be. Ranges from 20 to 500 work best; try starting with 100. - Uniform: `u_center`, a `CGPoint` representing the center of the gradient, where 0.5/0.5 is dead center - Uniform: `u_color`, the SKColor to use. Use darker colors to create a less intense core. **Parameters for Circle Wave Rainbow and Circle Wave Rainbow Blended:** - Uniform: `u_speed`, how fast the wave should travel. Ranges from -2 to 2 work best, where negative numbers cause waves to come inwards; try starting with 1. - Uniform: `u_brightness`, how bright the colors should be. Ranges from 0 to 5 work best; try starting with 0.5 and experiment. - Uniform: `u_strength`, how intense the waves should be. Ranges from 0.02 to 5 work best; try starting with 2. - Uniform: `u_density`, how large each wave should be. Ranges from 20 to 500 work best; try starting with 100. - Uniform: `u_center`, a `CGPoint` representing the center of the gradient, where 0.5/0.5 is dead center - Uniform: `u_red`, how much red to apply to the colors. Specify 0 to 1 to apply that amount of red, or use any negative number (e.g. -1) to have the amount of red fluctuate. Example code: ```swift func createCircleWave() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_speed", float: 1), SKUniform(name: "u_brightness", float: 0.5), SKUniform(name: "u_strength", float: 2), SKUniform(name: "u_density", float: 100), SKUniform(name: "u_center", point: CGPoint(x: 0.68, y: 0.33)), SKUniform(name: "u_color", color: UIColor(red: 0, green: 0.5, blue: 0, alpha: 1)) ] return SKShader(fromFile: "SHKCircleWave", uniforms: uniforms) } func createCircleWaveRainbowBlended() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_speed", float: 1), SKUniform(name: "u_brightness", float: 0.5), SKUniform(name: "u_strength", float: 2), SKUniform(name: "u_density", float: 100), SKUniform(name: "u_center", point: CGPoint(x: 0.68, y: 0.33)), SKUniform(name: "u_red", float: -1) ] return SKShader(fromFile: "SHKCircleWaveRainbowBlended", uniforms: uniforms) } ``` ### Color Alpha Colors all clear pixels in the node. **Parameters:** - Uniform: `u_color`, the `SKColor` to use. Example code: ```swift func createColorAlpha() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_color", color: .green) ] return SKShader(fromFile: "SHKColorAlpha", uniforms: uniforms) } ``` ### Color Non-Alpha Colors all clear pixels in the node. **Parameters:** - Uniform: u_color, the SKColor to use. Example code: ```swift func createColorNonAlpha() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_color", color: .yellow) ] return SKShader(fromFile: "SHKColorNonAlpha", uniforms: uniforms) } ``` ### Color Invert Inverts all colors in a node while retaining transparency. **Parameters:** - None. Example code: ```swift func createColorInvert() -> SKShader { return SKShader(fromFile: "SHKColorInvert") } ``` ### Colorize Recolors a texture to a user color based on a strength value. **Parameters:** - Uniform: `u_color`, the `SKColor` to use. This is multiplied with the original, meaning that blacks remain black. - Uniform: `u_strength`, how much of the replacement color to apply. Specify a value between 0 (use original color) and 1 (use replacement color fully). Example code: ```swift func createColorize() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_color", color: .green), SKUniform(name: "u_strength", float: 1) ] return SKShader(fromFile: "SHKColorize", uniforms: uniforms) } ``` ### Desaturate Desaturates the colors in a texture. **Parameters:** - Uniform: `u_strength`, the amount to desaturate. Specify 0 (no desaturation) to 1 (full desaturation). Example code: ```swift func createDesaturate() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_strength", float: 0.5), ] return SKShader(fromFile: "SHKDesaturate", uniforms: uniforms) } ``` ### Emboss Creates a 3D embossing effect. This comes in two variants: - Emboss Color retains the original color values while adding 3D highlights and shadows. - Emboss Gray uses a middle gray (RGB: 0.5) then adds 3D highlights and shadows on top. **Parameters:** - Attribute: `a_size`, the size of the node. - Uniform: `u_strength`, how much embossing to apply (ranges from 0 to 1 work best) Example code: ```swift func createColorEmboss() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_strength", float: 1) ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKEmbossColor", uniforms: uniforms, attributes: attributes) } func createGrayEmboss() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_strength", float: 1) ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKEmbossGray", uniforms: uniforms, attributes: attributes) } ``` ### Infrared Simulates an infrared camera by coloring brighter objects red and darker objects blue. **Parameters:** - None. Example code: ```swift func createInfrared() -> SKShader { return SKShader(fromFile: "SHKInfrared") } ``` ### Interlace Applies an interlacing effect where horizontal lines of original color are separated by lines of another color. **Parameters:** - Attribute: `a_size`, the size of the node. - Uniform: `u_width`, the width of the interlacing lines. Ranges of 1 to 4 work best; try starting with 1. - Uniform: `u_color`, the `SKColor` to use for interlacing lines. Try starting with black. - Uniform: `u_strength`, how much to blend interlaced lines with `u_color`. Specify 0 (not at all) up to 1 (fully). Example code: ```swift func createInterlace() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_width", float: 2), SKUniform(name: "u_color", color: .black), SKUniform(name: "u_strength", float: 0.35), ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKInterlace", uniforms: uniforms, attributes: attributes) } ``` ### Light grid Creates a grid of multi-colored flashing lights. **Parameters:** - Uniform: `u_density`, how many rows and columns to create. A range of 1 to 50 works well; try starting with 8. - Uniform: `u_speed`, how fast to make the lights vary their color. Higher values cause lights to flash faster and vary in color more. A range of 1 to 20 works well; try starting with 3. - Uniform: `u_group_size`, how many lights to place in each group. A range of 1 to 8 works well depending on your density; starting with 1. - Uniform: `u_brightness`, how bright to make the lights. A range of 0.2 to 10 works well; try starting with 3. Example code: ```swift func createLightGrid() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_density", float: 8), SKUniform(name: "u_speed", float: 3), SKUniform(name: "u_group_size", float: 2), SKUniform(name: "u_brightness", float: 3), ] return SKShader(fromFile: "SHKLightGrid", uniforms: uniforms) } ``` ### Linear gradient Creates a linear gradient over the node. Either the start or the end color can be translucent to let original pixel colors come through. **Parameters:** - Uniform: `u_first_color`, the `SKColor` to use at the top of the gradient - Uniform: `u_second_color`, the `SKColor` to use at the bottom of the gradient Example code: ```swift func createLinearGradient() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_first_color", color: .blue), SKUniform(name: "u_second_color", color: .clear) ] return SKShader(fromFile: "SHKLinearGradient", uniforms: uniforms) } ``` ### Noise Generates random pixels of different colors to simulate noise. This comes in four variants: 1. Static Gray Noise generates grayscale noise that doesnโ€™t move. 2. Static Rainbow Noise generates multicolor noise that doesnโ€™t move. 3. Dynamic Gray Noise generates grayscale noise that is constantly changing. 4. Dynamic Rainbow Noise generates multicolor noise that is constantly changing. **Parameters:** - None. Example code: ```swift func createStaticGrayNoise() -> SKShader { return SKShader(fromFile: "SHKStaticGrayNoise") } func createDynamicRainbowNoise() -> SKShader { return SKShader(fromFile: "SHKDynamicRainbowNoise") } ``` ### Pixelate Pixelates an image based on a strength provided by the user. **Parameters:** - Attribute: `a_size`, the size of the node. - Uniform: `u_strength`, how large each pixel block should be. Ranges from 2 to 50 work best; try starting with 5. Example code: ```swift func createPixelate() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_strength", float: 8), ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKPixelate", uniforms: uniforms, attributes: attributes) } ``` ### Radial gradient Creates a radial gradient over the node. Either the start or the end color can be translucent to let original pixel colors come through. **Parameters:** - Uniform: `u_first_color`, the SKColor to use at the center of the gradient - Uniform: `u_second_color`, the SKColor to use at the edge of the gradient - Uniform: `u_center`, a `CGPoint` representing the center of the gradient, where 0.5/0.5 is dead center. Example code: ```swift func createRadialGradient() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_first_color", color: .blue), SKUniform(name: "u_second_color", color: .clear), SKUniform(name: "u_center", point: CGPoint(x: 0.75, y: 0.25)) ] return SKShader(fromFile: "SHKRadialGradient", uniforms: uniforms) } ``` ### Scanlines Applies scanlines and pixelation to the node, giving a retro television effect. **Parameters:** - Uniform: `u_width`, vertical width of scanlines and width of pixelation. - Uniform: `u_brightness`, brightness of scanlines, between 0 and 1.0. Higher values introduce overexposure. - Uniform: `u_color`, blend color of scanlines. Example code: ```swift func createScanlines() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_width", float: 4.0), SKUniform(name: "u_brightness", float: 0.75), SKUniform(name: "u_color", color: .white), ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKScanlines", uniforms: uniforms, attributes: attributes) } ``` ### Screen Applies an interlacing effect where horizontal and vertical lines of original color are separated by lines of another color **Parameters:** - Attribute: `a_size`, the size of the node. - Uniform: `u_width`, the width of the interlacing lines. Ranges from 2 upwards work well. - Uniform: `u_color`, the `SKColor` to use for interlacing lines. Try starting with black. - Uniform: `u_strength`, how much to blend interlaced lines with `u_color`. Specify 0 (not at all) up to 1 (fully). Example code: ```swift func createScreen() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_width", float: 2), SKUniform(name: "u_color", color: .clear), SKUniform(name: "u_strength", float: 1), ] let attributes = [ SKAttribute(name: "a_size", type: .vectorFloat2) ] return SKShader(fromFile: "SHKScreen", uniforms: uniforms, attributes: attributes) } ``` ### Water Warps a textured node to create a water rippling effect. Note: this must be applied to something that has a texture. **Parameters:** - Uniform: `u_speed`, how many fast to make the water ripple. Ranges from 0.5 to 10 work best; try starting with 3. - Uniform: `u_strength`, how pronounced the rippling effect should be. Ranges from 1 to 5 work best; try starting with 3. - Uniform: `u_frequency`, how often ripples should be created. Ranges from 5 to 25 work best; try starting with 10. Example code: ```swift func createWater() -> SKShader { let uniforms: [SKUniform] = [ SKUniform(name: "u_speed", float: 3), SKUniform(name: "u_strength", float: 2.5), SKUniform(name: "u_frequency", float: 10) ] return SKShader(fromFile: "SHKWater", uniforms: uniforms) } ``` ## ShaderKit Sandbox Inside this repository are example SpriteKit projects for iOS and macOS that demonstrate each of the shaders with some example values โ€“ try running them if youโ€™re curious how each of the shaders look or perform on your device. If youโ€™ve modified one of the shaders and want to see how it looks, the sandbox is the best place. If you tap or click the screen the test nodes will alternate between alpha 0 and alpha 1 so you can make sure your modifications blend correctly. The iOS sandbox has been tested on iPhone 6, 6s, 7, and X, as well as iPad Pro. The macOS sandbox has been tested on a retina MacBook Pro using macOS 10.13. Note: although each of these filters could be ported to any shader-supporting platform with little work, Iโ€™ve tested them specifically on iOS/macOS and SpriteKit. ## Contributing I made ShaderKit because not enough people know that shaders are powerful, easy ways to add special effects to your games. If youโ€™d like to contribute your own shaders or modifications to existing shaders, thatโ€™s great! But first please read the following: - ShaderKit has a strong emphasis on readability. Beginners should be able to read most of these shaders and have a good idea of how they work. If you want to make one of the shaders faster, please donโ€™t do so at the expensive of readability. - You must comment your code thoroughly. Shaders are often extremely terse, so please write in English above every line what the code does โ€“ย a transliteration, if you will โ€“ย and also provide a description of how it all works to produce the final result. - All code must be licensed under the MIT license so it can benefit the most people. ## License MIT License. Copyright (c) 2017 Paul Hudson 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.
199
Swift + Redux + (Combine|RxSwift|ReactiveSwift) -> SwiftRex
<p align="center"> <a href="https://github.com/SwiftRex/SwiftRex/"><img src="https://swiftrex.github.io/SwiftRex/markdown/img/SwiftRexBanner.png" alt="SwiftRex" /></a><br /><br /> Unidirectional Dataflow for your favourite reactive framework<br /><br /> </p> ![Build Status](https://github.com/SwiftRex/SwiftRex/actions/workflows/swift.yml/badge.svg?branch=develop) [![codecov](https://codecov.io/gh/SwiftRex/SwiftRex/branch/develop/graph/badge.svg)](https://codecov.io/gh/SwiftRex/SwiftRex) [![Jazzy Documentation](https://swiftrex.github.io/SwiftRex/api/badge.svg)](https://swiftrex.github.io/SwiftRex/api/index.html) [![CocoaPods compatible](https://img.shields.io/cocoapods/v/SwiftRex.svg)](https://cocoapods.org/pods/SwiftRex) [![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-orange.svg)](https://swiftpackageindex.com/SwiftRex/SwiftRex) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2FSwiftRex%2FSwiftRex%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/SwiftRex/SwiftRex) [![Platform support](https://img.shields.io/badge/platform-iOS%20%7C%20watchOS%20%7C%20tvOS%20%7C%20macOS%20%7C%20Catalyst-252532.svg)](https://github.com/SwiftRex/SwiftRex) [![License Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/SwiftRex/SwiftRex/blob/master/LICENSE) If you've got questions, about SwiftRex or redux and Functional Programming in general, please [Join our Slack Channel](https://join.slack.com/t/swiftrex/shared_invite/zt-oko9h1z4-Nq4YsK2FbMJ~giN01sdDeQ). # Introduction SwiftRex is a framework that combines Unidirectional Dataflow architecture and reactive programming ([Combine](https://developer.apple.com/documentation/combine), [RxSwift](https://github.com/ReactiveX/RxSwift) or [ReactiveSwift](https://github.com/ReactiveCocoa/ReactiveSwift)), providing a central state Store for the whole state of your app, of which your SwiftUI Views or UIViewControllers can observe and react to, as well as dispatching events coming from the user interactions. This pattern, also known as ["Redux"](https://redux.js.org/basics/data-flow), allows us to rethink our app as a single [pure function](https://en.wikipedia.org/wiki/Pure_function) that receives user events as input and returns UI changes in response. The benefits of this workflow will hopefully become clear soon. [API documentation can be found here](https://swiftrex.github.io/SwiftRex/api/index.html). # Quick Guide In a hurry? Already familiar with other redux implementations? No problem, we have a [TL;DR Quick Guide](docs/markdown/QuickGuide.md) that shows the minimum you need to know about SwiftRex in a very practical approach. We still recommend reading the full README for a deeper understanding behind SwiftRex concepts. # Goals Several architectures and design patterns for mobile development nowadays propose to solve specific issues related to [Single Responsibility Principle](https://www.youtube.com/watch?v=Gt0M_OHKhQE) (such as Massive ViewControllers), or improve testability and dependency management. Other common challenges for mobile developers such as state handling, race conditions, modularization/componentization, thread-safety or dealing properly with UI life-cycle and ownership are less explored but can be equally harmful for an app. Managing all of these problems may sound like an impossible task that would require lots of patterns and really complex test scenarios. After all, how to to reproduce a rare but critical error that happens only with some of your users but never in developers' equipment? This can be frustrating and most of us has probably faced such problems from time to time. That's the scenario where SwiftRex shines, because it: <details> <summary>enforces the application of Single Responsibility Principle [tap to expand]</summary> <p>Some architectures are very flexible and allow us to add any piece of code anywhere. This should be fine for most small apps developed by only one person, but once the project and the team start to grow, some layers will get really large, holding too much responsibility, implicit side-effects, race conditions and other bugs. In this scenario, testability is also damaged, as is consistency between different parts of the app, so finding and fixing bugs becomes really tricky.</p> <p>SwiftRex prevents that by having a very strict policy of where the code should be and how limited that layer is, policy that is often enforced by the compiler. Well, this sounds hard and complicated, but in fact it's easier than traditional patterns, because once you understand this architecture you know exactly what to do, you know exactly where to find some line of code based on its responsibility, you know exactly how to test each component and you understand very well what are the boundaries of each layer.</p> </details> <details> <summary>offers a clear test strategy for each layer (<a href="https://github.com/SwiftRex/TestingExtensions">also check TestingExtensions</a>) [tap to expand]</summary> <p>We believe that an architecture must not only be very testable, but also offer a clear guideline of how to test each of its layers. If a layer has only one job, and this job can be verified by assertions of expected outputs based on given input all the times, the tests can be more meaningful and broad, so no regressions are introduced when a new feature is created.</p> <p>Most layers in SwiftRex architecture will be pure functions, that means all its computation is done solely from the input parameters, and all its results will be exposed on the output, no implicit effect or access to global scope. Testing that won't require mocks, stubs, dependency injection or any kind of preparation, you call a function with a value, you check the result and that's it.</p> <p>This is true for the UI Layer, presentation layer, reducers and state publishers, because this whole chain is a composition of pure functions. The only layer that needs dependency injection, therefore mocks, is the middleware, once it's the only layer that depends on services and triggers side-effects to the outside world. Luckily because middlewares are composable, we can break them into very small pieces that do only one job, and testing that becomes more pleasant and easy, because instead of mocking hundreds of components you only have to inject one.</p> <p>We also offer <a href="https://github.com/SwiftRex/TestingExtensions">TestingExtensions</a> that allows us to test the whole use case using a DSL syntax that will validate all SwiftRex layers, ensuring that no unexpected side-effect or action happened, and the state was mutated step-by-step as expected. This is a powerful and fun way to test the whole app with few and easy-to-write lines.</p> </details> <details> <summary>isolates all the side-effects in composable/reusable middleware boxes that can't mutate the state [tap to expand]</summary> <p>If a layer has to handle multiple services at the same time and mutate the state as they asynchronously respond, it's hard to keep this state consistent and prevent race conditions. It's also harder to test because one effect can interfere in the other.</p> <p>Along the years, both Apple and the community created amazing frameworks to access services in the web or network and sensors in the device. Unfortunately some of these frameworks rely on delegate pattern, some use closures/callbacks, some use Notification Center, KVO or reactive streams. Composing this mixture of notification forms will require boolean flags, counters, and other implicit state that will eventually break due to race conditions.</p> <p>Reactive frameworks help to make this more uniform and composable, especially when used together with their Cocoa extensions, and in fact even Apple realised that and a significant part of <a href="https://developer.apple.com/videos/play/wwdc2019/226/">WWDC 2019</a> was focused on demonstrating and fixing this problem, with the help of newly introduced frameworks Combine and SwiftUI.</p> <p>But composing lots of services in reactive pipelines is not always easy and has its own pitfalls, like full pipeline cancellation because one stream emitted an error, event reentrancy and, last but not least, steep learning curve on mastering the several operators.</p> <p>SwiftRex uses reactive-programming a lot, and allows you to use it as much as you feel comfortable. However we also offer a more uniform way to compose different services with only 1 data type and 2 operators: middleware, `<>` operator and `lift` operator, all the other operations can be simplified by triggering actions to itself, other middlewares or state reducers. You still have the option to create a larger middleware and handle multiple sources in a traditional reactive-stream fashion, if you like, but this can be overwhelming for un-experienced developers, harder to test and harder to reuse in different apps.</p> <p>Because this topic is very wide it's going to be better explained in the Middleware documentation.</p> </details> <details> <summary>minimizes the usage of dependencies on ViewControllers/Presenters/Interactors/SwiftUI Views [tap to expand]</summary> <p>Passing dependencies as you browse your app was never an easy task: ViewControllers initialisers are very tricky, you must always consider when the class is being created from NIB/XIB, programmatically or storyboards, then write the correct init method passing not only all the dependencies this class needs, but also the dependencies needed by its child view controllers and the next view controller that will be pushed when you press a button, so you have to keep sending dozens of dependencies across your views while routing through them. If initialisers are not used but property assignment is preferred, these properties have to be implicit unwrapped, which is not great.</p> <p>Surely coordinator/wireframe patterns help on that, but somehow you transfer the problems to the routers, that also need to keep asking more dependencies that they actually use, but because the next router will use. You can use a service locator pattern, such as the popular <a href="https://vimeo.com/291588126">Environment</a> approach, and this is really an easy way to handle the problem. Testing this singleton, however, can be tricky, because, well, it's a singleton. Also some people don't like the implicit injection and feel more comfortable adding the explicit dependencies a layer needs.</p> <p>So it's impossible to solve this and make everybody happy, right? Well, not really. What if your view controllers only need a single dependency called "Store", from where it gets the state it needs and to where it dispatches all user events without actually executing any work? In this case, injecting the store is much easier regardless if you use explicit injection or service locator.</p> <p>Ok, but someone still has to do the work, and this is precisely the job that middlewares execute. In SwiftRex, middlewares should be created in entry-point of an app, right after the dependencies are configured and ready. Then you create all middlewares, injecting whatever they need to perform their work (hopefully not more than 2 dependencies per middleware, so you know they are not holding too many responsibilities). Finally you compose them and start your store. Middlewares can have timers or purely react to actions coming from the UI, but they are the only layer that has side-effects, therefore the only layer that needs services dependencies.</p> <p>Finally, you can add locale, language and interface traits into your global state, so even if you need to create number and date formatters in your state you still can do it without dependency injection, and even better, react properly when the user decides to change an iOS setting.</p> </details> <details> <summary>detaches state, services, mutation and other side-effects completely from the UI life-cycle and its ownership tree [tap to expand]</summary> <p>UIViewControllers have a very peculiar ownership model: you don't control it. The view controllers are kept in memory while they are in the navigation stack, or if a tab is presented, or while a modal view is shown, but they can be released at any point, and with it, anything you put the ownership under view controller umbrella. All those [weak self] we've been using and loving can actually be weak sometimes, and it's very easy to not reason about that when we "guard that else return". Any important task that MUST be completed, regardless of your view being shown or not, should not be under the view controller life-cycle, as the user can easily dismiss your modal or pop your view. SwiftUI that has improved that but it's still possible to start async tasks from views' closures, and although now that view is a value-type it's a bit harder to make those mistakes, it's still possible.</p> <p>SwiftRex solves this problem by enforcing that all and every side-effect or async task should be done by the middleware, not the views. And middleware life-cycle is owned by the store, so we shouldn't expect any unfortunate surprise as long as the store lives while the app lives.</p> <p>You still can dispatch "viewDidLoad", "onAppear", "onDisappear" events from your views, in order to perform task cancellations, so you gain more control, not less.</> <p>For more information <a href="docs/markdown/UIKitLifetimeManagement.md">please check this link</a></p> </details> <details> <summary>eliminates race conditions [tap to expand]</summary> <p>When an app has to deal with information coming from different services and sources it's common the need for small boolean flags here and there to check when something has completed or failed. Usually this is due to the fact that some services report back via delegates, some via closures, and several other creative ways. Synchronising these multiple sources by using flags, or mutating the same variables or array from concurrent tasks can lead to really strange bugs and crashes, usually the most difficult sort of bugs to catch, understand and fix.</p> <p>Dealing with locks and dispatch queues can help on that, but doing this over and over again in a ad-hoc manner is tedious and dangerous, tests must be written that consider all possible paths and timings, and some of these tests will eventually become flaky in case the race condition still exists.</p> <p>By enforcing all events of the app to go through the same queue which, by the end, mutates uniformly the global state in a consistent manner, SwiftRex will prevent race conditions. First because having middlewares as the only source of side-effects and async tasks will simplify testing for race conditions, especially if you keep them small and focused on a single task. In that case, your responses will come in a queue following a FIFO order and will be handled by all the reducers at once. Second because the reducers are the gatekeepers for state mutation, keeping them free of side-effects is crucial to have a successful and consistent mutation. Last but not least, everything happens in response to actions, and actions can be easily logged in or put in your crash reports, including who dispatched that action, so if you still find a race condition happening you can easily understand what actions are mutating the state and where these actions come from.</p> </details> <details> <summary>allows a more type-safe coding style [tap to expand]</summary> <p>Swift generics are a bit hard to learn, and also are protocols associated types. SwiftRex doesn't require that you master generics, understand covariance or type-erasure, but more you dive into this world certainly you will write apps that are validated by the compiler and not by unit-tests. Bringing bugs from the runtime to the compile time is a very important goal that we all should embrace as good developers. It's probably better to struggle Swift type system than checking crash-reports after your app was released to the wild. This is exactly the mindset Swift brought as a static-typed language, a language where even nullability is type-safe, and thanks to Optional<Wrapped> we can now rest peacefully knowing that we won't access null pointers unless we unsafely - and explicitly - choose that.</p> <p>SwiftRex enforces the use of strongly-typed events/actions and state everywhere: store's action dispatcher, middleware's action handler, middleware's action output, reducer's actions and states inputs and outputs and finally store's state observation, the whole flow is strongly-typed so the compiler can prevent mistakes or runtime bugs.</p> <p>Furthermore, Middlewares, Reducers and Store all can be "lifted" from a partial state and action to a global state and action. What does that mean? It means that you can write a strongly-typed module that operates in an specific domain, like network reachability. Your middleware and reducer will "speak" network domain state and actions, things like it's connected or not, it's wi-fi or LTE, did change connectivity action, etc. Then you can "lift" these two components - middleware and reducer - to a global state of your app, by providing two map functions: one for lifting the state and the other for lifting the action. Thanks to generics, this whole operation is completely type-safe. The same can be done by "deriving" a store projection from the main store. A store projection implements the two methods that a Store must have (input action and output state), but instead of being a real store it only projects the global state and actions into more localised domain, that means, view events translated to actions and view state translated to domain state.</p> <p>With these tools we believe you can write, if you want, an app that is type-safe from edge to edge.</p> </details> <details> <summary>helps to achieve modularity, componentization and code reuse between projects [tap to expand]</summary> <p>Middlewares should be focused in a very very small domain, performing only one type of work and reporting back in form of actions. Reducers should be focused in a very tiny combination of action and state. Views should have access to a really tiny portion of the state, or ideally to a view state that is a flat representation of the app global state using primitives that map directly to text field's string, toggle's boolean, progress bar's double from 0.0 to 1.0 and so on and so forth.</p> <p>Then, you can "lift" these three pieces - middleware, reducer, store projection - into the global state and action your app actually needs.</p> <p>SwiftRex allows us to create small units-of-work that can be lifted to a global domain only when needed, so we can have Swift frameworks operating in a very specific domain, and covered with tests and Playgrounds/SwiftUI Previews to be used without having to launch the full app. Once this framework is ready, we just plug in our app, or even better, apps. Focusing on small domains will unlock better abstractions, and when this goes from middlewares (side-effect) to views, you have a powerful tool to define your building blocks.</p> </details> <details> <summary>enforces single source of truth and proper state management [tap to expand]</summary> <p>A trustable single source of truth that will never be inconsistent or out of sync among screens is possible with SwiftRex. It can be scary to think all your state is in a single place, a single tree that holds everything. It can be scary to see how much state you need, once you gather everything in a single place. But worry not, this is nothing that you didn't have before, it was there already, in a ViewController, in a Presenter, in a flag used to control the result of a service, but because it was so spread you didn't see how big it was. And worse, this leads to duplication, because when you need the same information from two different places, it's easier to duplicate and hope that you'll keep them in sync properly.</p> <p>In fact, when you gather your whole app state in a unified tree, you start getting rid of lots of things you don't need any more and your final state will be smaller than the messy one.</p> <p>Writing the global state and the global action tree correctly can be challenging, but this is the app domain and reasoning about that is probably the most important task an engineer has to do.</p> <p>For more information <a href="docs/markdown/StateManagement.md">please check this link</a></p> </details> <details> <summary>offers tooling for development, tests and debugging [tap to expand]</summary> <p>Several projects offer SwiftRex tools to help developers when writing apps, tests, debugging it or evaluating crash reports.</p> <p><a href="https://github.com/SwiftRex/CombineRextensions">CombineRextensions</a> offers SwiftUI extensions to work with CombineRex, <a href="https://github.com/SwiftRex/TestingExtensions">TestingExtensions</a> has "test asserts" that will unlock testability of use cases in a fun and easy way, <a href="https://github.com/SwiftRex/InstrumentationMiddleware">InstrumentationMiddleware</a> allows you to use Instruments to see what's happening in a SwiftRex app, <a href="https://github.com/SwiftRex/SwiftRexMonitor">SwiftRexMonitor</a> will be a Swift version of well-known Redux DevTools where you can remotely monitor state and actions of an app from an external Mac or iOS device, and even inject actions to simulate side-effects (useful for UITests, for example), <a href="https://github.com/SwiftRex/GatedMiddleware">GatedMiddleware</a> is a middleware wrapper that can be used to enable or disable other middlewares in runtime, <a href="https://github.com/SwiftRex/LoggerMiddleware">LoggerMiddleware</a> is a very powerful logger to be used by developers to easily understand what's happening in runtime. More Middlewares will be open-sourced soon allowing, for example, to create good Crashlytics reports that tell the story of a crash as you've never had access before, and that way, recreate crashes or user reports. Also tools for generating code (Sourcery templates, Xcode snippets and templates, console tools), and also higher level APIs such as EffectMiddlewares that allow us to create Middlewares with a single function, as easy as Reducers are, or Handler that will allow to group Middlewares and Reducers under a same structure to be able to lift both together. New dependency injection strategies are about to be released as well.</p> <p>All these tools are already done and will be released any time soon, and more are expected for the future.</p> </details> I'm not gonna lie, it's a completely different way of writing apps, as most reactive approaches are; but once you get used to, it makes more sense and enables you to reuse much more code between your projects, gives you better tooling for writing software, testing, debugging, logging and finally thinking about events, state and mutation as you've never done before. And I promise you, it's gonna be a way with no return, an Unidirectional journey. # Reactive Framework Libraries SwiftRex currently supports the 3 major reactive frameworks: - [Apple Combine](https://developer.apple.com/documentation/combine) - [RxSwift](https://github.com/ReactiveX/RxSwift) - [ReactiveSwift](https://github.com/ReactiveCocoa/ReactiveSwift) More can be easily added later by implementing some abstraction bridges that can be found in the `ReactiveWrappers.swift` file. To avoid adding unnecessary files to your app, SwiftRex is split in 4 packages: - SwiftRex: the core library - CombineRex: the implementation for Combine framework - RxSwiftRex: the implementation for RxSwift framework - ReactiveSwiftRex: the implementation for ReactiveSwift framework SwiftRex itself won't be enough, so you have to pick one of the three implementations. # Parts Let's understand the components of SwiftRex by splitting them into 3 sections: - [Conceptual parts](#conceptual-parts) - [Action](#action) - [State](#state) - [Core Parts](#core-parts) - [Store](#store) - [StoreType](#storetype) - [Real Store](#real-store) - [Store Projection](#store-projection) - [All together](#all-together) - [Middleware](#middleware) - [Generics](#generics) - [Returning IO and performing side-effects](#returning-io-and-performing-side-effects) - [Dependency Injection](#dependency-injection) - [Middleware Examples](#middleware-examples) - [EffectMiddleware](#effectmiddleware) - [Reducer](#reducer) - [Projection and Lifting](#projection-and-lifting) - [Store Projection](#store-projection) - [Lifting](#lifting) - [Lifting Reducer](#lifting-reducer) - [Lifting Reducer using closures:](#lifting-reducer-using-closures) - [Lifting Reducer using KeyPath:](#lifting-reducer-using-keypath) - [Lifting Middleware](#lifting-middleware) - [Lifting Middleware using closures:](#lifting-middleware-using-closures) - [Lifting Middleware using KeyPath:](#lifting-middleware-using-keypath) - [Optional transformation](#optional-transformation) - [Direction of the arrows](#direction-of-the-arrows) - [Use of KeyPaths](#use-of-keypaths) - [Identity, Ignore and Absurd](#identity-ignore-and-absurd) - [Xcode Snippets:](#xcode-snippets) --- ## Conceptual Parts - [Action](#action) - [State](#state) --- ### Action An Action represents an event that was notified by external (or sometimes internal) actors of your app. It's about relevant INPUT events. There's no "Action" protocol or type in SwiftRex. However, Action will be found as a generic parameter for most core data structures, meaning that it's up to you to define what is the root Action type. Conceptually, we can say that an Action represents something that happens from external actors of your app, that means user interactions, timer callbacks, responses from web services, callbacks from CoreLocation and other frameworks. Some internal actors also can start actions, however. For example, when UIKit finishes loading your view we could say that `viewDidLoad` is an action, in case we're interested in this event. Same for SwiftUI View (`.onAppear`, `.onDisappear`, `.onTap`) or Gesture (`.onEnded`, `.onChanged`, `.updating`) modifiers, they all can be considered actions. When URLSession replies with a Data that we were able to parse into a struct, this can be a successful action, but when the response is a 404, or JSONDecoder can't understand the payload, this should also become a failure Action. NotificationCenter does nothing else but notifying actions from all over the system, such as keyboard dismissal or device rotation. CoreData and other realtime databases have mechanism to notify when something changed, and this should become an action as well. **Actions are about INPUT events that are relevant for an app.** For representing an action in your app you can use structs, classes or enums, and organize the list of possible actions the way you think it's better. But we have a recommended way that will enable you to fully use type-safety and avoid problems, and this way is by using a tree structure created with enums and associated values. ```swift enum AppAction { case started case movie(MovieAction) case cast(CastAction) } enum MovieAction { case requestMovieList case gotMovieList(movies: [Movie]) case movieListResponseError(MovieResponseError) case selectMovie(id: UUID) } enum CastAction { case requestCastList(movieId: UUID) case gotCastList(movieId: UUID, cast: [Person]) case castListResponseError(CastResponseError) case selectPerson(id: UUID) } ``` All possible events in your app should be listed in these enums and grouped the way you consider more relevant. When grouping these enums one thing to consider is modularity: you can split some or all these enums in different frameworks if you want strict boundaries between your modules and/or reuse the same group of actions among different apps. For example, all apps will have common actions that represent life-cycle of any iOS app, such as `willResignActive`, `didBecomeActive`, `didEnterBackground`, `willEnterForeground`. If multiples apps need to know this life-cycle, maybe it's convenient to create an enum for this specific domain. The same for network reachability, we should consider creating an enum to represent all possible events we get from the system when our connection state changes, and this can be used in a wide variety of apps. > **_IMPORTANT:_** Because enums in Swift don't have KeyPath as structs do, we strongly recommend reading [Action Enum Properties](docs/markdown/ActionEnumProperties.md) document and implementing properties for each case, either manually or using code generators, so later you avoid writing lots and lots of error-prone switch/case. We also offer some templates to help you on that. --- ### State State represents the whole knowledge that an app holds while is open, usually in memory and mutable. It's about relevant OUTPUT properties. There's no "State" protocol or type in SwiftRex. However, State will be found as a generic parameter for most core data structures, meaning that it's up to you to define what is the root State type. Conceptually, we can say that state represents the whole knowledge that an app holds while is open, usually in memory and mutable; it's like a paper on where you write down some values, and for every action you receive you erase one value and replace it by a different value. Another way of thinking about state is in a functional programming way: the state is not persisted, but it's the result of a function that takes the initial condition of your app plus all the actions it received since it was launched, and calculates the current values by applying chronologically all the action changes on top of the initial state. This is known as [Event Sourcing Design Pattern](https://martinfowler.com/eaaDev/EventSourcing.html) and it's becoming popular recently in some web backend services, such as [Kafka Event Sourcing](https://kafka.apache.org/uses). In a device with limited battery and memory we can't afford having a true event-sourcing pattern because it would be too expensive recreating the whole history of an app every time someone requests a simple boolean. So we "cache" the new state every time an action is received, and this in-memory cache is precisely what we call "State" in SwiftRex. So maybe we mix both ways of thinking about State and come up with a better generalisation for what a state is. > **STATE** is the result of a function that takes two arguments: the previous (or initial) state and some action that occurred, to determine the new state. This happens incrementally as more and more actions arrive. State is useful for **output** data to the user. However, be careful, some things may look like state but they are not. Let's assume you have an app that shows an item price to the user. This price will be shown as `"$3.00"` in US, or `"$3,00"` in Germany, or maybe this product can be listed in british pounds, so in US we should show `"ยฃ3.00"` while in Germany it would be `"ยฃ3,00"`. In this example we have: - Currency type (`ยฃ` or `$`) - Numeric value (`3`) - Locale (`en_US` or `de_DE`) - Formatted string (`"$3.00"`, `"$3,00"`, `"ยฃ3.00"` or `"ยฃ3,00"`) The formatted string itself is **NOT** state, because it can be calculated from the other properties. This can be called "derived state" and holding that is asking for inconsistency. We would have to remember to update this value every time one of the others change. So it's better off to represent this String either as a calculated property or a function of the other 3 values. The best place for this sort of derived state is in presenters or controllers, unless you have a high cost to recalculate it and in this case you could store in the state and be very careful about it. Luckily SwiftRex helps to keep the state consistent as we're about to see in the Reducer section, still, it's better off not duplicating information that can be easily and cheaply calculated. For representing the state of an app we recommend value types: structs or enums. Tuples would be acceptable as well, but unfortunately Swift currently doesn't allow us to conform tuples to protocols, and we usually want our whole state to be Equatable and sometimes Codable. ```swift struct AppState: Equatable { var appLifecycle: AppLifecycle var movies: Loadable<[Movie]> = .neverLoaded var currentFilter: MovieFilter var selectedMovie: UUID? } struct MovieFilter: Equatable { var stringFilter: String? var yearMin: Int? var yearMax: Int? var ratingMin: Int? var ratingMax: Int? } enum AppLifecycle: Equatable { case backgroundActive case backgroundInactive case foregroundActive case foregroundInactive } enum Loadable<T> { case neverLoaded case loading case loaded(T) } extension Loadable: Equatable where T: Equatable {} ``` Some properties represent a state-machine, for example the `Loadable` enum will eventually change from `.neverLoaded` to `.loading` and then to `.loaded([Movie])` in our `movies` property. Learning when and how to represent properties in this shape is a matter of experimenting more and more with SwiftRex and getting used to this architecture. Eventually this will become natural and you can start writing your own data structures to represent such state-machines, that will be very useful in countless situations. Annotating the whole state as Equatable helps us to reduce the UI updates in case view models are not used, but this is not a strong requirement and there are other ways to also avoid that, although we still recommend it. Annotating the state as Codable can be useful for logging, debugging, crash reports, monitors, etc and this is also recommended if possible. --- ## Core Parts - [Store](#store) - [StoreType](#storetype) - [Real Store](#real-store) - [Store Projection](#store-projection) - [All together](#all-together) - [Middleware](#middleware) - [Generics](#generics) - [Returning IO and performing side-effects](#returning-io-and-performing-side-effects) - [Dependency Injection](#dependency-injection) - [Middleware Examples](#middleware-examples) - [EffectMiddleware](#effectmiddleware) - [Reducer](#reducer) --- ### Store #### StoreType A protocol that defines the two expected roles of a "Store": receive/distribute actions (``ActionHandler``); and publish changes of the the current app state (``StateProvider``) to possible subscribers. It can be a real store (such as ``ReduxStoreBase``) or just a "proxy" that acts on behalf of a real store, for example, in the case of ``StoreProjection``. Store Type is an ``ActionHandler``, which means actors can dispatch actions (``ActionHandler/dispatch(_:)``) that will be handled by this store. These actions will eventually start side-effects or change state. These actions can also be dispatched by the result of side-effects, like the callback of an API call, or CLLocation new coordinates. How this action is handled will depend on the different implementations of ``StoreType``. Store Type is also a ``StateProvider``, which means it's aware of certain state and can notify possible subscribers about changes through its publisher (``StateProvider/statePublisher``). If this ``StoreType`` owns the state (single source-of-truth) or only proxies it from another store will depend on the different implementations of the protocol. ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ UIButton โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ dispatch<Action>(_ action: Action) โ”‚UIGestureRecognizerโ”‚โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ–ผ โ”‚viewDidLoadโ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒ โ”ƒโ–‘ โ”ƒ โ”ƒโ–‘ โ”ƒ โ”ƒโ–‘ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒ โ”ƒโ–‘ โ”‚UILabelโ”‚โ—€โ”€ โ”€ โ”€ โ”€ โ” โ”ƒ โ”ƒโ–‘ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Combine, RxSwift โ”Œ โ”€ โ”€ โ”ป โ”€ โ” โ”ƒโ–‘ โ”‚ or ReactiveSwift State Store โ”ƒโ–‘ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€โ”‚Publisherโ”‚ โ”ƒโ–‘ โ–ผ โ”‚ subscribe(onNext:) โ”ƒโ–‘ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ–ผ sink(receiveValue:) โ”” โ”€ โ”€ โ”ณ โ”€ โ”˜ โ”ƒโ–‘ โ”‚ Diffable โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” assign(to:on:) โ”ƒ โ”ƒโ–‘ โ”‚ DataSource โ”‚ โ”‚RxDataSourcesโ”‚ โ”ƒ โ”ƒโ–‘ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒ โ”ƒโ–‘ โ”‚ โ”‚ โ”ƒ โ”ƒโ–‘ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”›โ–‘ โ”‚ โ”‚ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ UICollectionView โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` There are implementations that will be the actual Store, the one and only instance that will be the central hub for the whole redux architecture. Other implementations can be only projections or the main Store, so they act like a Store by implementing the same roles, but instead of owning the global state or handling the actions directly, these projections only apply some small (and pure) transformation in the chain and delegate to the real Store. This is useful when you want to have local "stores" in your views, but you don't want them to duplicate data or own any kind of state, but only act as a store while using the central one behind the scenes. For more information about real stores, please check ``ReduxStoreBase`` and ``ReduxStoreProtocol``, and for more information about the projections please check ``StoreProjection`` and ``StoreType/projection(action:state:)``. #### Real Store? A real Store is a class that you want to create and keep alive during the whole execution of an app, because its only responsibility is to act as a coordinator for the Unidirectional Dataflow lifecycle. That's also why we want one and only one instance of a Store, so either you create a static instance singleton, or keep it in your AppDelegate. Be careful with SceneDelegate if your app supports multiple windows and you want to share the state between these multiple instances of your app, which you usually want. That's why AppDelegate, singleton or global variable is usually recommended for the Store, not SceneDelegate. In case of SwiftUI you can create a store in your app protocol as a ``Combine/StateObject``: ```swift @main struct MyApp: App { @StateObject var store = Store.createStore(dependencyInjection: World.default).asObservableViewModel(initialState: .initial) var body: some Scene { WindowGroup { ContentView(viewModel: ContentViewModel(store: store)) } } } ``` SwiftRex will provide a protocol (``ReduxStoreProtocol``) and a base class (``ReduxStoreBase``) for helping you to create your own Store. ```swift class Store: ReduxStoreBase<AppAction, AppState> { static func createStore(dependencyInjection: World) -> Store { let store = Store( subject: .combine(initialValue: .initial), reducer: AppModule.appReducer, middleware: AppModule.appMiddleware(dependencyInjection: dependencyInjection) emitsValue: .whenDifferent ) store.dispatch(AppAction.lifecycle(LifeCycleAction.start)) return store } } ``` #### What is a Store Projection? Very often you don't want your view to be able to access the whole App State or dispatch any possible global App Action. Not only it could refresh your UI more often than needed, it also makes more error prone, put more complex code in the view layer and finally decreases modularisation making the view coupled to the global models. However, you don't want to split your state in multiple parts because having it in a central and unique point ensures consistency. Also, you don't want multiple separate places taking care of actions because that could potentially create race conditions. The real Store is the only place actually owning the global state and effectively handling the actions, and that's how it's supposed to be. To solve both problems, we offer a ``StoreProjection``, which conforms to the ``StoreType`` protocol so for all purposes it behaves like a real store, but in fact it only projects the real store using custom types for state and actions, that is, either a subset of your models (a branch in the state tree, for example), or a completely different entity like a View State. A ``StoreProjection`` has 2 closures, that allow it to transform actions and state between the global ones and the ones used by the view. That way, the View is not coupled to the whole global models, but only to tiny parts of it, and the closure in the ``StoreProjection`` will take care of extracting/mapping the interesting part for the view. This also improves performance, because the view will not refresh for any property in the global state, only for the relevant ones. On the other direction, view can only dispatch a limited set of actions, that will be mapped into global actions by the closure in the ``StoreProjection``. A Store Projection can be created from any other ``StoreType``, even from another ``StoreProjection``. It's as simple as calling ``StoreType/projection(action:state:)``, and providing the action and state mapping closures: ```swift let storeProjection = store.projection( action: { viewAction in viewAction.toAppAction() } , state: { globalState in MyViewState.from(globalState: globalState) } ).asObservableViewModel(initialState: .empty) ``` #### All together Putting everything together we could have: ```swift @main struct MyApp: App { @StateObject var store = Store.createStore(dependencyInjection: World.default).asObservableViewModel(initialState: .initial) var body: some Scene { WindowGroup { ContentView( viewModel: store.projection( action: { (viewAction: ContentViewAction) -> AppAction? in viewAction.toAppAction() }, state: { (globalState: AppState) -> ContentViewState in ContentViewState.from(globalState: globalState) } ).asObservableViewModel(initialState: .empty) ) } } } struct ContentViewState: Equatable { let title: String static func from(globalState: AppState) -> ContentViewState { ContentViewState(title: "\(L10n.goodMorning), \(globalState.foo.bar.title)") } } enum ContentViewAction { case onAppear func toAppAction() -> AppAction? { switch self { case .onAppear: return AppAction.foo(.bar(.startTimer)) } } } ``` In this example above we can see that `ContentView` doesn't know about the global models, it's limited to `ContentViewAction` and `ContentViewState` only. It also only refreshes when `globalState.foo.bar.title` changes, any other change in the `AppState` will be ignored because the other properties are not mapped into anything in the `ContentViewState`. Also, `ContentViewAction` has a single case, `onAppear`, and that's the only thing the view can dispatch, without knowing that this will eventually start a timer (`AppAction.foo(.bar(.startTimer))`). The view should not know about domain logic and its actions should be limited to `buttonTapped`, `onAppear`, `didScroll`, `toggle(enabled: Bool)` and other names that only suggest UI interaction. How this is mapped into App Actions is responsibility of other parts, in our example, `ContentViewAction` itself, but it could be a Presenter layer, a View Model layer, or whatever structure you decide to create to organise your code. Testing is also made easier with this approach, as the View doesn't hold any logic and the projection transformations are pure functions. ![Store, StoreProjection and View](StoreProjectionDiagram) ### Middleware ``MiddlewareProtocol`` is a plugin, or a composition of several plugins, that are assigned to the app global ``StoreType`` pipeline in order to handle each action received (``InputActionType``), to execute side-effects in response, and eventually dispatch more actions (``OutputActionType``) in the process. It can also access the most up-to-date ``StateType`` while handling an incoming action. We can think of a Middleware as an object that transforms actions into sync or async tasks and create more actions as these side-effects complete, also being able to check the current state while handling an action. An [Action](#action) is a lightweight structure, typically an enum, that is dispatched into the ``ActionHandler`` (usually a ``StoreType``). A Store like ``ReduxStoreProtocol`` enqueues a new action that arrives and submits it to a pipeline of middlewares. So, in other words, a ``MiddlewareProtocol`` is class that handles actions, and has the power to dispatch more actions, either immediately or after callback of async tasks. The middleware can also simply ignore the action, or it can execute side-effects in response, such as logging into file or over the network, or execute http requests, for example. In case of those async tasks, when they complete the middleware can dispatch new actions containing a payload with the response (a JSON file, an array of movies, credentials, etc). Other middlewares will handle that, or maybe even the same middleware in the future, or perhaps some ``Reducer`` will use this action to change the state, because the ``MiddlewareProtocol`` itself can never change the state, only read it. The ``MiddlewareProtocol/handle(action:from:state:)`` will be called before the Reducer, so if you read the state at that point it's still going to be the unchanged version. While implementing this function, it's expected that you return an ``IO`` object, which is basically a closure where you can perform side-effects and dispatch new actions. Inside this closure, the state will have the new values after the reducers handled the current action, so in case you made a copy of the old state, you can compare them, log, audit, perform analytics tracking, telemetry or state sync with external devices, such as Apple Watches. Remote Debugging over the network is also a great use of a Middleware. Every action dispatched also comes with its action source, which is the primary dispatcher of that action. Middlewares can access the file name, line of code, function name and additional information about the entity responsible for creating and dispatching that action, which is a very powerful debugging information that can help developers to trace how the information flows through the app. Ideally a ``MiddlewareProtocol`` should be a small and reusable box, handling only a very limited set of actions, and combined with other small middlewares to create more complex apps. For example, the same `CoreLocation` middleware could be used from an iOS app, its extensions, the Apple Watch extension or even different apps, as long as they share some sub-action tree and sub-state struct. Some suggestions of middlewares: - Run Timers, pooling some external resource or updating some local state at a constant time - Subscribe for `CoreData`, `Realm`, `Firebase Realtime Database` or equivalent database changes - Be a `CoreLocation` delegate, checking for significant location changes or beacon ranges and triggering actions to update the state - Be a `HealthKit` delegate to track activities, or even combining that with `CoreLocation` observation in order to track the activity route - Logger, Telemetry, Auditing, Analytics tracker, Crash report breadcrumbs - Monitoring or debugging tools, like external apps to monitor the state and actions remotely from a different device - `WatchConnectivity` sync, keep iOS and watchOS state in sync - API calls and other "cold observables" - Network Reachability - Navigation through the app (Redux Coordinator pattern) - `CoreBluetooth` central or peripheral manager - `CoreNFC` manager and delegate - `NotificationCenter` and other delegates - WebSocket, TCP Socket, Multipeer and many other connectivity protocols - `RxSwift` observables, `ReactiveSwift` signal producers, `Combine` publishers - Observation of traits changes, device rotation, language/locale, dark mode, dynamic fonts, background/foreground state - Any side-effect, I/O, networking, sensors, third-party libraries that you want to abstract ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” IO closure โ”Œโ”€โ–ถโ”‚ View 1 โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ” (don't run yet) โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ handle โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ โ”‚ send โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Middlewareโ”‚โ”€โ”€โ”˜ โ”‚ โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”œโ”€โ–ถโ”‚ View 2 โ”‚ โ”‚ โ”‚ Action โ”‚ Pipeline โ”‚โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” reduce โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ New state โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ–ถโ”‚ โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ Reducer โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ” dispatch โ”‚ โ”‚ โ”‚Storeโ”‚ Action โ”‚ Pipeline โ”‚ New state โ”‚ โ”‚ โ””โ”€โ–ถโ”‚ View 3 โ”‚ โ”‚Buttonโ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Storeโ”‚ โ”‚ โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚Storeโ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Action โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ State โ”‚ โ”‚ dispatch โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” New Action โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ”€runโ”€โ”€โ–ถโ”‚ IO closure โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Storeโ”‚โ”€ โ”€ โ–ถ ... โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ฒ requestโ”‚ side-effects โ”‚side-effects โ–ผ response โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”‚ External โ”‚โ”€ โ”€ async โ”€ โ”€ โ”€ โ”‚ World โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ ``` #### Generics Middleware protocol is generic over 3 associated types: - ``InputActionType``: The Action type that this ``MiddlewareProtocol`` knows how to handle, so the store will forward actions of this type to this middleware. Most of the times middlewares don't need to handle all possible actions from the whole global action tree, so we can decide to allow it to focus only on a subset of the action. In this case, this action type can be a subset to be lifted to a global action type in order to compose with other middlewares acting on the global action of an app. Please check [Lifting](#lifting) for more details. - ``OutputActionType``: The Action type that this ``MiddlewareProtocol`` will eventually trigger back to the store in response of side-effects. This can be the same as ``InputActionType`` or different, in case you want to separate your enum in requests and responses. Most of the times middlewares don't need to dispatch all possible actions of the whole global action tree, so we can decide to allow it to dispatch only a subset of the action, or not dispatch any action at all, so the ``OutputActionType`` can safely be set to `Never`. In this case, this action type can be a subset to be lifted to a global action type in order to compose with other middlewares acting on the global action of an app. Please check [Lifting](#lifting) for more details. - ``StateType``: The State part that this ``MiddlewareProtocol`` needs to read in order to make decisions. This middleware will be able to read the most up-to-date ``StateType`` from the store while handling an incoming action, but it can never write or make changes to it. Most of the times middlewares don't need reading the whole global state, so we can decide to allow it to read only a subset of the state, or maybe this middleware doesn't need to read any state, so the ``StateType`` can safely be set to `Void`. In this case, this state type can be a subset to be lifted to a global state in order to compose with other middlewares acting on the global state of an app. Please check [Lifting](#lifting) for more details. #### Returning IO and performing side-effects In its most important function, ``MiddlewareProtocol/handle(action:from:state:)`` the middleware is expected to return an ``IO`` object, which is a closure where side-effects should be executed and new actions can be dispatched. In some cases, we may want to not execute any side-effect or run any code after reducer, in that case, the function can return a simple ``IO/pure()``. Otherwise, return the closure that takes the `output` (of ``ActionHandler`` type, that accepts ``ActionHandler/dispatch(_:)`` calls): ```swift public func handle(action: InputActionType, from dispatcher: ActionSource, state: @escaping GetState<StateType>) -> IO<OutputActionType> { if action != .myExpectedAction { return .pure() } return IO { output in output.dispatch(.showPopup) DispatchQueue.global().asyncAfter(.now() + .seconds(3)) { output.dispatch(.hidePopup) } } } ``` #### Dependency Injection Testability is one of the most important aspects to account for when developing software. In Redux architecture, ``MiddlewareProtocol`` is the only type of object allowed to perform side-effects, so it's the only place where the testability can be challenging. To improve testability, the middleware should use as few external dependencies as possible. If it starts to use too many, consider splitting in smaller middlewares, this will also protect you against race conditions and other problems, will help with tests and make the middleware more reusable. Also, all external dependencies should be injected in the initialiser, so during the tests you can replace them with mocks. If your middleware uses only one call from a very complex object, instead of using a protocol full of functions please consider either creating a protocol with a single function requirement, or even inject a closure such as `@escaping (URLRequest) -> AnyPublisher<(Data, URLResponse), Error>`. Creating mocks for this will be way much easier. Finally, consider using ``MiddlewareReader`` to wrap this middleware in a dependency injection container. #### Middleware Examples When implementing your Middleware, all you have to do is to handle the incoming actions: ```swift public final class LoggerMiddleware: MiddlewareProtocol { public typealias InputActionType = AppGlobalAction // It wants to receive all possible app actions public typealias OutputActionType = Never // No action is generated from this Middleware public typealias StateType = AppGlobalState // It wants to read the whole app state private let logger: Logger private let now: () -> Date // Dependency Injection public init(logger: Logger = Logger.default, now: @escaping () -> Date) { self.logger = logger self.now = now } // inputAction: AppGlobalAction state: AppGlobalState output action: Never public func handle(action: InputActionType, from dispatcher: ActionSource, state: @escaping GetState<StateType>) -> IO<OutputActionType> { let stateBefore: AppGlobalState = state() let dateBefore = now() return IO { [weak self] output in guard let self = self else { return } let stateAfter = state() let dateAfter = self.now() let source = "\(dispatcher.file):\(dispatcher.line) - \(dispatcher.function) | \(dispatcher.info ?? "")" self.logger.log(action: action, from: source, before: stateBefore, after: stateAfter, dateBefore: dateBefore, dateAfter: dateAfter) } } } public final class FavoritesAPIMiddleware: MiddlewareProtocol { public typealias InputActionType = FavoritesAction // It wants to receive only actions related to Favorites public typealias OutputActionType = FavoritesAction // It wants to also dispatch actions related to Favorites public typealias StateType = FavoritesModel // It wants to read the app state that manages favorites private let api: API // Dependency Injection public init(api: API) { self.api = api } // inputAction: FavoritesAction state: FavoritesModel output action: FavoritesAction public func handle(action: InputActionType, from dispatcher: ActionSource, state: @escaping GetState<StateType>) -> IO<OutputActionType> { guard case let .toggleFavorite(movieId) = action else { return .pure() } let favoritesList = state() // state before reducer let makeFavorite = !favoritesList.contains(where: { $0.id == movieId }) return IO { [weak self] output in guard let self = self else { return } self.api.changeFavorite(id: movieId, makeFavorite: makeFavorite) (completion: { result in switch result { case let .success(value): output.dispatch(.changedFavorite(movieId, isFavorite: makeFavorite), info: "API.changeFavorite callback") case let .failure(error): output.dispatch(.changedFavoriteHasFailed(movieId, isFavorite: !makeFavorite, error: error), info: "api.changeFavorite callback") } }) } } } ``` ![SwiftUI Side-Effects](wwdc2019-226-02) #### EffectMiddleware This is a middleware implementation that aims for simplicity while keeping it very powerful. For every incoming action you must return an Effect, which is simply a wrapper for a reactive Observable, Publisher or SignalProducer, depending on your favourite reactive library. The only condition is that the Output (Element) of your reactive stream must be a DispatchedAction and the Error must be Never. DispatchedAction is a struct having the action itself and the dispatcher (action source), so it's generic over the Action and matches the OutputAction of the EffectMiddleware. Error must be Never because Middlewares are expected to resolve all side-effects, including Errors. So if you want to treat the error, you can do it in the middleware, if you want to warn the user about the error, then you catch the error in your reactive stream and transform it into an Action such as `.somethingWentWrong(messageToTheUser: String)` to be dispatched and later reduced into the AppState. Optionally an EffectMiddleware can also handle Dependencies. This helps to perform Dependency Injection into the middleware. If your Dependency generic parameter is Void, then the Middleware can be created immediately without passing any dependency, however you can't use any external dependency when handling the action. If Dependency generic parameter has some type, or tuple, then you can use them while handling the action, but in order to create the effect middleware you will need to provide that type or tuple. Important: the dependency will be available inside the Effect closure only, because it's expected that you "access" the external world only while executing an Effect. ```swift static let favouritesMiddleware = EffectMiddleware<FavoritesAction /* input action */, FavoritesAction /* output action */, AppState, FavouritesAPI /* dependencies */>.onAction { incomingAction, dispatcher, getState in switch incomingAction { case let .toggleFavorite(movieId): return Effect(token: "Any Hashable. Use this to cancel tasks, or to avoid two tasks of the same type") { context -> AnyPublisher<DispatchedAction<FavoritesAction>, Never> in let favoritesList = getState() let makeFavorite = !favoritesList.contains(where: { $0.id == movieId }) let api = context.dependencies return api.changeFavoritePublisher(id: movieId, makeFavorite: makeFavorite) .catch { error in DispatchedAction(.somethingWentWrong("Got an error: \(error)") } .eraseToAnyPublisher() } default: return .doNothing // Special type of Effect that, well, does nothing. } } ``` Effect has some useful constructors such as `.doNothing`, `.fireAndForget`, `.just`, `.sequence`, `.promise`, `.toCancel` and others. Also, you can lift any Publisher, Observable or SignalProducer into an Effect, as long as it matches the required generic parameters, for that you can simply use `.asEffect()` functions. ![SwiftUI Side-Effects](https://swiftrex.github.io/SwiftRex/markdown/img/wwdc2019-226-02.jpg) ### Reducer `Reducer` is a pure function wrapped in a monoid container, that takes an action and the current state to calculate the new state. The ``MiddlewareProtocol`` pipeline can do two things: dispatch outgoing actions and handling incoming actions. But what they can NOT do is changing the app state. Middlewares have read-only access to the up-to-date state of our apps, but when mutations are required we use the ``MutableReduceFunction`` function: ```swift (ActionType, inout StateType) -> Void ``` Which has the same semantics (but better performance) than old ``ReduceFunction``: ```swift (ActionType, StateType) -> StateType ``` Given an action and the current state (as a mutable inout), it calculates the new state and changes it: ``` initial state is 42 action: increment reducer: increment 42 => new state 43 current state is 43 action: decrement reducer: decrement 43 => new state 42 current state is 42 action: half reducer: half 42 => new state 21 ``` The function is reducing all the actions in a cached state, and that happens incrementally for each new incoming action. It's important to understand that reducer is a synchronous operations that calculates a new state without any kind of side-effect (including non-obvious ones as creating `Date()`, using DispatchQueue or `Locale.current`), so never add properties to the ``Reducer`` structs or call any external function. If you are tempted to do that, please create a middleware and dispatch actions with Dates or Locales from it. Reducers are also responsible for keeping the consistency of a state, so it's always good to do a final sanity check before changing the state, like for example check other dependant properties that must be changed together. Once the reducer function executes, the store will update its single source-of-truth with the new calculated state, and propagate it to all its subscribers, that will react to the new state and update Views, for example. This function is wrapped in a struct to overcome some Swift limitations, for example, allowing us to compose multiple reducers into one (monoid operation, where two or more reducers become a single one) or lifting reducers from local types to global types. The ability to lift reducers allow us to write fine-grained "sub-reducer" that will handle only a subset of the state and/or action, place it in different frameworks and modules, and later plugged into a bigger state and action handler by providing a way to map state and actions between the global and local ones. For more information about that, please check [Lifting](#lifting). A possible implementation of a reducer would be: ```swift let volumeReducer = Reducer<VolumeAction, VolumeState>.reduce { action, currentState in switch action { case .louder: currentState = VolumeState( isMute: false, // When increasing the volume, always unmute it. volume: min(100, currentState.volume + 5) ) case .quieter: currentState = VolumeState( isMute: currentState.isMute, volume: max(0, currentState.volume - 5) ) case .toggleMute: currentState = VolumeState( isMute: !currentState.isMute, volume: currentState.volume ) } } ``` Please notice from the example above the following good practices: - No `DispatchQueue`, threading, operation queue, promises, reactive code in there. - All you need to implement this function is provided by the arguments `action` and `currentState`, don't use any other variable coming from global scope, not even for reading purposes. If you need something else, it should either be in the state or come in the action payload. - Do not start side-effects, requests, I/O, database calls. - Avoid `default` when writing `switch`/`case` statements. That way the compiler will help you more. - Make the action and the state generic parameters as much specialised as you can. If volume state is part of a bigger state, you should not be tempted to pass the whole big state into this reducer. Make it short, brief and specialised, this also helps preventing `default` case or having to re-assign properties that are never mutated by this reducer. ``` โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” IO closure โ”Œโ”€โ–ถโ”‚ View 1 โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ” (don't run yet) โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ handle โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ โ”‚ send โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Middlewareโ”‚โ”€โ”€โ”˜ โ”‚ โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”œโ”€โ–ถโ”‚ View 2 โ”‚ โ”‚ โ”‚ Action โ”‚ Pipeline โ”‚โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ” reduce โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ New state โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ–ถโ”‚ โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ Reducer โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ” dispatch โ”‚ โ”‚ โ”‚Storeโ”‚ Action โ”‚ Pipeline โ”‚ New state โ”‚ โ”‚ โ””โ”€โ–ถโ”‚ View 3 โ”‚ โ”‚Buttonโ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Storeโ”‚ โ”‚ โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚Storeโ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Action โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ State โ”‚ โ”‚ dispatch โ”Œโ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” New Action โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚โ”€runโ”€โ”€โ–ถโ”‚ IO closure โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚Storeโ”‚โ”€ โ”€ โ–ถ ... โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ–ฒ requestโ”‚ side-effects โ”‚side-effects โ–ผ response โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”‚ External โ”‚โ”€ โ”€ async โ”€ โ”€ โ”€ โ”‚ World โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ ``` ## Projection and Lifting - [Store Projection](#store-projection) - [Lifting](#lifting) - [Lifting Reducer](#lifting-reducer) - [Lifting Reducer using closures:](#lifting-reducer-using-closures) - [Lifting Reducer using KeyPath:](#lifting-reducer-using-keypath) - [Lifting Middleware](#lifting-middleware) - [Lifting Middleware using closures:](#lifting-middleware-using-closures) - [Lifting Middleware using KeyPath:](#lifting-middleware-using-keypath) - [Optional transformation](#optional-transformation) - [Direction of the arrows](#direction-of-the-arrows) - [Use of KeyPaths](#use-of-keypaths) - [Identity, Ignore and Absurd](#identity-ignore-and-absurd) - [Xcode Snippets:](#xcode-snippets) ### Store Projection An app should have a single real Store, holding a single source-of-truth. However, we can "derive" this store to small subsets, called store projections, that will handle either a smaller part of the state or action tree, or even a completely different type of actions and states as long as we can map back-and-forth to the original store types. It won't store anything, only project the original store. For example, a View can define a completely custom View State and View Action, and we can create a ``StoreProjection`` that works on these types, as long as it's backed by a real store which State and Action types can be mapped somehow to the View State and View Action types. The Store Projection will take care of translating these entities. ![Store Projection](https://swiftrex.github.io/SwiftRex/markdown/img/StoreProjectionDiagram.png) Very often you don't want your view to be able to access the whole App State or dispatch any possible global App Action. Not only it could refresh your UI more often than needed, it also makes more error prone, put more complex code in the view layer and finally decreases modularisation making the view coupled to the global models. However, you don't want to split your state in multiple parts because having it in a central and unique point ensures consistency. Also, you don't want multiple separate places taking care of actions because that could potentially create race conditions. The real Store is the only place actually owning the global state and effectively handling the actions, and that's how it's supposed to be. To solve both problems, we offer a ``StoreProjection``, which conforms to the ``StoreType`` protocol so for all purposes it behaves like a real store, but in fact it only projects the real store using custom types for state and actions, that is, either a subset of your models (a branch in the state tree, for example), or a completely different entity like a View State. A ``StoreProjection`` has 2 closures, that allow it to transform actions and state between the global ones and the ones used by the view. That way, the View is not coupled to the whole global models, but only to tiny parts of it, and the closure in the ``StoreProjection`` will take care of extracting/mapping the interesting part for the view. This also improves performance, because the view will not refresh for any property in the global state, only for the relevant ones. On the other direction, view can only dispatch a limited set of actions, that will be mapped into global actions by the closure in the ``StoreProjection``. A Store Projection can be created from any other ``StoreType``, even from another ``StoreProjection``. It's as simple as calling ``StoreType/projection(action:state:)``, and providing the action and state mapping closures: ```swift let storeProjection = store.projection( action: { viewAction in viewAction.toAppAction() } , state: { globalState in MyViewState.from(globalState: globalState) } ).asObservableViewModel(initialState: .empty) ``` For more information about real store vs. store projections, and also for complete code examples, please check documentation for ``StoreType``. ### Lifting An app can be a complex product, performing several activities that not necessarily are related. For example, the same app may need to perform a request to a weather API, check the current user location using CLLocation and read preferences from UserDefaults. Although these activities are combined to create the full experience, they can be isolated from each other in order to avoid URLSession logic and CLLocation logic in the same place, competing for the same resources and potentially causing race conditions. Also, testing these parts in isolation is often easier and leads to more significant tests. Ideally we should organise our `AppState` and `AppAction` to account for these parts as isolated trees. In the example above, we could have 3 different properties in our AppState and 3 different enum cases in our AppAction to group state and actions related to the weather API, to the user location and to the UserDefaults access. This gets even more helpful in case we split our app in 3 types of ``Reducer`` and 3 types of ``MiddlewareProtocol``, and each of them work not on the full `AppState` and `AppAction`, but in the 3 paths we grouped in our model. The first pair of ``Reducer`` and ``MiddlewareProtocol`` would be generic over ``WeatherState`` and ``WeatherAction``, the second pair over ``LocationState`` and ``LocationAction`` and the third pair over ``RepositoryState`` and ``RepositoryAction``. They could even be in different frameworks, so the compiler will forbid us from coupling Weather API code with CLLocation code, which is great as this enforces better practices and unlocks code reusability. Maybe our CLLocation middleware/reducer can be useful in a completely different app that checks for public transport routes. But at some point we want to put these 3 different types of entities together, and the ``StoreType`` of our app "speaks" `AppAction` and `AppState`, not the subsets used by the specialised handlers. ```swift enum AppAction { case weather(WeatherAction) case location(LocationAction) case repository(RepositoryAction) } struct AppState { let weather: WeatherState let location: LocationState let repository: RepositoryState } ``` Given a reducer that is generic over `WeatherAction` and `WeatherState`, we can "lift" it to the global types `AppAction` and `AppState` by telling this reducer how to find in the global tree the properties that it needs. That would be `\AppAction.weather` and `\AppState.weather`. The same can be done for the middleware, and for the other 2 reducers and middlewares of our app. When all of them are lifted to a common type, they can be combined together using the diamond operator (`<>`) and set as the store handler. > **_IMPORTANT:_** Because enums in Swift don't have KeyPath as structs do, we strongly recommend reading [Action Enum Properties](docs/markdown/ActionEnumProperties.md) document and implementing properties for each case, either manually or using code generators, so later you avoid writing lots and lots of error-prone switch/case. We also offer some templates to help you on that. Let's explore how to lift reducers and middlewares. #### Lifting Reducer ``Reducer`` has AppAction INPUT, AppState INPUT and AppState OUTPUT, because it can only handle actions (never dispatch them), read the state and write the state. The lifting direction, therefore, should be: ``` Reducer: - ReducerAction? โ† AppAction - ReducerState โ†โ†’ AppState ``` Given: ```swift // type 1 type 2 Reducer<ReducerAction, ReducerState> ``` Transformations: ``` โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ โ•‘ โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ โ•‘ โ•‘ Reducer โ•‘ .lift โ•‘ Store โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ•‘ โ•‘ โ”‚ โ•‘ โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ” (AppAction) -> ReducerAction? โ”‚ โ”‚ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”‚ Reducer โ”‚ { $0.case?.reducerAction } โ”‚ โ”‚ Input Action โ”‚ Action โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚ AppAction โ”‚ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”‚ โ”‚ KeyPath<AppAction, ReducerAction?> โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ \AppAction.case?.reducerAction โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ get: (AppState) -> ReducerState โ”‚ { $0.reducerState } โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ” set: (inout AppState, ReducerState) -> Void โ”‚ โ”‚ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”‚ Reducer โ”‚ { $0.reducerState = $1 } โ”‚ โ”‚ State โ”‚ State โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ AppState โ”‚ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”‚ โ”‚ WritableKeyPath<AppState, ReducerState> โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ \AppState.reducerState โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ ``` ##### Lifting Reducer using closures: ```swift .lift( actionGetter: { (action: AppAction) -> ReducerAction? /* type 1 */ in // prism3 has associated value of ReducerAction, // and whole thing is Optional because Prism is always optional action.prism1?.prism2?.prism3 }, stateGetter: { (state: AppState) -> ReducerState /* type 2 */ in // property2: ReducerState state.property1.property2 }, stateSetter: { (state: inout AppState, newValue: ReducerState /* type 2 */) -> Void in // property2: ReducerState state.property1.property2 = newValue } ) ``` Steps: - Start plugging the 2 types from the Reducer into the 3 closure headers. - For type 1, find a prism that resolves from AppAction into the matching type. **BE SURE TO RUN SOURCERY AND HAVING ALL ENUM CASES COVERED BY PRISM** - For type 2 on the stateGetter closure, find lenses (property getters) that resolve from AppState into the matching type. - For type 2 on the stateSetter closure, find lenses (property setters) that can change the global state receive to the newValue received. Be sure that everything is writeable. ##### Lifting Reducer using KeyPath: ```swift .lift( action: \AppAction.prism1?.prism2?.prism3, state: \AppState.property1.property2 ) ``` Steps: - Start with the closure example above - For action, we can use KeyPath from `\AppAction` traversing the prism tree - For state, we can use WritableKeyPath from `\AppState` traversing the properties as long as all of them are declared as `var`, not `let`. #### Lifting Middleware ``MiddlewareProtocol`` has AppAction INPUT, AppAction OUTPUT and AppState INPUT, because it can handle actions, dispatch actions, and only read the state (never write it). The lifting direction, therefore, should be: ``` Middleware: - MiddlewareInputAction? โ† AppAction - MiddlewareOutputAction โ†’ AppAction - MiddlewareState โ† AppState ``` Given: ```swift // type 1 type 2 type 3 MyMiddleware<MiddlewareInputAction, MiddlewareOutputAction, MiddlewareState> ``` Transformations: ``` โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ โ•‘ โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ โ•‘ โ•‘ Middleware โ•‘ .lift โ•‘ Store โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ•‘ โ•‘ โ”‚ โ•‘ โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• โ”‚ โ”‚ โ”‚ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ” (AppAction) -> MiddlewareInputAction? โ”‚ โ”‚ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”‚Middleware โ”‚ { $0.case?.middlewareInputAction } โ”‚ โ”‚ Input Action โ”‚ Input โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚ AppAction โ”‚ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”‚ Action โ”‚ KeyPath<AppAction, MiddlewareInputAction?> โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ \AppAction.case?.middlewareInputAction โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” (MiddlewareOutputAction) -> AppAction โ”‚ โ”‚ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”‚Middleware โ”‚ { AppAction.case($0) } โ”‚ โ”‚ Output Action โ”‚ Output โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ AppAction โ”‚ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”‚ Action โ”‚ AppAction.case โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ” (AppState) -> MiddlewareState โ”‚ โ”‚ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”‚Middleware โ”‚ { $0.middlewareState } โ”‚ โ”‚ State โ”‚ State โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”‚ AppState โ”‚ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”‚ โ”‚ KeyPath<AppState, MiddlewareState> โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”˜ \AppState.middlewareState โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚ ``` ##### Lifting Middleware using closures: ```swift .lift( inputAction: { (action: AppAction) -> MiddlewareInputAction? /* type 1 */ in // prism3 has associated value of MiddlewareInputAction, // and whole thing is Optional because Prism is always optional action.prism1?.prism2?.prism3 }, outputAction: { (local: MiddlewareOutputAction /* type 2 */) -> AppAction in // local is MiddlewareOutputAction, // an associated value for .prism3 AppAction.prism1(.prism2(.prism3(local))) }, state: { (state: AppState) -> MiddlewareState /* type 3 */ in // property2: MiddlewareState state.property1.property2 } ) ``` Steps: - Start plugging the 3 types from MyMiddleware into the closure headers. - For type 1, find a prism that resolves from AppAction into the matching type. **BE SURE TO RUN SOURCERY AND HAVING ALL ENUM CASES COVERED BY PRISM** - For type 2, wrap it from inside to outside until you reach AppAction, in this example we wrap it (being "it" = local) in .prism3, which we wrap in .prism2, then .prism1 to finally reach AppAction. - For type 3, find lenses (property getters) that resolve from AppState into the matching type. ##### Lifting Middleware using KeyPath: ```swift .lift( inputAction: \AppAction.prism1?.prism2?.prism3, outputAction: Prism2.prism3, state: \AppState.property1.property2 ) .lift(outputAction: Prism1.prism2) .lift(outputAction: AppAction.prism1) ``` Steps: - Start with the closure example above - For inputAction, we can use KeyPath from `\AppAction` traversing the prism tree - For outputAction it's **NOT** a KeyPath, but a wrapping. Because we can't wrap more than 1 level at once, either we: - use the closure version for this one - lift level by level, from inside to outside, in that case follow the steps of wrapping local into Prism2 (case .prism3), then wrapping result into Prism1 (case .prism2), then wrapping result into AppAction (case .prism1) - When it's only 1 level, there's nothing to worry about - For state, we can use KeyPath from `\AppState` traversing the properties. #### Optional transformation If some action is running through the store, some reducers and middlewares may opt for ignoring it. For example, if the action tree has nothing to do with that middleware or reducer. That's why, every INCOMING action (InputAction for Middlewares and simply Action for Reducers) is a transformation from `AppAction โ†’ Optional<Subset>`. Returning nil means that the action will be ignored. This is not true for the other direction, when actions are dispatched by Middlewares, they MUST become an AppAction, we can't ignore what Middlewares have to say. #### Direction of the arrows **Reducers** receive actions (input action) and are able to read and write state. **Middlewares** receive actions (input action), dispatch actions (output action) and only read the state (input state). When lifting, we must keep that in mind because it defines the variance (covariant/contravariant) of the transformation, that is, _map_ or _contramap_. One special case is the State for reducer, because that requires a read and write access, in other words, you are given an `inout Whole` and a new value for `Part`, you use that new value to set the correct path inside the inout Whole. This is precisely what WritableKeyPaths are mean for, which we will see with more details now. #### Use of KeyPaths KeyPath is the same as `Global -> Part` transformation, where you give the description of the tree in the following way: `\Global.parent.part`. WritableKeyPath has similar usage syntax, but it's much more powerful, allowing us to transform `(Global, Part) -> Global`, or `(inout Global, Part) -> Void` which is the same. That said we need to understand that KeyPaths are only possible when the direction of the arrows comes from `AppElement -> ReducerOrMiddlewareElement`, that is: ``` Reducer: - ReducerAction? โ† AppAction // Keypath is possible - ReducerState โ†โ†’ AppState // WritableKeyPath is possible ``` ``` Middleware: - MiddlewareInputAction? โ† AppAction // KeyPath is possible - MiddlewareOutputAction โ†’ AppAction // NOT POSSIBLE - MiddlewareState โ† AppState // KeyPath is possible ``` For the `ReducerAction? โ† AppAction` and `MiddlewareInputAction? โ† AppAction` we can use KeyPaths that resolve to `Optional<ReducerOrMiddlewareAction>`: ```swift { (globalAction: AppAction) -> ReducerOrMiddlewareAction? in globalAction.parent?.reducerOrMiddlewareAction } // or // KeyPath<AppAction, ReducerOrMiddlewareAction?> \AppAction.parent?.reducerOrMiddlewareAction ``` For the `ReducerState โ†โ†’ AppState` and `MiddlewareState โ† AppState` transformations, we can use similar syntax although the Reducer is inout (WritableKeyPath). That means our whole tree must be composed by `var` properties, not `let`. In this case, unless the Middleware or Reducer accepts Optional, the transformation should NOT be Optional. ```swift { (globalState: AppState) -> PartState in globalState.something.thatsThePieceWeWant } { (globalState: inout AppState, newValue: PartState) -> Void in globalState.something.thatsThePieceWeWant = newValue } // or // KeyPath<AppState, PartState> or WritableKeyPath<AppState, PartState> \AppState.something.thatsThePieceWeWant // where: // var something // var thatsThePieceWeWant ``` For the `MiddlewareOutputAction โ†’ AppAction` we can't use keypath, it doesn't make sense, because the direction is the opposite of what we want. In that case we are not unwrapping/extracting the part from a global value, we were given a specific action from certain middleware and we need to wrap it into the AppAction. This can be achieved by two forms: ```swift { (middlewareAction: MiddlewareAction) -> AppAction in AppAction.treeForMiddlewareAction(middlewareAction) } // or simply AppAction.treeForMiddlewareAction // please notice, not KeyPath, it doesn't start by \ ``` The short form, however, can't traverse 2 levels at once: ```swift { (middlewareAction: MiddlewareAction) -> AppAction in AppAction.firstLevel( FirstLevel.secondLevel(middlewareAction) ) } // this will NOT compile (although a better Prism could solve that, probably): AppAction.firstLevel.secondLevel // You could try, however, to lift twice: .lift(outputAction: FirstLevel.secondLevel) // Notice that first we wrap the middleware value in the second level .lift(outputAction: AppAction.firstLevel) // And then we wrap the first level in the AppAction // The order must be from inside to outside, always. ``` #### Identity, Ignore and Absurd Void: - when Middleware doesn't need State, it can be Void - lift Void using `ignore`, which is `{ (_: Anything) -> Void in }` Never: - when Middleware doesn't need to dispatch actions, it can be Never - lift Never using `absurd`, which is `{ (never: Never) -> Anything in }` Identity: - when some parts of your lift should be unchanged because they are already in the expected type - lift that using `identity`, which is `{ $0 }` Theory behind: Void and Never are dual: - Anything can become Void (terminal object) - Never (initial object) can become Anything - Void has 1 instance possible (it's a singleton) - Never has 0 instances possible - Because nobody can give you Never, you can promise Anything as a challenge. That's why function is called absurd, it's impossible to call it. #### Xcode Snippets: ```swift // Reducer expanded .lift( actionGetter: { (action: AppAction) -> <#LocalAction#>? in action.<#something?.child#> }, stateGetter: { (state: AppState) -> <#LocalState#> in state.<#something.child#> }, stateSetter: { (state: inout AppState, newValue: <#LocalState#>) -> Void in state.<#something.child#> = newValue } ) // Reducer KeyPath: .lift( action: \AppAction.<#something?.child#>, state: \AppState.<#something.child#> ) // Middleware expanded .lift( inputAction: { (action: AppAction) -> <#LocalAction#>? in action.<#something?.child#> }, outputAction: { (local: <#LocalAction#>) -> AppAction in AppAction.<#something(.child(local))#> }, state: { (state: AppState) -> <#LocalState#> in state.<#something.child#> } ) // Middleware KeyPath .lift( inputAction: \AppAction.<#local#>, outputAction: AppAction.<#local#>, // not more than 1 level state: \AppState.<#local#> ) ``` # Architecture This dataflow is, somehow, an implementation of MVC, one that differs significantly from the Apple's MVC for offering a very strict and opinative description of layers' responsibilities and by enforcing the growth of the Model layer, through a better definition of how it should be implemented: in this scenario, the Model is the Store. All your Controller has to do is to forward view actions to the Store and subscribe to state changes, updating the views whenever needed. If this flow doesn't sound like MVC, let's check a picture taken from Apple's website: ![iOS MVC](https://swiftrex.github.io/SwiftRex/markdown/img/CocoaMVC.gif) One important distinction is about the user action: on SwiftRex it's forwarded by the controller and reaches the Store, so the responsibility of updating the state becomes the Store's responsibility now. The rest is pretty much the same, but with a better definition of how the Model operates. ``` โ•ผโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•พ โ•ฑโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ—‰โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฒ โ•ฑโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ—‰โ–‘โ–‘โ—–โ– โ– โ– โ– โ– โ– โ– โ——โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ•ญโ”ƒโ–‘โ•ญโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•ฎโ–‘โ”ƒ โ”‚โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ•ฐโ”ƒโ–‘โ”ƒ โ”‚ UIButton โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”ƒโ–‘โ”ƒ โ•ญโ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”ƒโ–‘โ”ƒโ•ฎ dispatch<Action>(_ action: Action) โ”‚โ”ƒโ–‘โ”ƒ โ”‚UIGestureRecognizerโ”‚โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”ƒโ–‘โ”ƒโ”‚ โ”‚ โ•ฐโ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”ƒโ–‘โ”ƒโ”‚ โ–ผ โ•ญโ”ƒโ–‘โ”ƒ โ”‚viewDidLoadโ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒโ•ฏ โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“ โ”‚โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”‚โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ•ฐโ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚UILabelโ”‚โ—€โ”€ โ”€ โ”€ โ”€ โ” โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ Combine, RxSwift โ”Œ โ”€ โ”€ โ”ป โ”€ โ” โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”ƒโ–‘โ”ƒ or ReactiveSwift State Store โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ•‹โ–‘โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€โ”‚Publisherโ”‚ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ–ผ โ”‚ โ”ƒโ–‘โ”ƒ subscribe(onNext:) โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ–ผ โ”ƒโ–‘โ”ƒ sink(receiveValue:) โ”” โ”€ โ”€ โ”ณ โ”€ โ”˜ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ Diffable โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ assign(to:on:) โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ DataSource โ”‚ โ”‚RxDataSourcesโ”‚ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”›โ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ UICollectionView โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ•ฐโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•ฏโ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ•ฒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฑ โ•ฒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฑ โ•ผโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•พ ``` You can think of Store as a very heavy "Model" layer, completely detached from the View and Controller, and where all the business logic stands. At a first sight it may look like transferring the "Massive" problem from a layer to another, so that's why the Store is nothing but a collection of composable boxes with very well defined roles and, most importantly, restrictions. ``` โ•ผโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•พ โ•ฑโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ—‰โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฒ โ•ฑโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ—‰โ–‘โ–‘โ—–โ– โ– โ– โ– โ– โ– โ– โ——โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ•ญโ”ƒโ–‘โ•ญโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•ฎโ–‘โ”ƒ โ”‚โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ•ฐโ”ƒโ–‘โ”ƒ โ”‚ Button โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”ƒโ–‘โ”ƒ โ”Œ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“ โ•ญโ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”ƒโ–‘โ”ƒโ•ฎ dispatch โ”ƒ โ”ƒโ–‘ โ”‚โ”ƒโ–‘โ”ƒ โ”‚ Toggle โ”‚โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”‚ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€โ–ถ โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถโ”ƒ โ”ƒโ–‘ โ”‚โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”ƒโ–‘โ”ƒโ”‚ view event f: (Event) โ†’ Action app action โ”ƒ โ”ƒโ–‘ โ•ฐโ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”ƒโ–‘โ”ƒโ”‚ โ”‚ โ”‚ โ”ƒ โ”ƒโ–‘ โ•ญโ”ƒโ–‘โ”ƒ โ”‚ onAppear โ”‚โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒโ•ฏ โ”ƒ โ”ƒโ–‘ โ”‚โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ โ”‚ ObservableViewModel โ”‚ โ”ƒ โ”ƒโ–‘ โ”‚โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ•ฐโ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ a projection of โ”‚ projection โ”ƒ Store โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ the actual store โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”ƒ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”Œโ”ƒโ”€ โ”€ โ”€ โ”€ โ”€ โ” โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ @ObservedObject โ”‚โ—€ โ”€ โ”€ โ•‹โ–‘โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ—€โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ—€โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ State โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ view state โ”‚ f: (State) โ†’ View โ”‚ app state โ”‚ Publisher โ”‚ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ State โ”ณ โ”€ โ”€ โ”€ โ”€ โ”€ โ”ƒโ–‘ โ”ƒโ–‘โ”ƒ โ”‚ โ”‚ โ”‚ โ”ƒโ–‘โ”ƒ โ”” โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”€ โ”˜ โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”›โ–‘ โ”ƒโ–‘โ”ƒ โ–ผ โ–ผ โ–ผ โ”ƒโ–‘โ”ƒ โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ โ”ƒโ–‘โ”ƒ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”‚ Text โ”‚ โ”‚ List โ”‚ โ”‚ForEach โ”‚ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ”ƒ โ”ƒโ–‘โ•ฐโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•ฏโ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ”ƒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ”ƒ โ•ฒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–“โ–“โ–“โ–“โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฑ โ•ฒโ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ•ฑ โ•ผโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•พ ``` And what about SwiftUI? Is this architecture a good fit for the new UI framework? In fact, this architecture works even better in SwiftUI, because SwiftUI was inspired by several functional patterns and it's reactive and stateless by conception. It was said multiple times during WWDC 2019 that, in SwiftUI, the **View is a function of the state**, and that we should always aim for single source of truth and the data should always flow in a single direction. ![SwiftUI Unidirectional Flow](https://swiftrex.github.io/SwiftRex/markdown/img/wwdc2019-226-01.jpg) # Installation ## CocoaPods Create or modify the Podfile at the root folder of your project. Your settings will depend on the ReactiveFramework of your choice. For Combine: ```ruby # Podfile source 'https://github.com/CocoaPods/Specs.git' use_frameworks! target 'MyAppTarget' do pod 'CombineRex' end ``` For RxSwift: ```ruby # Podfile source 'https://github.com/CocoaPods/Specs.git' use_frameworks! target 'MyAppTarget' do pod 'RxSwiftRex' end ``` For ReactiveSwift: ```ruby # Podfile source 'https://github.com/CocoaPods/Specs.git' use_frameworks! target 'MyAppTarget' do pod 'ReactiveSwiftRex' end ``` As seen above, some lines are optional because the final Podspecs already include the correct dependencies. Then, all you must do is install your pods and open the `.xcworkspace` instead of the `.xcodeproj` file: ```shell $ pod install $ xed . ``` ## Swift Package Manager Create or modify the Package.swift at the root folder of your project. You can use the automatic linking mode (static/dynamic), or use the project with suffix Dynamic to force dynamic linking and overcome current Xcode limitations to resolve diamond dependency issues. If you use it from only one target, automatic mode should be fine. Combine, automatic linking mode: ```swift // swift-tools-version:5.5 import PackageDescription let package = Package( name: "MyApp", platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)], products: [ .executable(name: "MyApp", targets: ["MyApp"]) ], dependencies: [ .package(url: "https://github.com/SwiftRex/SwiftRex.git", from: "0.8.12") ], targets: [ .target(name: "MyApp", dependencies: [.product(name: "CombineRex", package: "SwiftRex")]) ] ) ``` RxSwift, automatic linking mode: ```swift // swift-tools-version:5.5 import PackageDescription let package = Package( name: "MyApp", platforms: [.macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v3)], products: [ .executable(name: "MyApp", targets: ["MyApp"]) ], dependencies: [ .package(url: "https://github.com/SwiftRex/SwiftRex.git", from: "0.8.12") ], targets: [ .target(name: "MyApp", dependencies: [.product(name: "RxSwiftRex", package: "SwiftRex")]) ] ) ``` ReactiveSwift, automatic linking mode: ```swift // swift-tools-version:5.5 import PackageDescription let package = Package( name: "MyApp", platforms: [.macOS(.v10_10), .iOS(.v8), .tvOS(.v9), .watchOS(.v3)], products: [ .executable(name: "MyApp", targets: ["MyApp"]) ], dependencies: [ .package(url: "https://github.com/SwiftRex/SwiftRex.git", from: "0.8.12") ], targets: [ .target(name: "MyApp", dependencies: [.product(name: "ReactiveSwiftRex", package: "SwiftRex")]) ] ) ``` Combine, dynamic linking mode (use similar approach of appending "Dynamic" also for RxSwift or ReactiveSwift products): ```swift // swift-tools-version:5.5 import PackageDescription let package = Package( name: "MyApp", platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)], products: [ .executable(name: "MyApp", targets: ["MyApp"]) ], dependencies: [ .package(url: "https://github.com/SwiftRex/SwiftRex.git", from: "0.8.12") ], targets: [ .target(name: "MyApp", dependencies: [.product(name: "CombineRexDynamic", package: "SwiftRex")]) ] ) ``` Then you can either building on the terminal or use Xcode 11 or higher that now supports SPM natively. ```shell $ swift build $ xed . ``` > **_IMPORTANT:_** For Xcode 12, please use the version 0.8.8. Versions 0.9.0 and above require Xcode 13. ## Carthage Carthage is no longer supported due to lack of interest and high maintenance effort. In case this is REALLY critical for you, please open a Github issue and let us know, we will evaluate the possibility to bring it back. In meantime you can check last Carthage compatible version, which was 0.7.1, and eventually target that version until we come up with a better solution.