branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>apply plugin: 'com.android.dynamic-feature' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 28 defaultConfig { minSdkVersion 21 targetSdkVersion 28 } buildTypes{ release{ proguardFiles 'proguard-rules-dynamic-features.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation project(':app') } <file_sep>package com.example.appbundlesample import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.google.android.play.core.splitinstall.SplitInstallException import com.google.android.play.core.splitinstall.SplitInstallManager import com.google.android.play.core.splitinstall.SplitInstallManagerFactory import com.google.android.play.core.splitinstall.SplitInstallRequest import com.google.android.play.core.splitinstall.model.SplitInstallErrorCode import com.google.android.play.core.splitinstall.model.SplitInstallSessionStatus import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener { private val splitInstallManager by lazy { SplitInstallManagerFactory.create(this) } private lateinit var request: SplitInstallRequest private var sessionId = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initComponent() } override fun onClick(v: View?) { when (v?.id) { R.id.button_download_feature_1 -> downloadFeatureModule(DYNAMIC_FEATURE_MODULE_1) R.id.button_goto_feature_1 -> startDynamicFeature(CLASS_NAME_MODULE_1) R.id.button_download_feature_2 -> downloadFeatureModule(DYNAMIC_FEATURE_MODULE_2) R.id.button_goto_feature_2 -> startDynamicFeature(CLASS_NAME_MODULE_2) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == REQUIRES_USER_CONFIRMATION) { // Handle the user's decision Log.d("TAG", "ResultCode: $resultCode") } } private fun initComponent() { button_download_feature_1.setOnClickListener(this) button_goto_feature_1.setOnClickListener(this) button_download_feature_2.setOnClickListener(this) button_goto_feature_2.setOnClickListener(this) } /* Option 1: Use SplitInstallManager.startInstall(). Require App in Foreground*/ private fun downloadFeatureModule(nameModule: String) { request = SplitInstallRequest.newBuilder() .addModule(nameModule) .build() /* * Can instead by splitInstallManager.deferredInstall() * Purpose: If you want to defer installation for when the app is in background */ splitInstallManager.startInstall(request) .addOnSuccessListener { sessionId -> this.sessionId = sessionId Log.d("TAG", "SessionId: ${this.sessionId}") } .addOnFailureListener { exception -> when (((exception as SplitInstallException).errorCode)) { SplitInstallErrorCode.NETWORK_ERROR -> showMessage(resources.getString(R.string.network_error)) SplitInstallErrorCode.MODULE_UNAVAILABLE -> showMessage(resources.getString(R.string.module_unavailable)) SplitInstallErrorCode.INVALID_REQUEST -> showMessage(resources.getString(R.string.invalid_request)) SplitInstallErrorCode.ACTIVE_SESSIONS_LIMIT_EXCEEDED -> checkForActiveDownloads() /*,etc...*/ } } .addOnCompleteListener { } listenRequest() } /* * Listen request and handle state updates */ private fun listenRequest() { /*Listen request status updates*/ this.splitInstallManager.registerListener { state -> if (state.errorCode() == SplitInstallErrorCode.SERVICE_DIED) { // Retry the request return@registerListener } if (state.sessionId() == this.sessionId) { when (state.status()) { SplitInstallSessionStatus.PENDING -> { // The request has been accepted and the download should start soon. } SplitInstallSessionStatus.DOWNLOADING -> { showMessage(resources.getString(R.string.downloading)) // update progressBar val totalBytes = state.totalBytesToDownload() val progress = state.bytesDownloaded() } SplitInstallSessionStatus.DOWNLOADED -> showMessage(resources.getString(R.string.downloaded)) SplitInstallSessionStatus.INSTALLED -> { // After installed, you can start accessing it. Fire an Intent showMessage(resources.getString(R.string.installed)) } SplitInstallSessionStatus.INSTALLING -> showMessage(resources.getString(R.string.installing)) SplitInstallSessionStatus.CANCELING -> showMessage(resources.getString(R.string.canceling)) SplitInstallSessionStatus.CANCELED -> showMessage(resources.getString(R.string.installed)) SplitInstallSessionStatus.FAILED -> { // Retry the request } SplitInstallSessionStatus.REQUIRES_USER_CONFIRMATION -> { /* * Displays a dialog for user "Download" or "Cancel" >10MB * Params: * + Download -> request status changes to: PENDING * + Cancel -> CANCELED * + Do not choose -> requestCode default */ splitInstallManager.startConfirmationDialogForResult(state, this, REQUIRES_USER_CONFIRMATION) } } } } } /*Cancel a request before it is installed*/ private fun cancelRequest() { splitInstallManager.cancelInstall(this.sessionId) } /*unregister the listener*/ private fun unregister() { splitInstallManager.unregisterListener { } } /*To check currently installed dynamic feature modules on the device*/ private fun checkFeatureInstalled() { val installedModules = splitInstallManager.installedModules Log.d("TAG", "Number: ${installedModules.size}") } /*To uninstall module*/ private fun uninstallModule() { splitInstallManager.deferredUninstall(listOf(DYNAMIC_FEATURE_MODULE_2)) } /*Check if there are nay request that are still downloading*/ private fun checkForActiveDownloads() { splitInstallManager.sessionStates .addOnCompleteListener { task -> if (task.isSuccessful) { for (state in task.result) { if (state.status() == SplitInstallSessionStatus.DOWNLOADING) { // Dang co yeu cau tai xuong cancelRequest() } } } } } private fun startDynamicFeature(className: String) { Intent(this@MainActivity, Class.forName(className)).apply { startActivity(this) } } private fun Context.showMessage(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() companion object { private const val DYNAMIC_FEATURE_MODULE_1 = "dynamic_feature" private const val DYNAMIC_FEATURE_MODULE_2 = "dynamic_feature2" private const val CLASS_NAME_MODULE_1 = "com.example.dynamic_feature.DynamicActivity" private const val CLASS_NAME_MODULE_2 = "com.example.dynamic_feature2.MainActivity" private const val REQUIRES_USER_CONFIRMATION = 1 } } <file_sep># App Bundles-Dynamic Deliver # Phần 1: App Bundles - App Bundles là một định dạng upload mới bao gồm tất cả các code và resource được compile từ app, không tạo APK. - Publish với App Bundle cũng tăng giới hạn kích thước app lên 150MB mà không cần phải sử dụng APK. Đó là kích thước tải xuống chứ không phải kích thước xuất bản. ## Lợi ích của App Bundle - Dynamic Delivery: Kích thước APK nhỏ hơn. - Không cần tạo và quản lý thủ công nhiều APK - Dynamic Feature Module (Phân phối động): Cho phép người dùng tải xuống và cài đặt thêm các tính năng khi có yêu cầu. Điều này cho phép chúng ta làm giảm kích thước ban đầu của app. Các tính năng này nằm ở các module khác nhau và sử dụng thư viện <b>Play Core Library</b> để tải xuống các module này. - Support Instant App: Người dùng có thể chạy các feature module mà không cần phải cài đặt app. Tham khảo Instant App <a href="https://viblo.asia/p/android-instant-app-buoc-dot-pha-cho-trai-nghiem-nguoi-dung-XL6lAA0mlek">Tại đây</a> ## Định dạng file aab và apks ### File aab - App Bundle là một file (có phần mở rộng .aab, không thể cài đặt trên device) mà bản upload lên Google Play để được support *Dynamic Delivery*. - App Bundle là các tệp nhị phân được ký kết, sắp xếp code và resource trong module. <img src="images/app_bundle_format.png"> - Các phần được tô màu xanh như drawable, values, lib đại diện cho code và resource mà Google Play sử dụng để tạo APK cấu hình cho từng Module. - Chi tiết: + base/, feature1/, feature2/: Đại diện cho một module khác nhau của app. + BUNDLE-METADATA/: Thư mục này bao gồm các file metadata chứa các thông tin tools và app stores. + Module Protocol Buffer(.pb): Các file này cung cấp metadata để mô tả nội dung của từng module cho app store.Ví dụ: *BundleConfig.pb* cung cấp thông tin của chính nó chẳng hạn như version nào của các tool được sử dụng để xây dựng app bundle *native.pb*, *resources.pb* (resource.arac trong APK) mô tả code và resources trong mỗi module, *assets.pb* sẽ chỉ sử dụng khi bạn đang sử dụng tài nguyên trong app. + manifest/: *app bundle* sẽ lưu trữ các file AndroidManifest.xml của mỗi module trong thư mục riêng này. + dex/: *app bundle* sẽ lưu trữ các file DEX cho mỗi module trong thư mục riêng này. + res/, lib/, assets/: Giống trong APK. + root/: Dùng để lưu trữ file root của bất kỳ APK có chứa module mà thư mục này được đặt. - *Cẩn thận*: Nếu nội dung trong các file *root* xung đột với các file và thư mục khác trong root APK, Play Console sẽ từ chối toàn bộ app bundle gửi lên . Ví dụ: root/lib nó sẽ xung đột với thư mục lib đã tồn tại trong mỗi APK. - *Note*: Nếu sử dụng *product flavor* để tạo nhiều version cho app từ một app project và mỗi version sử dụng applicationID duy nhất, bạn cần phải tạo một App Bundle riêng biệt cho từng version. ## Building và Distributing App Bundle - Config: <img src="images/config_deploy_app_bundle.png"/> - Bấm *Run* để build và deploy app trên device. - *Note*: Android Studio yêu cầu AAPT2 để build *app bundle* (mặc định được bật cho các project mới). Để đảm bảo nó được bật trên project hiện có, thêm *android.enableAapt2=true* trong *gradle.properties* và restart lại Gradle bằng *./gradlew --stop* từ command line. - Generate *App Bundle* bằng cách sử dụng Android Studio từ 3.2 trở lên hoặc Console *./gradlew bundle*. - *App Bundle* được tạo ra sẽ lưu trữ trong *app/build/outputs/bundle/buildVariant/bundle.aab* - Khi build *app bundle*, mặc định tất cả các phân tách sẽ được generate. Ta có thể thiết lập những phần nào sẽ được đóng gói vào APK bằng cách sử dụng khối bundle{} trong khối android{} <img src="images/setup_bundle_generate.png"/> <img src="images/build_app_bundle.png"/> ## Bundle tool - Là công cụ mà Gradle, Android Studio, Google Play sử dụng để xây dựng *App Bundle* hoặc chuyển đổi *App Bundle* thành APK triển khai trên device. ### Generate APKs từ App Bundle - Generate apks từ *app bundle*: *java -jar ./bundletool-all-0.10.0.jar build-apks --bundle=./app.aab --output=./out.apks* <img src="images/result_apk_set.png"/> - Cài vào device: *java -jar ./bundletool-all-0.10.0.jar install-apks --apks=./out.apks* ### Generate APKs cho một device cụ thể - Nếu không muốn build một bộ APk cho tất cả các cấu hình device, có thể tạo APK nhắm mục tiêu cấu hình thiết bị cụ thể. + Thiết bị được kết nối: *java -jar ./bundletool-all-0.10.0.jar build-apks --connected-device --bundle=./app.aab --output=./out_specific.apks* <img src="images/result_apk_connected.png"/> + Sử dụng tệp Json mô tả cấu hình device: java -jar ./bundletool-all-0.10.0.jar build-apks --device-spec=./pixel1.json --bundle=./app.aab --output=./out_specific_json.apks <img src="images/device_specific_json.png"/> <img src="images/result_apk_connected.png"/> # Phần 2: Dynamic Deliver - Mô hình phục vụ ứng dụng Google Play, sử dụng *App Bundle* để tạo ra APK nhỏ hơn, tối ưu hóa cho từng cấu hình device. Vì vậy, người dùng chỉ cần download code và resouces cần thiết để chạy app. Bạn không cần phải xây dựng và quản lý nhiều APK để hỗ trợ cho các device khác nhau nữa. ## Dynamic Deliver với split APKs. - *split APK* là một thành phần cơ bản của *Dynamic Deliver* có sẵn từ Android 5.0 (API level 21) - cơ chế phân tách APK, nó bao gồm *DEX bytecode* được biên dịch, *resources* và *Android manifest*. Có thể cài đặt nhiều *split APK* và nó xuất hiện như app được cài đặt trên device. <img src="images/dynamic_split_apk.png"> - Lợi ích của *split APK* là các APK này nhỏ hơn, tối ưu hơn với từng cấu hình device mà có đầy đủ chức năng cần thiết cho người dùng, và người dùng có thể cài đặt các gói riêng biệt nếu cần. + Base APK: Là những phần chung cho tất cả các cấu hình thiết bị như là manifest, dex, ngôn ngữ và bất kỳ phần nào giống nhau cho tất cả device. - Các loại APK + Configuration APKs: Chỉ chứa các thư viện và resources cho một cấu hình thiết bị nhất định, tối ưu hóa nội dung APK dựa theo: ngôn ngữ, mật độ màn hình, kiến trúc CPU. + Dynamic Feature APKs: Chứa code và resources cho một feature, không bắt buộc khi cài app lần đầu tiên nhưng có thể được cài đặt sau khi người dùng yêu cầu. - Cách hoạt động: <img src="images/split_apk.png"> + Ví dụ: Khi user device có cấu hình: x86, hdpi, en thì APK tương ứng là (base + x86 + hdpi + en).apk + Nếu nguời dùng thay đổi cấu hình device ở thời điểm nào đó (chẳng hạn như thay đổi ngôn ngữ), PlayStore sẽ nhận ra điều này và sẽ tải xuống các phần chia cấu hình mới cho tất cả các ứng dụng sử dụng *split APK* trên thiết bị. Nếu device không có internet thì nó sẽ tải xuống sau. - Đối với các device dưới Android 5.0 không hỗ trợ tải xuống và cài đặt *split APKs*, Google Play sẽ thay thế nó bằng một APK duy nhất gọi là multi-APK. Thay vì chia tách ra, APK độc lập sẽ được tạo phù hợp với ma trận kết hợp các kiến trúc và mật độ thiết bị khác nhau. Theo cách tiếp cận này thì tất cả các ngôn ngữ sẽ nằm trong APK vì ma trận sẽ trở nên quá lớn khi kết hợp. <img src="images/lower21.png"> ## Dynamic feature module - Cho phép tách các tính năng nhất định khỏi module cơ sở của ứng dụng và đưa chúng vào *app bundle*. Dựa vào Dynamic Delivery, sau này có thể download và install các tính năng đó theo yêu cầu của. ### Tạo Dynamic Feature Module - Yêu cầu sử dụng Android Studio từ 3.2 trở lên: File -> New -> New Module -> Dynamic Feature Module -> Next - <b> Note : Before creating a dynamic module, you have to create you app bundle. </b> <img src="images/manifest_feature_module.png"/> - Note: *If the dynamic feature module generates no DEX files, use hasCode va replace* - Thiết lập mối quan hệ với base module: - Android sử dụng một plugin mới "com.android.dynamic-feature" để xây dựng dynamic feature module. Chỉ định tên của base module, vì vậy chúng ta có thể sử dụng các chức năng của base module. <img src="images/config_dynamic_module.png"/> - Cần khai báo tất cả các dynamic feature modules trong build.gradle của base module. Để cho Gradle biết bạn cần tất cả resources và code khả dụng cho các dynamic modules khác. <img src="images/relate_base_module.png"/> ### Download modules with the Play Core Library - Quy trình download: <img src="images/download_dynamic_feature.png"/> - Thêm thư viện Play Core Library: <img src="images/lib_play_core.png"/> - Request an on demand module: Cần chỉ định rõ tên của module được xác định bởi thuộc tính *split* trong module's manifest. <img src="images/request_modules.png"/> + Defer installation of on demand modules: Trì hoãn cài đặt khi ứng dụng ở background (vd: tải xuống một số hình ảnh quảng cáo cho việc cài đặt app sau này). Với cách này thì ta không thể theo dõi tiến trình. Vì vậy trước khi truy cập vào một module đã chỉ định cài đặt trì hoãn, ta nên kiểm tra module đã được cài đặt hay chưa. <img src="images/defer_install.png"/> - Theo dõi trạng thái yêu cầu: Để cập nhật progress, xử lý lỗi, Xử lý intent sau khi cài đặt <img src="images/listen_state.png"/> - Xử lý lỗi khi download hoặc cài đặt module: Nếu xảy ra lỗi, hãy xem xét hiển thị hộp thoại cung cấp 2 tùy chọn cho người dùng: *Try again* và *Cancel* <img src="images/handle_error.png"/> - Xử lý trạng thái update: <img src="images/handle_state_update.png"/> - Trong một vài trường hợp, cần có xác nhận của user. Ví dụ: Tải 1 lượng lớn data (>10MB) <img src="images/user_confirmation.png"/> <img src="images/callback_confirmation.png"/> - Hủy yêu cầu cài đặt: <img src="images/cancel_install_request.png"/> - Quản lý các module đã cài đặt: <img src="images/installed_module.png"/> - Uninstall modules: <img src="images/uninstall_module.png"/> ## Tham khảo - https://developer.android.com/guide/app-bundle - https://medium.com/google-developer-experts/exploring-the-android-app-bundle-ca16846fa3d7 - https://medium.com/mindorks/android-app-bundle-6c65ce8105a1
b828e53bbf925d56421bb6adc65a62cb551a4470
[ "Markdown", "Kotlin", "Gradle" ]
3
Gradle
hoangbn-1772/AppBundles-DynamicDeliver
e601e4cce28cda6a2372fc2d34c7a6ed79799205
2a41d5fe2ddfcd9a92035dec0d09b4a9d7ebdb93
refs/heads/master
<repo_name>jelastic-jps/docker<file_sep>/addons/le-ssl-deploy-hook.js nodeId = getParam('nodeId'); envName = getParam('envName'); envAppid = getParam('envAppid'); envDomain = getParam('envDomain'); scriptName = getParam('action') == 'uninstall' ? 'undeployLE.sh' : 'deployLE.sh'; resp = jelastic.environment.control.GetNodeInfo(envAppid, session, nodeId); if (resp.result != 0) return resp; if (resp.node && resp.node.nodeGroup == "bl") return {result: 0} //getting first custom domain customDomains = (getParam('customDomains') || "").replace(/^\s+|\s+$/gm , "").split(/\s*[;,\s]\s*/).shift(); domain = customDomains || envDomain; //executing custom deployment hook script on master node resp = jelastic.env.control.ExecCmdById(envName, session, nodeId, toJSON([{ command:'/bin/bash $([ -f "~/' + scriptName + '" ] && echo "~/" || echo "/var/lib/jelastic/keys/letsencrypt/")' + scriptName}]), true); return resp; <file_sep>/addons/scripts/attach-external-ip.js var resp = jelastic.billing.account.GetQuotas(appid, session, [ 'environment.externalip.enabled', 'environment.externalip.maxcount', 'environment.externalip.maxcount.per.node' ].join(";")); if (resp.result != 0) return resp; var ipQuotas = resp, resp = {result: 0}; if (ipQuotas.array[0].value != 0 && ipQuotas.array[1].value > 0 && ipQuotas.array[2].value > 0) { var r = jelastic.env.control.GetEnvInfo('${env.name}', session), nodes = []; if (r.result != 0) return r; var targetGroup = "cp"; for (var i = r.nodes.length; i--;) if (r.nodes[i].nodeGroup == targetGroup) nodes.push(r.nodes[i].id); resp.onAfterReturn = [ "env.binder.AttachExtIp["+nodes.join(',')+"]" ] }; return resp; <file_sep>/docker-engine/text/description.md This package provides standalone Docker Engine. You can use it for performing *docker build*, *docker run*, *docker-compose up* and *docker swarm join*. For using *docker swarm* and *docker stack* please review [dedicated package](https://github.com/jelastic-jps/docker/tree/master/docker-swarm) of Docker Swarm cluster.
be36329950a86ad5f59a16c85d8e931a8c85db14
[ "JavaScript", "Markdown" ]
3
JavaScript
jelastic-jps/docker
616e24bb265d9096786d3dadeeaff53d90edb6fa
a0d30e400c10a8c20888389b2f809cdc49deb705
refs/heads/master
<repo_name>Elukoye/Daily_Coding_Challenges<file_sep>/unique_staircase.rb # Daily Coding Problem: Problem #12 [Hard] # This problem was asked by Amazon. # There exists a staircase with N steps, # and you can climb up either 1 or 2 steps at a time. # Given N, write a function that returns the number of unique ways you can climb the staircase. # The order of the steps matters. # For example, if N is 4, then there are 5 unique ways: # 1, 1, 1, 1 # 2, 1, 1 # 1, 2, 1 # 1, 1, 2 # 2, 2 # What if, instead of being able to climb 1 or 2 steps at a time, # you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, # you could climb 1, 3, or 5 steps at a time.<file_sep>/deserilize_tree.rb # This problem was asked by Google. # Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. # For example, given the following Node class # class Node: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # The following test should pass: # node = Node('root', Node('left', Node('left.left')), Node('right')) # assert deserialize(serialize(node)).left.left.val == 'left.left'<file_sep>/encoded_msg.rb # Daily Coding Problem: Problem #7 [Medium] # This problem was asked by Facebook. # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. For example, '001' is not allowed. <file_sep>/cons_pair.rb # This problem was asked by <NAME>. # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. # For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of cons: # def cons(a, b): # def pair(f): # return f(a, b) # return pair # Implement car and cdr.<file_sep>/xor.rb # Good morning! Here's your coding interview problem for today. # This problem was asked by Google. # An XOR linked list is a more memory efficient doubly linked list. # Instead of each node holding next and prev fields, it holds a field named both, # which is an XOR of the next node and the previous node. Implement an XOR linked list; # it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. # If using a language that has no pointers (such as Python), # you can assume you have access to get_pointer and dereference_pointer functions that # converts between nodes and memory addresses. <file_sep>/prefix.rb # Daily Coding Problem: Problem #11 [Medium] # Implement an autocomplete system. That is, # given a query string s and a set of all possible query strings, # return all strings in the set that have s as a prefix. # For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal]. # Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.<file_sep>/missing_positive_int.rb # This problem was asked by Stripe. # Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, # find the lowest positive integer that does not exist in the array. # The array can contain duplicates and negative numbers as well. # For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. # You can modify the input array in-place.<file_sep>/unival_tree.rb # Daily Coding Problem: Problem #8 [Easy] # This problem was asked by Google. # A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value. # Given the root to a binary tree, count the number of unival subtrees. # For example, the following tree has 5 unival subtrees: # 0 # / \ # 1 0 # / \ # 1 0 # / \ # 1 1<file_sep>/job_schedular.rb # Daily Coding Problem: Problem #10 [Medium] # This problem was asked by Apple. # Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.<file_sep>/largest_sum_non_adjacent.rb # Daily Coding Problem: Problem #9 [Hard] # This problem was asked by Airbnb. # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. # Numbers can be 0 or negative. # For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, # since we pick 5 and 5. # Follow-up: Can you do this in O(N) time and constant space?
0a70131412094fd3ad491492970943edb36e3e12
[ "Ruby" ]
10
Ruby
Elukoye/Daily_Coding_Challenges
f76cc59b7b3c7714eefad7627c1d39ae08fd0ebc
dd804772c3608240fb836f46c9773c7faed8146c
refs/heads/master
<repo_name>pasudo123/SpringBoot-BoardSample<file_sep>/settings.gradle rootProject.name = 'board-core' <file_sep>/src/main/java/edu/pasudo123/board/core/comment/api/CommentXXController.java package edu.pasudo123.board.core.comment.api; import edu.pasudo123.board.core.comment.dto.CommentOneResponseDto; import edu.pasudo123.board.core.comment.dto.CommentXXOneRequestDto; import edu.pasudo123.board.core.comment.service.CommentCreateService; import edu.pasudo123.board.core.comment.service.CommentDeleteService; import edu.pasudo123.board.core.comment.service.CommentUpdateService; import edu.pasudo123.board.core.config.auth.CurrentUser; import edu.pasudo123.board.core.config.auth.CustomOAuth2User; import edu.pasudo123.board.core.global.exception.ValidationException; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** * Created by pasudo123 on 2019-08-15 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> * * 코멘트에 대한 코멘트 api (CUD) * **/ @RestController @RequestMapping("/api") @RequiredArgsConstructor public class CommentXXController { private final CommentCreateService commentCreateService; private final CommentUpdateService commentUpdateService; private final CommentDeleteService commentDeleteService; @PostMapping("comment-xx") public ResponseEntity<CommentOneResponseDto> saveCommentXX(@CurrentUser CustomOAuth2User customOAuth2User, @Valid @RequestBody CommentXXOneRequestDto dto, BindingResult bindingResult){ if(bindingResult.hasErrors()){ throw new ValidationException("Validation Result Failed.", bindingResult); } return ResponseEntity.ok().body(commentCreateService.addNewCommentXX(dto, customOAuth2User.getUser())); } } <file_sep>/src/main/java/edu/pasudo123/board/core/config/auth/CustomOAuth2User.java package edu.pasudo123.board.core.config.auth; import edu.pasudo123.board.core.user.model.User; import lombok.Builder; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.oauth2.core.user.OAuth2User; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; /** * Created by pasudo123 on 2019-08-09 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public class CustomOAuth2User implements OAuth2User, Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final User user; private final Set<GrantedAuthority> authorities; private final Map<String, Object> attributes; private final String nameAttributeKey; @Builder private CustomOAuth2User(User user, Set<GrantedAuthority> authorities, Map<String, Object> attributes, String nameAttributeKey) { this.user = user; this.authorities = authorities; this.attributes = attributes; this.nameAttributeKey = nameAttributeKey; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public Map<String, Object> getAttributes() { return this.attributes; } @Override public String getName() { return this.user.getUserRegistrationId(); } public User getUser() { return this.user; } } <file_sep>/src/main/java/edu/pasudo123/board/core/article/model/Article.java package edu.pasudo123.board.core.article.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import edu.pasudo123.board.core.article.dto.ArticleOneRequestDto; import edu.pasudo123.board.core.comment.model.Comment; import edu.pasudo123.board.core.common.BaseTimeEntity; import edu.pasudo123.board.core.user.model.User; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.List; /** * Created by pasudo123 on 2019-07-27 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter @NoArgsConstructor(access = AccessLevel.PROTECTED) @Entity @Table(name = "ARTICLE", indexes = { @Index(name = "idx_article_1", columnList = "descIndex"), @Index(name = "idx_article_2", columnList = "registrationDate") }) public class Article extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, length = 200) private String title; @Enumerated(EnumType.STRING) @Column(nullable = false, length = 50) private ArticleType articleType; @Column(nullable = false, length = 1000) private String content; @JsonManagedReference @OneToMany(mappedBy = "article", fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) private List<Comment> commentList = new ArrayList<>(); @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}) @JoinColumn(name = "USER_ID") private User writerUser; private LocalDateTime registrationDateTime; private LocalDate registrationDate; private long descIndex; @Builder public Article(String title, ArticleType articleType, String content, User writerUser){ this.title = title; this.articleType = articleType; this.content = content; this.writerUser = writerUser; this.registrationDateTime = LocalDateTime.now(); this.registrationDate = registrationDateTime.toLocalDate(); this.descIndex = toMillisecond(registrationDateTime); } private long toMillisecond(LocalDateTime registrationDateTime){ return ZonedDateTime.of(registrationDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli(); } public void updateArticle(ArticleOneRequestDto dto){ this.title = dto.getTitle(); this.articleType = dto.getArticleType(); this.content = dto.getContent(); } public void setWriterUser(User user){ this.writerUser = user; getWriterUser().addNewArticle(this); } public void addNewComment(Comment comment){ getCommentList().add(comment); comment.setArticle(this); } public void removeComment(Comment comment){ if(commentList == null || commentList.size() == 0){ return; } getCommentList().remove(comment); } }<file_sep>/src/main/java/edu/pasudo123/board/core/comment/service/impl/CommentCreateServiceImpl.java package edu.pasudo123.board.core.comment.service.impl; import edu.pasudo123.board.core.article.model.Article; import edu.pasudo123.board.core.article.service.ArticleExternalFindService; import edu.pasudo123.board.core.comment.dto.CommentOneRequestDto; import edu.pasudo123.board.core.comment.dto.CommentOneResponseDto; import edu.pasudo123.board.core.comment.dto.CommentXXOneRequestDto; import edu.pasudo123.board.core.comment.model.Comment; import edu.pasudo123.board.core.comment.repository.CommentRepository; import edu.pasudo123.board.core.comment.service.CommentCreateService; import edu.pasudo123.board.core.comment.service.CommentExternalFindService; import edu.pasudo123.board.core.user.model.User; import edu.pasudo123.board.core.user.service.UserExternalFindService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Created by pasudo123 on 2019-08-11 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Service @RequiredArgsConstructor public class CommentCreateServiceImpl implements CommentCreateService { private final UserExternalFindService userExternalFindService; private final ArticleExternalFindService articleExternalService; private final CommentExternalFindService commentExternalFindService; private final CommentRepository commentRepository; @Transactional @Override public CommentOneResponseDto addNewComment(CommentOneRequestDto dto, User currentUser) { Comment comment = dto.toEntity(); /** 아티클 X 코멘트 :: Select Query **/ Article article = articleExternalService.findOneById(dto.getArticleId()); article.addNewComment(comment); /** 코멘트 X 유저 :: Select Query **/ User foundUser = userExternalFindService.findByUserRegistrationId(currentUser.getUserRegistrationId()); comment.setWriterUser(foundUser); commentRepository.save(comment); return new CommentOneResponseDto(comment); } @Transactional @Override public CommentOneResponseDto addNewCommentXX(CommentXXOneRequestDto dto, User currentUser) { Comment comment = dto.toEntity(); /** 코멘트 X 코멘트 **/ Comment parentComment = commentExternalFindService.findOneById(dto.getCommentId()); parentComment.addNewChildComment(comment); /** 작성유저 X 코멘트 **/ User foundUser = userExternalFindService.findByUserRegistrationId(currentUser.getUserRegistrationId()); comment.setWriterUser(foundUser); commentRepository.save(comment); return new CommentOneResponseDto(comment); } }<file_sep>/src/main/java/edu/pasudo123/board/core/comment/service/CommentCreateService.java package edu.pasudo123.board.core.comment.service; import edu.pasudo123.board.core.comment.dto.CommentOneRequestDto; import edu.pasudo123.board.core.comment.dto.CommentOneResponseDto; import edu.pasudo123.board.core.comment.dto.CommentXXOneRequestDto; import edu.pasudo123.board.core.user.model.User; /** * Created by pasudo123 on 2019-08-11 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public interface CommentCreateService { CommentOneResponseDto addNewComment(CommentOneRequestDto dto, User currentUser); CommentOneResponseDto addNewCommentXX(CommentXXOneRequestDto dto, User currentUser); } <file_sep>/src/main/java/edu/pasudo123/board/core/config/JpaAuditingConfiguration.java package edu.pasudo123.board.core.config; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; /** * Created by pasudo123 on 2019-07-27 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Configuration @EnableJpaAuditing public class JpaAuditingConfiguration { /** CreatedBy 사용 안하기 **/ // @Bean // public AuditorAware<String> auditorAware(){ // return new JpaAuditorAware(); // } } <file_sep>/src/main/java/edu/pasudo123/board/core/user/service/UserCreateService.java package edu.pasudo123.board.core.user.service; import edu.pasudo123.board.core.article.model.Article; import edu.pasudo123.board.core.comment.model.Comment; import edu.pasudo123.board.core.user.model.User; /** * Created by pasudo123 on 2019-08-10 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public interface UserCreateService { void addNewMyArticle(User user, Article article); void addNewMyComment(User user, Comment comment); } <file_sep>/src/main/java/edu/pasudo123/board/core/user/api/UserAuthController.java package edu.pasudo123.board.core.user.api; import edu.pasudo123.board.core.config.auth.CurrentUser; import edu.pasudo123.board.core.config.auth.CustomOAuth2User; import edu.pasudo123.board.core.user.dto.UserDto; import edu.pasudo123.board.core.user.model.User; import edu.pasudo123.board.core.user.service.UserFindService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by pasudo123 on 2019-08-11 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @RestController public class UserAuthController { @GetMapping("/auth/current-user") public ResponseEntity<UserDto> currentUser(@CurrentUser CustomOAuth2User currentUser){ User user = currentUser.getUser(); return ResponseEntity.ok().body(new UserDto(user)); } } <file_sep>/src/main/java/edu/pasudo123/board/core/config/JpaAuditorAware.java package edu.pasudo123.board.core.config; import edu.pasudo123.board.core.config.auth.CustomOAuth2User; import org.springframework.data.domain.AuditorAware; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import java.util.Optional; /** * Created by pasudo123 on 2019-08-08 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Component public class JpaAuditorAware implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication instanceof AnonymousAuthenticationToken) { return Optional.empty(); } CustomOAuth2User oAuth2User = (CustomOAuth2User) authentication.getPrincipal(); /** oAuth2User 의 실제 이름이 아닌, unique 한 userId 값 **/ return Optional.ofNullable(oAuth2User.getName()); } } <file_sep>/frontend/src/store/modules/comment.module.js import instance from '@/config/request' import {createHelpers} from 'vuex-map-fields' const {getCommentFields, updateCommentFields} = createHelpers({ getterType: `getCommentFields`, mutationType: `updateCommentFields` }); export default { state: { }, actions: { createComment({commit}, payload){ return new Promise((resolve) => { instance.post(`/api/comment`, payload).then((response) => { resolve(response); }).catch((error) => { console.error(`댓글 등록 시 에러 발생 : `); console.error(error.response.data); }) }); }, deleteComment({commit}, commentId){ return new Promise((resolve) => { instance.delete(`/api/comment/${commentId}`).then((response) => { resolve(response); }).catch((error) => { console.error(`댓글 삭제 시 에러 발생 : `); console.error(error.response.data); }) }); }, modifyComment({commit}, params){ let commentId = params.commentId; const payload = {}; payload.articleId = params.articleId; payload.comment = params.comment; return new Promise((resolve) => { instance.patch(`/api/comment/${commentId}`, payload).then((response) => { resolve(response); }).catch((error) => { console.error(`댓글 수정 시 에러 발생 : `); console.error(error.response.data); }) }); } }, mutations: { updateCommentFields }, getters: { getCommentFields } } <file_sep>/src/main/java/edu/pasudo123/board/core/config/auth/CurrentUser.java package edu.pasudo123.board.core.config.auth; import org.springframework.security.core.annotation.AuthenticationPrincipal; import java.lang.annotation.*; /** * Created by pasudo123 on 2019-08-08 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @AuthenticationPrincipal public @interface CurrentUser { } <file_sep>/src/main/java/edu/pasudo123/board/core/comment/service/impl/CommentExternalFindServiceImpl.java package edu.pasudo123.board.core.comment.service.impl; import edu.pasudo123.board.core.comment.exception.CommentNotFoundException; import edu.pasudo123.board.core.comment.model.Comment; import edu.pasudo123.board.core.comment.repository.CommentRepository; import edu.pasudo123.board.core.comment.service.CommentExternalFindService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; /** * Created by pasudo123 on 2019-08-15 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Service @RequiredArgsConstructor public class CommentExternalFindServiceImpl implements CommentExternalFindService { private final CommentRepository commentRepository; @Override public Comment findOneById(Long commentId) { return commentRepository.findById(commentId).orElseThrow(() -> new CommentNotFoundException("해당 코멘트는 존재하지 않습니다.")); } } <file_sep>/src/main/java/edu/pasudo123/board/core/global/exception/CustomErrorResponse.java package edu.pasudo123.board.core.global.exception; import lombok.Builder; import lombok.Getter; import org.springframework.http.HttpStatus; import java.time.LocalDateTime; import java.util.List; /** * Created by pasudo123 on 2019-07-31 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter public class CustomErrorResponse <T> { private LocalDateTime timestamp; private HttpStatus status; private String message; private String details; private List<String> errors; private T data; @Builder public CustomErrorResponse(HttpStatus status, String message, String details, List<String> errors, T data){ this.timestamp = LocalDateTime.now(); this.status = status; this.message = message; this.details = details; this.errors = errors; this.data = data; } } <file_sep>/src/main/java/edu/pasudo123/board/core/CoreApplication.java package edu.pasudo123.board.core; import edu.pasudo123.board.core.config.ProfileConfiguration; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @RequiredArgsConstructor public class CoreApplication implements CommandLineRunner { private final ProfileConfiguration profileConfiguration; public static void main(String[] args) { SpringApplication.run(CoreApplication.class, args); } @Override public void run(String... args) throws Exception { System.out.println(profileConfiguration); } } <file_sep>/build.gradle plugins { id 'org.springframework.boot' version '2.1.6.RELEASE' id 'java' id "com.moowork.node" version "1.3.1" } apply plugin: 'io.spring.dependency-management' apply plugin: "com.moowork.node" group = 'edu.pasudo123.board' version = '0.1.0' + new Date().format('yyyyMMddHHmmss') sourceCompatibility = '1.8' configurations { developmentOnly runtimeClasspath { extendsFrom developmentOnly } compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web-services' compileOnly 'org.projectlombok:lombok' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'mysql:mysql-connector-java' runtimeOnly 'com.h2database:h2' /** https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor **/ annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' /** Spring Security & OAuth 2**/ /** https://docs.spring.io/spring-security-oauth2-boot/docs/current/reference/htmlsingle/#source **/ compile 'org.springframework.boot:spring-boot-starter-security' compile 'org.springframework.boot:spring-boot-starter-oauth2-client' /** Spring Security end **/ /** https://github.com/json-path/JsonPath **/ compile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.4.0' /** JsonPath end **/ /** freemarker **/ compile 'org.springframework.boot:spring-boot-starter-freemarker' /** freemarker end **/ /** swagger **/ /** https://www.tutorialspoint.com/spring_boot/spring_boot_enabling_swagger2 **/ compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0' compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0' /** swagger end **/ /** model-mapper **/ compile 'org.modelmapper:modelmapper:2.3.0' /** model-mapper end **/ } // reference :: https://codar.club/blogs/using-gradle-to-build-the-api-development-framework-of-springboot-vue.js.html //task npmBuild(type:NpmTask, dependsOn:npmInstall){ // group = 'node' // inputs.file('./frontend/package.json') // inputs.file('./frontend/package-lock.json') // args = ['run', 'build'] //} //jar.dependsOn npmBuild<file_sep>/src/main/java/edu/pasudo123/board/core/config/ProfileConfiguration.java package edu.pasudo123.board.core.config; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * Created by pasudo123 on 2019-09-01 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Configuration @EnableConfigurationProperties @ConfigurationProperties(prefix = "server") @Getter @Setter @ToString public class ProfileConfiguration { private String email; } <file_sep>/src/main/java/edu/pasudo123/board/core/user/service/UserFindService.java package edu.pasudo123.board.core.user.service; import edu.pasudo123.board.core.user.model.User; /** * Created by pasudo123 on 2019-08-09 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public interface UserFindService { User currentUser(); User findByUserRegistrationId(String userRegistrationId); User findByEmail(String email); } <file_sep>/src/main/java/edu/pasudo123/board/core/user/exception/UserNotFoundException.java package edu.pasudo123.board.core.user.exception; /** * Created by pasudo123 on 2019-08-09 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } <file_sep>/src/test/java/edu/pasudo123/board/core/common/JsonPojoTest.java package edu.pasudo123.board.core.common; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.JsonTest; import org.springframework.boot.test.json.JacksonTester; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Created by pasudo123 on 2019-08-11 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @RunWith(SpringRunner.class) @JsonTest public class JsonPojoTest { @Autowired private JacksonTester<WriterDto> articleWriterDtoJacksonTester; @Test public void articleWriter_pojoJsonPropertyTest() throws Exception{ final WriterDto dto = WriterDto.builder() .userRegistrationId("google_1234") .name("홍길동") .profileImage("프로필 이미지") .build(); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .hasJsonPathStringValue("@.registrationId"); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .hasJsonPathStringValue("@.name"); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .hasJsonPathStringValue("@.image"); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .extractingJsonPathStringValue("@.registrationId").isEqualTo("google_1234"); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .extractingJsonPathStringValue("@.name").isEqualTo("홍길동"); assertThat(this.articleWriterDtoJacksonTester.write(dto)) .extractingJsonPathStringValue("@.image").isEqualTo("프로필 이미지"); } } <file_sep>/src/main/java/edu/pasudo123/board/core/config/profile/ProfileService.java package edu.pasudo123.board.core.config.profile; /** * Created by pasudo123 on 2019-09-01 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ public class ProfileService { private String name; public ProfileService(String name){ this.name = name; } public String getProfile(){ return "profile " + this.name; } } <file_sep>/src/main/java/edu/pasudo123/board/core/user/service/impl/UserFindServiceImpl.java package edu.pasudo123.board.core.user.service.impl; import edu.pasudo123.board.core.user.exception.UserNotFoundException; import edu.pasudo123.board.core.user.model.User; import edu.pasudo123.board.core.user.repository.UserRepository; import edu.pasudo123.board.core.user.service.UserFindService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; /** * Created by pasudo123 on 2019-08-09 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Service @RequiredArgsConstructor public class UserFindServiceImpl implements UserFindService { private final UserRepository userRepository; @Override public User currentUser() { return null; } @Override public User findByUserRegistrationId(String userRegistrationId) { return userRepository.findByUserRegistrationId(userRegistrationId) .orElseThrow(() -> new UserNotFoundException("현재 접속 유저는 존재하지 않습니다.")); } @Override public User findByEmail(String email) throws UserNotFoundException { return userRepository.findByEmail(email) .orElseThrow(() -> new UserNotFoundException("현재 접속 유저는 존재하지 않습니다.")); } } <file_sep>/src/main/java/edu/pasudo123/board/core/config/auth/AuthType.java package edu.pasudo123.board.core.config.auth; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Created by pasudo123 on 2019-08-09 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter @RequiredArgsConstructor public enum AuthType { GOOGLE, FACEBOOK, GITHUB } <file_sep>/src/main/java/edu/pasudo123/board/core/article/dto/ArticleListResponseDto.java package edu.pasudo123.board.core.article.dto; import com.fasterxml.jackson.annotation.JsonProperty; import edu.pasudo123.board.core.article.model.Article; import edu.pasudo123.board.core.article.model.ArticleType; import edu.pasudo123.board.core.common.WriterDto; import lombok.Getter; import lombok.NoArgsConstructor; import java.time.LocalDate; import java.time.LocalDateTime; /** * Created by pasudo123 on 2019-07-28 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter @NoArgsConstructor public class ArticleListResponseDto { private Long id; private String title; private ArticleType articleType; private LocalDateTime registrationDateTime; private LocalDate registrationDate; private LocalDateTime createdDate; private LocalDateTime modifiedDate; @JsonProperty("writer") private WriterDto writerDto; public ArticleListResponseDto(Article article){ this.id = article.getId(); this.title = article.getTitle(); this.articleType = article.getArticleType(); this.registrationDateTime = article.getRegistrationDateTime(); this.registrationDate = article.getRegistrationDate(); this.createdDate = article.getCreatedDate(); this.modifiedDate = article.getModifiedDate(); this.writerDto = new WriterDto(article.getWriterUser()); } } <file_sep>/src/main/java/edu/pasudo123/board/core/global/exception/ValidationException.java package edu.pasudo123.board.core.global.exception; import lombok.Getter; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import java.util.List; /** * Created by pasudo123 on 2019-08-04 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter public class ValidationException extends RuntimeException{ BindingResult bindingResult; String message; public ValidationException(String message, BindingResult bindingResult){ super(message); this.message = message; this.bindingResult = bindingResult; } } <file_sep>/src/main/java/edu/pasudo123/board/core/user/dto/UserOneRequestDto.java package edu.pasudo123.board.core.user.dto; import lombok.Builder; import lombok.Getter; /** * Created by pasudo123 on 2019-08-10 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter public class UserOneRequestDto { private String name; private String profileImage; @Builder public UserOneRequestDto(String name, String profileImage){ this.name = name; this.profileImage = profileImage; } } <file_sep>/src/main/java/edu/pasudo123/board/core/user/model/User.java package edu.pasudo123.board.core.user.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import edu.pasudo123.board.core.article.model.Article; import edu.pasudo123.board.core.comment.model.Comment; import edu.pasudo123.board.core.config.auth.dto.OAuthAttributesDto; import edu.pasudo123.board.core.user.dto.UserOneRequestDto; import lombok.AccessLevel; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.hibernate.annotations.Fetch; import javax.persistence.*; import java.util.ArrayList; import java.util.List; /** * Created by pasudo123 on 2019-08-06 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Getter @Entity @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "USER", uniqueConstraints = { @UniqueConstraint(name = "unique_user_registration_id", columnNames = {"userRegistrationId"}), }) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String userRegistrationId; @Column(nullable = false) private String name; @Column(nullable = false) private String email; @Column private String profileImage; @Enumerated(EnumType.STRING) @Column(nullable = false) private Role role; @JsonManagedReference @OneToMany(mappedBy = "writerUser", fetch = FetchType.LAZY) List<Article> articleList = new ArrayList<>(); @JsonManagedReference @OneToMany(mappedBy = "writerUser", fetch = FetchType.LAZY) List<Comment> commentList = new ArrayList<>(); @Builder public User(String userRegistrationId, String name, String email, String profileImage, Role role) { this.userRegistrationId = userRegistrationId; this.name = name; this.email = email; this.profileImage = profileImage; this.role = role; } public void addNewArticle(Article article) { getArticleList().add(article); } public void addNewComment(Comment comment){ getCommentList().add(comment); } public String getRoleKey() { return this.role.getKey(); } public User updateUser(UserOneRequestDto dto){ this.name = dto.getName(); this.profileImage = dto.getProfileImage(); return this; } } <file_sep>/frontend/vue.config.js const path = require('path'); function resolve(dir) { return path.join(__dirname, dir) } module.exports = { devServer: { port: 8888, proxy: { '/auth': { target: 'http://localhost:8080' }, '/api': { target: 'http://localhost:8080' }, } }, configureWebpack: { resolve: { alias: { '@': resolve('src') } }, }, publicPath: '/', outputDir: '../src/main/resources/static', assetsDir: 'static', pages: { login: { entry: './src/pages/login/main.js', template: 'public/index.html', filename: './templates/login.ftl', }, article: { entry: './src/pages/home/main.js', template: 'public/index.html', filename: './templates/article.ftl', }, }, };<file_sep>/src/main/java/edu/pasudo123/board/core/user/service/impl/UserDeleteServiceImpl.java package edu.pasudo123.board.core.user.service.impl; import edu.pasudo123.board.core.user.repository.UserRepository; import edu.pasudo123.board.core.user.service.UserDeleteService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; /** * Created by pasudo123 on 2019-08-11 * Blog: https://pasudo123.tistory.com/ * Email: <EMAIL> **/ @Service @RequiredArgsConstructor public class UserDeleteServiceImpl implements UserDeleteService { private final UserRepository userRepository; @Override public void deleteOneByRegistrationId(String registrationId) { userRepository.deleteByUserRegistrationId(registrationId); } } <file_sep>/frontend/src/config/router.js import Vue from "vue" import VueRouter from "vue-router" Vue.use(VueRouter); export default new VueRouter({ mode: 'history', routes: [ { path: "login", name: "login", component: () => import("@/pages/login/Login") }, { path: "/article", name: "home", component: () => import("@/pages/home/Article"), }, { path: "/article/edit", name: "articleEdit", component: () => import("@/pages/home/ArticleEdit"), }, { path: "/article/view", name: "articleView", component: () => import("@/pages/home/ArticleView"), }, ] });<file_sep>/README.md # 스프링부트로 간단 게시판 구현 ### 참고자료 * [인텔리제이 깃헙 이용](https://cheese10yun.github.io/intellij-github/) * [깃헙 이슈 관리](https://github.com/cheese10yun/github-project-management#pull-requestcode-review) * [서비스 레이어 책임](https://github.com/cheese10yun/spring-guide/blob/master/docs/service-guide.md) * [실무에서 롬복 사용방법](https://www.popit.kr/%EC%8B%A4%EB%AC%B4%EC%97%90%EC%84%9C-lombok-%EC%82%AC%EC%9A%A9%EB%B2%95/) * [앵귤러 커밋 메세지 작성 요령](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines) * [스프링부트로 웹 서비스 구축하기 by 조졸두](https://github.com/jojoldu/springboot-webservice) ### js library * [vue-persistedstate](https://github.com/robinvdvleuten/vuex-persistedstate) * [vuex-map-fields](https://github.com/maoberlehner/vuex-map-fields) * [js-Cookies](https://www.npmjs.com/package/js-cookie) * [glob](https://www.npmjs.com/package/glob) <file_sep>/frontend/src/pages/home/main.js import Vue from 'vue' import App from '@/pages/home/App.vue' import router from '@/config/router' import store from '@/store/store' import Vuetify from 'vuetify' import 'vuetify/dist/vuetify.min.css' Vue.use(Vuetify); Vue.config.productionTip = false; import '@/style/global.css' router.beforeEach((to, from, next) => { store.dispatch(`currentUser`).catch((error) => { console.error(error.response.data); /** TODO 회원을 못 찾았기 때문에 로그인 페이지 이동 여부 확인 **/ }); next(); }); new Vue({ router, store, render: h => h(App) }).$mount('#app');
2df4b4d0994df9998f6ba02bde9c7c6c2fbf3b45
[ "JavaScript", "Java", "Markdown", "Gradle" ]
32
Gradle
pasudo123/SpringBoot-BoardSample
0d438f54abb30ffb57c0e1d38660ae90cc508afb
d8607e63ab8933dda635c1d381f53d58dcd2c030
refs/heads/master
<repo_name>SamGurr/Geoduck_transgen_offspring_OA<file_sep>/RAnalysis/Scripts/Larvae.size.R #Title: Larvae.size #Author: <NAME> #Edited by: <NAME> #Date Last Modified: 20190628 #See Readme file for details rm(list=ls()) #clears workspace ## install packages if you dont already have them in your library if ("devtools" %in% rownames(installed.packages()) == 'FALSE') install.packages('devtools') if ("segmented" %in% rownames(installed.packages()) == 'FALSE') install.packages('segmented') if ("plotrix" %in% rownames(installed.packages()) == 'FALSE') install.packages('plotrix') if ("gridExtra" %in% rownames(installed.packages()) == 'FALSE') install.packages('gridExtra') if ("LoLinR" %in% rownames(installed.packages()) == 'FALSE') install_github('colin-olito/LoLinR') if ("lubridate" %in% rownames(installed.packages()) == 'FALSE') install.packages('lubridate') if ("chron" %in% rownames(installed.packages()) == 'FALSE') install.packages('chron') if ("plyr" %in% rownames(installed.packages()) == 'FALSE') install.packages('plyr') if ("dplyr" %in% rownames(installed.packages()) == 'FALSE') install.packages('dplyr') #Read in required libraries ##### Include Versions of libraries #install_github('colin-olito/LoLinR') library("ggplot2") library("segmented") library("plotrix") library("gridExtra") library("LoLinR") library("lubridate") library("chron") library('plyr') library('dplyr') # Load packages and pacage version/date/import/depends info library(dplyr) # Version 0.7.6, Packaged: 2018-06-27, Depends: R (>= 3.1.2)Imports: assertthat (>= 0.2.0), bindrcpp (>= 0.2.0.9000), glue (>=1.1.1), magrittr (>= 1.5), methods, pkgconfig (>= 2.0.1), R6(>= 2.2.2), Rcpp (>= 0.12.15), rlang (>= 0.2.0), tibble (>=1.3.1), tidyselect (>= 0.2.3), utils library(ggplot2) # Version 2.2.1, Packaged: 2016-12-30, Depends: R (>= 3.1)Imports: digest, grid, gtable (>= 0.1.1), MASS, plyr (>= 1.7.1),reshape2, scales (>= 0.4.1), stats, tibble, lazyeval library(ggpubr) # Version: 0.1.8 Date: 2018-08-30, Depends: R (>= 3.1.0), ggplot2, magrittrImports: ggrepel, grid, ggsci, stats, utils, tidyr, purrr, dplyr(>=0.7.1), cowplot, ggsignif, scales, gridExtra, glue, polynom library(Rmisc) # Version: 1.5 Packaged: 2013-10-21, Depends: lattice, plyr library(plotrix) # Version: 3.7-4, Date/Publication: 2018-10-03 library(lsmeans) # Version: 2.27-62, Date/Publication: 2018-05-11, Depends: methods, R (>= 3.2) library(gridExtra) # Version: 2.3, Date/Publication: 2017-09-09, Imports: gtable, grid, grDevices, graphics, utils library(reshape) # Version: 0.8.7, Date/Publication: 2017-08-06, Depends: R (>= 2.6.1) Imports: plyr library(multcompView) # Version: 0.1-7, Date/Publication: 2015-07-31, Imports: grid library(Rmisc) library(lmtest) library(car) #Required Data files # Set Working Directory: # setwd("~/MyProjects/Geoduck_Conditioning/RAnalysis/") #set working setwd("C:/Users/samjg/Documents/My_Projects/Geoduck_transgen_offspring_OA/RAnalysis/") #Load Sample Info Size.data <- read.csv(file="Data/Size_data/Size_larvae.csv", header=T) #read sample.info data # Analysis names(Size.data) # filter data Size.data_2 <- Size.data %>% filter(!(Age == "28_days")) #%>% # filter out day 28 becasue no samples for T3 (variable pH) #filter(Tank_ID %in% c("T1", "T3")) # select only T1 and T3 (T0 and T2 failed midway through experiment) # run the model aov.mod_1 <- aov(length_um ~ Parental_treatment*Age, data = Size.data_2) anova(aov.mod_1) # diagnostic tests and plots of model residuals (not transformed) # Shapiro test shapiro.test(residuals(aov.mod_1)) # residuals are normal - 0.05555 # hist qq residual diagnostic par(mfrow=c(1,3)) #set plotting configuration par(mar=c(1,1,1,1)) #set margins for plots hist(residuals(aov.mod_1)) #plot histogram of residuals - normal bell curve boxplot(residuals(aov.mod_1)) #plot boxplot of residuals plot(fitted(aov.mod_1),residuals(aov.mod_1)) qqnorm(residuals(aov.mod_1)) # qqplot - good qqnorm plot # post-hoc analysis TukeyHSD(aov.mod_1) # tukey of the model ID.size.ANOVA <- lsmeans(aov.mod_1, pairwise ~ Parental_treatment*Age)# pariwise Tukey Post-hoc test between repeated treatments ID.size.ANOVA # view post hoc summary Treatment.pairs.05 <- cld(ID.size.ANOVA, alpha=.05, Letters=letters) #list pairwise tests and letter display p < 0.05 Treatment.pairs.05 #view results # plot data Larvae.size.plot <- ggplot(Size.data_2, aes(x = factor(Age), y = length_um, fill = Parental_treatment)) + theme_classic() + scale_fill_manual(values=c("blue", "orange", "blue", "orange", "blue", "orange", "blue", "orange")) + #labels=c("Ambient","Ambient × Ambient","Ambient × Elevated","Elevated","Elevated × Ambient","Elevated × Elevated") geom_boxplot(alpha = 0.5, # color hue width=0.6, # boxplot width outlier.size=0, # make outliers small position = position_dodge(preserve = "single")) + geom_point(pch = 19, position = position_jitterdodge(.3), size=1) + stat_summary(fun.y=mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..), width = 0.6, size=0.4, linetype = "dashed", position = position_dodge(preserve = "single")) + theme(legend.position = c(0.55,0.96), legend.direction="horizontal", legend.title=element_blank()) + labs(y=expression("Size"~(µm)), x=expression("Age")) Larvae.size.plot # view plot Larvae.size.plot_FINAL <- Larvae.size.plot + annotate("text", x=0.7, y=140, label = "a", size = 5) + annotate("text", x=1.3, y=145, label = "ab", size = 5) + annotate("text", x=1.7, y=150, label = "b", size = 5) + annotate("text", x=2.3, y=160, label = "c", size = 5) + annotate("text", x=2.7, y=180, label = "cd", size = 5) + annotate("text", x=3.3, y=175, label = "d", size = 5) + annotate("text", x=3.7, y=200, label = "e", size = 5) + annotate("text", x=4.3, y=210, label = "e", size = 5) + annotate("text", x=4.7, y=260, label = "e", size = 5) + annotate("text", x=5.3, y=220, label = "f", size = 5) + annotate("text", x=2, y=185, label = "*", size = 5) + annotate("text", x=5, y=270, label = "*", size = 5) + annotate("segment", x = 2.25, xend = 1.75, y = 180, yend = 180, colour = "black") + annotate("segment", x = 5.25, xend = 4.75, y = 265, yend = 265, colour = "black") Larvae.size.plot_FINAL #save file to output ggsave(file="Output/Larvae.size.plot.pdf", Larvae.size.plot_FINAL, width = 12, height = 8, units = c("in")) <file_sep>/RAnalysis/Scripts/TA.test.HgCl2.R #Title: TA HgCl2 test #Author: <NAME> #Edited by: <NAME> #Date Last Modified: 20190209 #See Readme file for details rm(list=ls()) #clears workspace if ("dplyr" %in% rownames(installed.packages()) == 'FALSE') install.packages('dplyr') library('dplyr') setwd("C:/Users/samjg/Documents/My_Projects/Geoduck_transgen_offspring_OA/RAnalysis/") #Load Carb chem test file Carb.chem.file<- read.csv(file="Data/TA_HgCl2_test/20190209_Carb_chem_output.csv", header=T) #read sample.info data Carb.chem.file # Elevated treatment elevated <- Carb.chem.file %>% filter(Carb.chem.file$Treatment == "Elevated") # Conicals test_conicals_elevated <- elevated %>% filter((substr(elevated$Tank, 10,10)) == "T") # test Conicals t.test(TA~Notes, data=test_conicals_elevated) # Broodstock tanks test_broodstock_elevated <- elevated %>% filter((substr(elevated$Tank, 11,11)) == "B") # test broodstock tanks t.test(TA~Notes, data=test_broodstock_elevated) # Ambient treatment Ambient <- Carb.chem.file %>% filter(Carb.chem.file$Treatment == "Ambient") # Conicals test_conicals_Ambient <- Ambient %>% filter((substr(Ambient$Tank, 10,10)) == "T") # test Conicals t.test(TA~Notes, data=test_conicals_Ambient) # Broodstock tanks test_broodstock_Ambient <- Ambient %>% filter((substr(Ambient$Tank, 11,11)) == "B") # test broodstock tanks t.test(TA~Notes, data=test_broodstock_Ambient) <file_sep>/RAnalysis/Scripts/Resp.Calc.Analysis.R #Title: Respiration Calculations #Author: <NAME> #Edited by: <NAME> #Date Last Modified: 20190329 #See Readme file for details rm(list=ls()) #clears workspace ## install packages if you dont already have them in your library if ("devtools" %in% rownames(installed.packages()) == 'FALSE') install.packages('devtools') library(devtools) if ("segmented" %in% rownames(installed.packages()) == 'FALSE') install.packages('segmented') if ("plotrix" %in% rownames(installed.packages()) == 'FALSE') install.packages('plotrix') if ("gridExtra" %in% rownames(installed.packages()) == 'FALSE') install.packages('gridExtra') if ("LoLinR" %in% rownames(installed.packages()) == 'FALSE') install_github('colin-olito/LoLinR') if ("lubridate" %in% rownames(installed.packages()) == 'FALSE') install.packages('lubridate') if ("chron" %in% rownames(installed.packages()) == 'FALSE') install.packages('chron') if ("plyr" %in% rownames(installed.packages()) == 'FALSE') install.packages('plyr') if ("dplyr" %in% rownames(installed.packages()) == 'FALSE') install.packages('dplyr') if ("lmtest" %in% rownames(installed.packages()) == 'FALSE') install.packages('lmtest') if ("car" %in% rownames(installed.packages()) == 'FALSE') install.packages('car') #Read in required libraries ##### Include Versions of libraries #install_github('colin-olito/LoLinR') library("ggplot2") library("segmented") library("plotrix") library("gridExtra") library("LoLinR") library("lubridate") library("chron") library('plyr') library('dplyr') library('car') library('lmtest') # Set Working Directory: # setwd("~/MyProjects/Geoduck_Conditioning/RAnalysis/") #set working setwd("C:/Users/samjg/Documents/My_Projects/Geoduck_transgen_offspring_OA/RAnalysis/") #Load Sample Info Sample.Info <- read.csv(file="Data/SDR_data/REFERENCE_number.individuals_shell.size.csv", header=T) #read sample.info data # X = the cumulative summary table of all Lolin outputs # (1) merge witht he individual number or size data after you make the cumulative table #x <- merge(df_total, Sample.Info, by=c("Date","SDR_position", "RUN")) # merge the individual info (size, estimate number of larvae) by common columns # (2) instead of making this table (renders through many csv files for hours) - open the csv of the finished table itself # call the cumulative resp table of Lolin raw outputs cumulative_resp_table <- read.csv(file="Data/SDR_data/Cumulative_resp_alpha0.4.csv", header=T) #read sample.info data # call the sample info of size and number of individuals per trial ( sample info called above) x <- merge(cumulative_resp_table, Sample.Info, by=c("Date","SDR_position", "RUN")) # Pediveliger fifth drop respiration 20190418 #---------------------------------------------- Pediveligerresp_20190418<- x %>% filter((substr(x$Date, 1,9)) == "20190418") # call only resp values of juveniles # Run 1 T1_T3 --------------- Pediveligerresp_T1_T3 <- Pediveligerresp_20190418 %>% filter((Pediveligerresp_20190418$RUN) == 1)# call only resp values of juveniles PediveligerT1_T3resp_blanks <- Pediveligerresp_T1_T3 %>% filter(Pediveligerresp_T1_T3$Tank.ID == "Blank") # call only blanks PediveligerT1_T3resp_blankMEANS <- PediveligerT1_T3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value PediveligerT1_T3resp_geoduck_7 <- Pediveligerresp_T1_T3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) PediveligerT1_T3resp_geoduck_7$Resp_rate_ug.mol <- ((((((abs(PediveligerT1_T3resp_geoduck_7$Lpc)) - (PediveligerT1_T3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(PediveligerT1_T3resp_geoduck_7$length_number.individuals)) PediveligerT1_T3resp_geoduck_7$Resp_rate_ug.mol # units in ug O2/hr/individual PediveligerT1_T3resp_geoduck_7 <- PediveligerT1_T3resp_geoduck_7 %>% filter(PediveligerT1_T3resp_geoduck_7$Resp_rate_ug.mol > 0) PediveligerT1_T3resp_table_treatments_ALL <- PediveligerT1_T3resp_geoduck_7 %>% #filter(PediveligerT1_T3resp_geoduck$Resp_rate_ug.mol > 0) %>% #filter out all negative rates group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order PediveligerT1_T3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 7 Day32_20190418 <- PediveligerT1_T3resp_geoduck_7 Day32_20190418$Day <- "32" # D-hinge fifth drop respiration 20190410 #---------------------------------------------- Dhingeresp_20190410<- x %>% filter((substr(x$Date, 1,9)) == "20190410") # call only resp values of juveniles # Run 1 T1 --------------- Dhingeresp_T1 <- Dhingeresp_20190410 %>% filter((Dhingeresp_20190410$RUN) == 1)# call only resp values of juveniles DhingeT1resp_blanks <- Dhingeresp_T1 %>% filter(Dhingeresp_T1$Tank.ID == "Blank") # call only blanks DhingeT1resp_blankMEANS <- DhingeT1resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT1resp_geoduck_5 <- Dhingeresp_T1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT1resp_geoduck_5$Resp_rate_ug.mol <- ((((((abs(DhingeT1resp_geoduck_5$Lpc)) - (DhingeT1resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT1resp_geoduck_5$length_number.individuals)) DhingeT1resp_geoduck_5$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT1resp_geoduck_5 <- DhingeT1resp_geoduck_5 %>% filter(DhingeT1resp_geoduck_5$Resp_rate_ug.mol > 0) DhingeT1resp_table_treatments_ALL <- DhingeT1resp_geoduck_5 %>% filter(DhingeT1resp_geoduck$Resp_rate_ug.mol > 0) %>% #filter out all negative rates group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT1resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 2 T3 --------------- (did not do T2 becasue there was a low yield of larvae) Dhingeresp_t3 <- Dhingeresp_20190410 %>% filter((Dhingeresp_20190410$RUN) == 2)# call only resp values of juveniles Dhinget3resp_blanks <- Dhingeresp_t3 %>% filter(Dhingeresp_t3$Tank.ID == "Blank") # call only blanks Dhinget3resp_blankMEANS <- Dhinget3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT3resp_geoduck_5 <- Dhingeresp_t3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT3resp_geoduck_5$Resp_rate_ug.mol <- ((((((abs(DhingeT3resp_geoduck_5$Lpc)) - (Dhinget3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT3resp_geoduck_5$length_number.individuals)) DhingeT3resp_geoduck_5$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT3resp_geoduck_5 <- DhingeT3resp_geoduck_5 %>% filter(DhingeT3resp_geoduck_5$Resp_rate_ug.mol > 0) Dhinget3resp_table_treatments_ALL <- DhingeT3resp_geoduck_5 %>% group_by(Treatment) %>% filter(Dhinget3resp_geoduck$Resp_rate_ug.mol > 0) %>% #filter out all negative rates summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order Dhinget3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 5 Day24_20190410 <- rbind(DhingeT1resp_geoduck_5, DhingeT3resp_geoduck_5) Day24_20190410$Day <- "24" ############################################### # D-hinge fourth drop respiration 20190406 #---------------------------------------------- ############################################### Dhingeresp_20190406<- x %>% filter((substr(x$Date, 1,9)) == "20190406") # call only resp values of juveniles # Run 1 T1 --------------- Dhingeresp_T1 <- Dhingeresp_20190406 %>% filter((Dhingeresp_20190406$RUN) == 1)# call only resp values of juveniles DhingeT1resp_blanks <- Dhingeresp_T1 %>% filter(Dhingeresp_T1$Tank.ID == "Blank") # call only blanks DhingeT1resp_blankMEANS <- DhingeT1resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT1resp_geoduck_4 <- Dhingeresp_T1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT1resp_geoduck_4$Resp_rate_ug.mol <- ((((((abs(DhingeT1resp_geoduck_4$Lpc)) - (DhingeT1resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT1resp_geoduck_4$length_number.individuals)) DhingeT1resp_geoduck$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT1resp_geoduck_4 <- DhingeT1resp_geoduck_4 %>% filter(DhingeT1resp_geoduck_4$Resp_rate_ug.mol > 0) DhingeT1resp_table_treatments_ALL <- DhingeT1resp_geoduck_4 %>% filter(DhingeT1resp_geoduck_4$Resp_rate_ug.mol > 0) %>% #filter out all negative rates group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT1resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 2 T2 --------------- Dhingeresp_T2 <- Dhingeresp_20190406 %>% filter((Dhingeresp_20190406$RUN) == 2)# call only resp values of juveniles DhingeT2resp_blanks <- Dhingeresp_T2 %>% filter(Dhingeresp_T2$Tank.ID == "Blank") # call only blanks DhingeT2resp_blankMEANS <- DhingeT2resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT2resp_geoduck_4 <- Dhingeresp_T2 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT2resp_geoduck_4$Resp_rate_ug.mol <- ((((((abs(DhingeT2resp_geoduck_4$Lpc)) - (DhingeT2resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT2resp_geoduck_4$length_number.individuals)) DhingeT2resp_geoduck_4$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT2resp_geoduck_4 <- DhingeT2resp_geoduck_4 %>% filter(DhingeT2resp_geoduck_4$Resp_rate_ug.mol > 0) DhingeT2resp_table_treatments_ALL <- DhingeT2resp_geoduck_4 %>% group_by(Treatment) %>% filter(DhingeT2resp_geoduck_4$Resp_rate_ug.mol > 0) %>% #filter out all negative rates summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT2resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 3 T3 --------------- Dhingeresp_T3 <- Dhingeresp_20190406 %>% filter((Dhingeresp_20190406$RUN) == 3)# call only resp values of juveniles DhingeT3resp_blanks <- Dhingeresp_T3 %>% filter(Dhingeresp_T3$Tank.ID == "Blank") # call only blanks DhingeT3resp_blankMEANS <- DhingeT3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT3resp_geoduck_4 <- Dhingeresp_T3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT3resp_geoduck_4$Resp_rate_ug.mol <- ((((((abs(DhingeT3resp_geoduck_4$Lpc)) - (DhingeT3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT3resp_geoduck_4$length_number.individuals)) DhingeT3resp_geoduck_4$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT3resp_geoduck_4 <- DhingeT3resp_geoduck_4 %>% filter(DhingeT3resp_geoduck_4$Resp_rate_ug.mol > 0) DhingeT3resp_table_treatments_ALL <- DhingeT3resp_geoduck_4 %>% group_by(Treatment) %>% filter(DhingeT3resp_geoduck_4$Resp_rate_ug.mol > 0) %>% #filter out all negative rates summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 5 Day20_20190406 <- rbind(DhingeT1resp_geoduck_4, DhingeT3resp_geoduck_4) Day20_20190406$Day <- "20" ####################################################### # D-hinge third drop respiration 20190402 #---------------------------------------------- ####################################################### Dhingeresp_20190402<- x %>% filter((substr(x$Date, 1,9)) == "20190402") # call only resp values of juveniles # Run 1 T1 --------------- Dhingeresp_T1 <- Dhingeresp_20190402 %>% filter((Dhingeresp_20190402$RUN) == 1)# call only resp values of juveniles DhingeT1resp_blanks <- Dhingeresp_T1 %>% filter(Dhingeresp_T1$Tank.ID == "Blank") # call only blanks DhingeT1resp_blankMEANS <- DhingeT1resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT1resp_geoduck_3 <- Dhingeresp_T1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT1resp_geoduck_3$Resp_rate_ug.mol <- ((((((abs(DhingeT1resp_geoduck_3$Lpc)) - (DhingeT1resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT1resp_geoduck_3$length_number.individuals)) DhingeT1resp_geoduck_3$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT1resp_geoduck_3 <- DhingeT1resp_geoduck_3 %>% filter(DhingeT1resp_geoduck_3$Resp_rate_ug.mol > 0) DhingeT1resp_table_treatments_ALL <- DhingeT1resp_geoduck_3 %>% filter(DhingeT1resp_geoduck_3$Resp_rate_ug.mol > 0) %>% #filter out all negative rates group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT1resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 2 T2 --------------- Dhingeresp_T2 <- Dhingeresp_20190402 %>% filter((Dhingeresp_20190402$RUN) == 2)# call only resp values of juveniles DhingeT2resp_blanks <- Dhingeresp_T2 %>% filter(Dhingeresp_T2$Tank.ID == "Blank") # call only blanks DhingeT2resp_blankMEANS <- DhingeT2resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT2resp_geoduck_3 <- Dhingeresp_T2 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT2resp_geoduck_3$Resp_rate_ug.mol <- ((((((abs(DhingeT2resp_geoduck_3$Lpc)) - (DhingeT2resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT2resp_geoduck_3$length_number.individuals)) DhingeT2resp_geoduck_3$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT2resp_geoduck_3 <- DhingeT2resp_geoduck_3 %>% filter(DhingeT2resp_geoduck_3$Resp_rate_ug.mol > 0) DhingeT2resp_table_treatments_ALL <- DhingeT2resp_geoduck_3 %>% group_by(Treatment) %>% filter(DhingeT2resp_geoduck_3$Resp_rate_ug.mol > 0) %>% #filter out all negative rates summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT2resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 3 T3 --------------- Dhingeresp_T3 <- Dhingeresp_20190402 %>% filter((Dhingeresp_20190402$RUN) == 3)# call only resp values of juveniles DhingeT3resp_blanks <- Dhingeresp_T3 %>% filter(Dhingeresp_T3$Tank.ID == "Blank") # call only blanks DhingeT3resp_blankMEANS <- DhingeT3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT3resp_geoduck_3 <- Dhingeresp_T3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT3resp_geoduck_3$Resp_rate_ug.mol <- ((((((abs(DhingeT3resp_geoduck_3$Lpc)) - (DhingeT3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT3resp_geoduck_3$length_number.individuals)) DhingeT3resp_geoduck_3$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT3resp_geoduck_3 <- DhingeT3resp_geoduck_3 %>% filter(DhingeT3resp_geoduck_3$Resp_rate_ug.mol > 0) DhingeT3resp_table_treatments_ALL <- DhingeT3resp_geoduck_3 %>% group_by(Treatment) %>% filter(DhingeT3resp_geoduck_3$Resp_rate_ug.mol > 0) %>% #filter out all negative rates summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 5 Day16_20190402 <- rbind(DhingeT1resp_geoduck_3, DhingeT3resp_geoduck_3) Day16_20190402$Day <- "16" ####################################################### # D-hinge second drop respiration 20190329 #---------------------------------------------- ####################################################### Dhingeresp_190329 <- x %>% filter((substr(x$Date, 1,9)) == "20190329") # call only resp values of juveniles # T0 --------------- not enogh larvae alive to quanitfy for trial - T0 ended today 20190329 # Run 1 T1 --------------- Dhingeresp_T1 <- Dhingeresp_190329 %>% filter((Dhingeresp_190329$RUN) == 1)# call only resp values of juveniles DhingeT1resp_blanks <- Dhingeresp_T1 %>% filter(Dhingeresp_T1$Tank.ID == "Blank") # call only blanks DhingeT1resp_blankMEANS <- DhingeT1resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT1resp_geoduck_2 <- Dhingeresp_T1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT1resp_geoduck_2$Resp_rate_ug.mol <- ((((((abs(DhingeT1resp_geoduck_2$Lpc)) - (DhingeT1resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT1resp_geoduck_2$length_number.individuals)) DhingeT1resp_geoduck_2$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT1resp_geoduck_2 <- DhingeT1resp_geoduck_2 %>% filter(DhingeT1resp_geoduck_2$Resp_rate_ug.mol > 0) DhingeT1resp_table_treatments_ALL <- DhingeT1resp_geoduck_2 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT1resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 2 T2 --------------- Dhingeresp_T2 <- Dhingeresp_190329 %>% filter((Dhingeresp_190329$RUN) == 2)# call only resp values of juveniles DhingeT2resp_blanks <- Dhingeresp_T2 %>% filter(Dhingeresp_T2$Tank.ID == "Blank") # call only blanks DhingeT2resp_blankMEANS <- DhingeT2resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT2resp_geoduck_2 <- Dhingeresp_T2 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT2resp_geoduck_2$Resp_rate_ug.mol <- ((((((abs(DhingeT2resp_geoduck_2$Lpc)) - (DhingeT2resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT2resp_geoduck_2$length_number.individuals)) DhingeT2resp_geoduck_2$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT2resp_geoduck_2 <- DhingeT2resp_geoduck_2 %>% filter(DhingeT2resp_geoduck_2$Resp_rate_ug.mol > 0) DhingeT2resp_table_treatments_ALL <- DhingeT2resp_geoduck_2 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT2resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 3 T3 --------------- Dhingeresp_T3 <- Dhingeresp_190329 %>% filter((Dhingeresp_190329$RUN) == 3)# call only resp values of juveniles DhingeT3resp_blanks <- Dhingeresp_T3 %>% filter(Dhingeresp_T3$Tank.ID == "Blank") # call only blanks DhingeT3resp_blankMEANS <- DhingeT3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT3resp_geoduck_2 <- Dhingeresp_T3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT3resp_geoduck_2$Resp_rate_ug.mol <- ((((((abs(DhingeT3resp_geoduck_2$Lpc)) - (DhingeT3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT3resp_geoduck_2$length_number.individuals)) DhingeT3resp_geoduck_2$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT3resp_geoduck_2 <- DhingeT3resp_geoduck_2 %>% filter(DhingeT3resp_geoduck_2$Resp_rate_ug.mol > 0) DhingeT3resp_table_treatments_ALL <- DhingeT3resp_geoduck_2 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 2 Day12_20190329 <- rbind(DhingeT1resp_geoduck_2, DhingeT3resp_geoduck_2) Day12_20190329$Day <- "12" #################################################### # D-hinge first drop respiration 20190325 #---------------------------------------------- #################################################### Dhingeresp_190325 <- x %>% filter((substr(x$Date, 1,9)) == "20190325") # call only resp values of juveniles # Run 1 T0 --------------- Dhingeresp_T0 <- Dhingeresp_190325 %>% filter((Dhingeresp_190325$RUN) == 1)# call only resp values of juveniles DhingeT0resp_blanks <- Dhingeresp_T0 %>% filter(Dhingeresp_T0$Tank.ID == "Blank") # call only blanks DhingeT0resp_blankMEANS <- DhingeT0resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT0resp_geoduck_1 <- Dhingeresp_T0 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT0resp_geoduck_1$Resp_rate_ug.mol <- ((((((abs(DhingeT0resp_geoduck_1$Lpc)) - (DhingeT0resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT0resp_geoduck_1$length_number.individuals)) DhingeT0resp_geoduck_1$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT0resp_geoduck_1 <- DhingeT0resp_geoduck_1 %>% filter(DhingeT0resp_geoduck_1$Resp_rate_ug.mol > 0) DhingeT0resp_table_treatments_ALL <- DhingeT0resp_geoduck_1 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT0resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 2 T1 --------------- Dhingeresp_T1 <- Dhingeresp_190325 %>% filter((Dhingeresp_190325$RUN) == 2)# call only resp values of juveniles DhingeT1resp_blanks <- Dhingeresp_T1 %>% filter(Dhingeresp_T1$Tank.ID == "Blank") # call only blanks DhingeT1resp_blankMEANS <- DhingeT1resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT1resp_geoduck_1 <- Dhingeresp_T1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT1resp_geoduck_1$Resp_rate_ug.mol <- ((((((abs(DhingeT1resp_geoduck_1$Lpc)) - (DhingeT1resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT1resp_geoduck_1$length_number.individuals)) DhingeT1resp_geoduck_1$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT1resp_geoduck_1 <- DhingeT1resp_geoduck_1 %>% filter(DhingeT1resp_geoduck_1$Resp_rate_ug.mol > 0) DhingeT1resp_table_treatments_ALL <- DhingeT1resp_geoduck_1 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT1resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 3 T2 --------------- Dhingeresp_T2 <- Dhingeresp_190325 %>% filter((Dhingeresp_190325$RUN) == 3)# call only resp values of juveniles DhingeT2resp_blanks <- Dhingeresp_T2 %>% filter(Dhingeresp_T2$Tank.ID == "Blank") # call only blanks DhingeT2resp_blankMEANS <- DhingeT2resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT2resp_geoduck_1 <- Dhingeresp_T2 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT2resp_geoduck_1$Resp_rate_ug.mol <- ((((((abs(DhingeT2resp_geoduck_1$Lpc)) - (DhingeT2resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT2resp_geoduck_1$length_number.individuals)) DhingeT2resp_geoduck_1$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT2resp_geoduck_1 <- DhingeT2resp_geoduck_1 %>% filter(DhingeT2resp_geoduck_1$Resp_rate_ug.mol > 0) DhingeT2resp_table_treatments_ALL <- DhingeT2resp_geoduck_1 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT2resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Run 4 T3 --------------- Dhingeresp_T3 <- Dhingeresp_190325 %>% filter((Dhingeresp_190325$RUN) == 4)# call only resp values of juveniles DhingeT3resp_blanks <- Dhingeresp_T3 %>% filter(Dhingeresp_T3$Tank.ID == "Blank") # call only blanks DhingeT3resp_blankMEANS <- DhingeT3resp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value DhingeT3resp_geoduck_1 <- Dhingeresp_T3 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) DhingeT3resp_geoduck_1$Resp_rate_ug.mol <- ((((((abs(DhingeT3resp_geoduck_1$Lpc)) - (DhingeT3resp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(DhingeT3resp_geoduck_1$length_number.individuals)) DhingeT3resp_geoduck_1$Resp_rate_ug.mol # units in ug O2/hr/individual DhingeT3resp_geoduck_1 <- DhingeT3resp_geoduck_1 %>% filter(DhingeT3resp_geoduck_1$Resp_rate_ug.mol > 0) DhingeT3resp_table_treatments_ALL <- DhingeT3resp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order DhingeT3resp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # SUMMARY DATA FROM TANK DROP 1 Day8_20190325 <- rbind(DhingeT1resp_geoduck_1, DhingeT3resp_geoduck_1) Day8_20190325$Day <- "8" #PLOTS OF AMBIENT AND ELEVATED FROM JUST T1 AND T3 # RBIND ALL DATA ALL_DATA <- rbind(Day8_20190325, Day12_20190329, Day16_20190402, Day20_20190406, Day24_20190410, Day32_20190418) ALL_DATA$Resp_rate_ng.mol <- ALL_DATA$Resp_rate_ug.mol*1000 # resp fig for all data RESP_FIG_T1_T3 <- ggplot(ALL_DATA, aes(x = factor(Date), y = Resp_rate_ng.mol, fill = Treatment)) + theme_classic() + scale_fill_manual(values=c("white", "grey3"), labels=c("P_ambient","P_elevated")) + geom_boxplot(alpha = 0.5, # color hue width=0.6, # boxplot width outlier.size=0, # make outliers small position = position_dodge(preserve = "single")) + geom_point(pch = 19, position = position_jitterdodge(.05), size=1) + stat_summary(fun.y=mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..), width = 0.6, size=0.4, linetype = "dashed", position = position_dodge(preserve = "single")) + scale_x_discrete(labels = c(8,12,16,20,24,32)) + theme(legend.position = c(0.55,0.96), legend.direction="horizontal", legend.title=element_blank()) + ylim(0,10) + labs(y=expression("Respiration rate"~ng~O[2]*hr^{-1}*individual^{-1}), x=expression("Age (days)")) RESP_FIG_T1_T3.FINAL <- RESP_FIG_T1_T3 + theme(axis.text.x = element_text(angle = 0, hjust = 0.5, size=13,color="black"), axis.text.y = element_text(angle = 0, hjust = 0.5, size=13,color="black"), axis.line = element_line(color = 'black'), axis.ticks.length=unit(0.2, "cm"), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14)) RESP_FIG_T1_T3.FINAL # view the plot # resp fig for days 8 - 24 ALL_DATA_8.24 <- ALL_DATA %>% filter(!(Day == 32)) # make new dataset without day 32 data RESP_FIG_DAYS8.24 <- ggplot(ALL_DATA_8.24, aes(x = factor(Date), y = (Resp_rate_ng.mol), fill = Treatment)) + theme_classic() + scale_fill_manual(values=c("blue", "orange"), labels=c("ambient","var.pH")) + geom_boxplot(alpha = 0.5, # color hue width=0.6, # boxplot width outlier.size=0, # make outliers small position = position_dodge(preserve = "single")) + geom_point(pch = 19, position = position_jitterdodge(.05), size=1) + stat_summary(fun.y=mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..), width = 0.6, size=0.4, linetype = "dashed", position = position_dodge(preserve = "single")) + scale_x_discrete(labels = c(8,12,16,20,24,32)) + theme(legend.position = c(0.55,0.96), legend.direction="horizontal", legend.title=element_blank()) + ylim(0,10) + labs(y=expression("sqrt(Respiration rate)"~ng~O[2]*hr^{-1}*individual^{-1}), x=expression("Age")) RESP_FIG_DAYS8.24_FINAL <- RESP_FIG_DAYS8.24 + theme(axis.text.x = element_text(angle = 0, hjust = 0.5, size=13,color="black"), axis.text.y = element_text(angle = 0, hjust = 0.5, size=13,color="black"), axis.line = element_line(color = 'black'), axis.ticks.length=unit(0.2, "cm"), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14)) RESP_FIG_DAYS8.24_FINAL # view the plot # TWO WAY ANOVA MODEL hist(ALL_DATA_8.24$Resp_rate_ng.mol) # histogram shows positibe skew # model on transformed respiration data RESP_aov <- aov(Resp_rate_ng.mol~Treatment*Day, data = ALL_DATA_8.24) # run two way anova of parental treatment*time summary(RESP_aov) # significant effect of treatment and time # diagnostic tests and plots of model residuals (not transformed) # Shapiro test shapiro.test(residuals(RESP_aov)) # residuals are non-normal - p = 2.381e-05 # hist qq residual diagnostic par(mfrow=c(1,3)) #set plotting configuration par(mar=c(1,1,1,1)) #set margins for plots hist(residuals(RESP_aov)) #plot histogram of residuals boxplot(residuals(RESP_aov)) #plot boxplot of residuals plot(fitted(RESP_aov),residuals(RESP_aov)) qqnorm(residuals(RESP_aov)) # qqplot # TRANSFORM VIA SQRT AND RUN MODEL AGAIN - TEST SHAPRIO.WILK FOR NORMALITY ASSUMPTIONS # model on transformed respiration data ALL_DATA_8.24$Resp_rate_ng.mol_SQRT <- sqrt(ALL_DATA_8.24$Resp_rate_ng.mol) # new column for sqrt of the data RESP_aov.sqrt <- aov(Resp_rate_ng.mol_SQRT~Treatment*Day, data = ALL_DATA_8.24) # run two way anova of parental treatment*time summary(RESP_aov.sqrt) # looses the interaction term effect but keeps the effect of time and treatment seperately # Shapiro test shapiro.test(residuals(RESP_aov.sqrt)) # residuals are normal - p =0.1048 # post-hoc library(lsmeans) # Version: 2.27-62, Date/Publication: 2018-05-11, Depends: methods, R (>= 3.2) # effect of Treatment ------------------------------- # resp.ph <- lsmeans(RESP_aov.sqrt, pairwise ~ Treatment)# pariwise Tukey Post-hoc test between repeated treatments resp.ph # view post hoc summary E1.pairs.RESP.05 <- cld(resp.ph, alpha=.05, Letters=letters) #list pairwise tests and letter display p < 0.05 E1.pairs.RESP.05 # Ambient > Elevated ( Elevated 1.320509) ( Ambient 1.784314) # effect of Day ------------------------------- # resp.day <- lsmeans(RESP_aov.sqrt, pairwise ~ Day)# pariwise Tukey Post-hoc test between repeated treatments resp.day # view post hoc summary resp.day.RESP.05 <- cld(resp.day, alpha=.05, Letters=letters) #list pairwise tests and letter display p < 0.05 resp.day.RESP.05 # day 16 least resp rate all others non sig diff #RESP_FIG_DAYS8.24_FINAL <- # RESP_FIG_DAYS8.24_FINAL + # annotate("text", x=0.85, y=5.56, label = "de", size = 4) + # annotate("text", x=1.2, y=4, label = "abc", size = 4) + # annotate("text", x=1.9, y=10.0, label = "e", size = 4) + # annotate("text", x=2.2, y=4, label = "abc", size = 4) + # annotate("text", x=2.85, y=3.5, label = "ab", size = 4) + # annotate("text", x=3.2, y=2.2, label = "a", size = 4) + # annotate("text", x=3.85, y=8, label = "cde", size = 4) + # annotate("text", x=4.2, y=4.8, label = "ab", size = 4) + # annotate("text", x=4.85, y=8.6, label = "bcde", size = 4) + # annotate("text", x=5.2, y=5.0, label = "bcd", size = 4) # RESP_FIG_DAYS8.24_FINAL #save file to output ggsave(file="Output/Larvae.resp.plot.sqrt.pdf", RESP_FIG_DAYS8.24_FINAL, width = 12, height = 8, units = c("in")) ALL_DATA_table <- ALL_DATA %>% group_by(Day,Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ng.mol), max_resp = max(Resp_rate_ng.mol), min_resp = min(Resp_rate_ng.mol), sd_resp = sd(Resp_rate_ng.mol), SEM = ((sd(Resp_rate_ng.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order ALL_DATA_table # view table - looks like the LARVAE resp was no different from the blanks ################################################### TEST LARVAE FROM OTHER POOLS ################################# # UMBONE LARVAE ----------------------------------------------------------------- UMBONEresp_all <- x %>% filter((substr(x$Date, 1,9)) == "20190322") # call only resp values of juveniles UMBONEresp_blanks <- UMBONEresp_all %>% filter(UMBONEresp_all$Tank.ID == "Blank") # call only blanks UMBONEresp_blankMEANS <- UMBONEresp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value UMBONEresp_geoduck <- UMBONEresp_all %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) UMBONEresp_geoduck$Resp_rate_ug.mol <- ((((((abs(UMBONEresp_geoduck$Lpc)) - (UMBONEresp_blankMEANS$mean_Lpc))*(0.08/1000))*(60))*31.998)/(UMBONEresp_geoduck$length_number.individuals)) UMBONEresp_geoduck$Resp_rate_ug.mol # units in ug O2/hr/individual UMBONEresp_table_treatments_ALL <- UMBONEresp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order UMBONEresp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # Dhinge LARVAE on 20190207 Dhingeresp_all <- x %>% filter((substr(x$Date, 1,9)) == "20190207") # run 1 Dhingeresp_RUN_1 <- Dhingeresp_all %>% filter((Dhingeresp_all$RUN) == 1)# call Dhingeresp_blanks_RUN_1 <- Dhingeresp_RUN_1 %>% filter(Dhingeresp_RUN_1$Tank.ID == "Blank") # call only blanks Dhingeresp_blankMEANS_RUN_1 <- Dhingeresp_blanks_RUN_1 %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value Dhingeresp_geoduck_RUN_1 <- Dhingeresp_RUN_1 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) Dhingeresp_geoduck_RUN_1$Resp_rate_ug.mol <- ((((((abs(Dhingeresp_geoduck_RUN_1$Lpc)) - (Dhingeresp_blankMEANS_RUN_1$mean_Lpc))*(0.08/1000))*(60))*31.998)/(Dhingeresp_geoduck_RUN_1$length_number.individuals)) Dhingeresp_geoduck_RUN_1$Resp_rate_ug.mol # units in ug O2/hr/individual Dhingeresp_table_treatments_RUN_1 <- Dhingeresp_geoduck_RUN_1 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order Dhingeresp_table_treatments_RUN_1 # view table - looks like the LARVAE resp was no different from the blanks # run 2 Dhingeresp_RUN_2 <- Dhingeresp_all %>% filter((Dhingeresp_all$RUN) == 2)# call only resp values of juveniles Dhingeresp_blanks_RUN_2 <- Dhingeresp_RUN_2 %>% filter(Dhingeresp_RUN_2$Tank.ID == "Blank") # call only blanks Dhingeresp_blankMEANS_RUN_2 <- Dhingeresp_blanks_RUN_2 %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value Dhingeresp_geoduck_RUN_2 <- Dhingeresp_RUN_2 %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) Dhingeresp_geoduck_RUN_2$Resp_rate_ug.mol <- ((((((abs(Dhingeresp_geoduck_RUN_2$Lpc)) - (Dhingeresp_blankMEANS_RUN_2$mean_Lpc))*(0.08/1000))*(60))*31.998)/(Dhingeresp_geoduck_RUN_2$length_number.individuals)) Dhingeresp_geoduck_RUN_2$Resp_rate_ug.mol # units in ug O2/hr/individual Dhingeresp_table_treatments_RUN_2 <- Dhingeresp_geoduck_RUN_2 %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order Dhingeresp_table_treatments_RUN_2 # view table - looks like the LARVAE resp was no different from the blanks # EMBRYOS -- # analysis of EMBRYOS resp - from 20190131 LARVAEresp_all <- x %>% filter((substr(x$Date, 1,9)) == "20190131") # call only resp values of juveniles LARVAEresp_blanks <- LARVAEresp_all %>% filter(LARVAEresp_all$Tank.ID == "Blank") # call only blanks LARVAEresp_blankMEANS <- LARVAEresp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value LARVAEresp_geoduck <- LARVAEresp_all %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) LARVAEresp_geoduck$Resp_rate_ug.mol <- ((((((abs(LARVAEresp_geoduck$Lpc)) - (LARVAEresp_blankMEANS$mean_Lpc))*(4/1000))*(60))*31.998)/(LARVAEresp_geoduck$length_number.individuals)) LARVAEresp_geoduck$Resp_rate_ug.mol # RESPIRATION SUMMARY TABLE LARVAEresp_table_treatments_ALL <- LARVAEresp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order LARVAEresp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # analysis of LARVAE resp - from 20190131 LARVAEresp_all <- x %>% filter((substr(x$Date, 1,9)) == "20190207") # call only resp values of juveniles LARVAEresp_blanks <- LARVAEresp_all %>% filter(LARVAEresp_all$Tank.ID == "Blank") # call only blanks LARVAEresp_blankMEANS <- LARVAEresp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value LARVAEresp_geoduck <- LARVAEresp_all %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) LARVAEresp_geoduck$Resp_rate_ug.mol <- ((((((abs(LARVAEresp_geoduck$Lpc)) - (LARVAEresp_blankMEANS$mean_Lpc))*(4/1000))*(60))*31.998)/(LARVAEresp_geoduck$length_number.individuals)) LARVAEresp_geoduck$Resp_rate_ug.mol # RESPIRATION SUMMARY TABLE LARVAEresp_table_treatments_ALL <- LARVAEresp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), max_resp = max(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order LARVAEresp_table_treatments_ALL # view table - looks like the LARVAE resp was no different from the blanks # analysis of juvenile resp 150d post summer experiments JUVresp_all <- x %>% filter((substr(x$Notes, 1,9)) == "juveniles") # call only resp values of juveniles JUVresp_blanks <- JUVresp_all %>% filter(JUVresp_all$Tank.ID == "Blank") # call only blanks JUVresp_blankMEANS <- JUVresp_blanks %>% summarise(mean_Lpc = mean(abs(Lpc)),mean_Leq = mean(abs(Leq)), mean_Lz = mean(abs(Lz))) # summarize the blanks into a mean value JUVresp_geoduck <- JUVresp_all %>% filter(!is.na(length_number.individuals)) # remove the NAs from the number of individuals (these are the blanks) JUVresp_geoduck$Resp_rate_ug.mol <- ((((((abs(JUVresp_geoduck$Lpc)) - (JUVresp_blankMEANS$mean_Lpc))*(4/1000))*(60))*31.998)/(JUVresp_geoduck$length_number.individuals)) JUVresp_geoduck$Resp_rate_ug.mol # RESPIRATION SUMMARY TABLE JUVresp_table_treatments_ALL <- JUVresp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order JUVresp_table_treatments_ALL # view table # RESP: INITIAL TREATMENT sUMMRAY TABLE JUVresp_table_treatments_INITIAL <- JUVresp_geoduck %>% group_by(Treat.initial) %>% #group the dataset by INITIAL TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order JUVresp_table_treatments_INITIAL # view table # RESP: SECODNARY TREATMENT SUMMARY TABLE JUVresp_table_treatments_SECONDARY<- JUVresp_geoduck %>% group_by(Treat.Secondary) %>% #group the dataset by SECONDARY TREATMENT summarise(mean_resp = mean(Resp_rate_ug.mol), min_resp = min(Resp_rate_ug.mol), sd_resp = sd(Resp_rate_ug.mol), SEM = ((sd(Resp_rate_ug.mol))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_resp)) # makes table in descending order JUVresp_table_treatments_SECONDARY # view table # RUN A TWO WAY ANOVA ON INITIAL AND SECONDARY TREATMENT ON RESP JUVresp.mod <- aov(Resp_rate_ug.mol~Treat.initial*Treat.Secondary, data = JUVresp_geoduck) anova(JUVresp.mod) TukeyHSD(JUVresp.mod) # tukey HSD of the entire model shows a signifcant difference between the E×E and E×A treatments par(mfrow=c(1,3)) #set plotting configuration par(mar=c(1,1,1,1)) #set margins for plots shapiro.test((residuals(JUVresp.mod))) hist(residuals(JUVresp.mod)) #plot histogram of residuals boxplot(residuals(JUVresp.mod)) #plot boxplot of residuals plot(fitted(JUVresp.mod),residuals(JUVresp.mod)) library(Rmisc) sum_JUVresp_means <- summarySE(JUVresp_geoduck, measurevar="Resp_rate_ug.mol", groupvars=c("Treat.Secondary")) # summarize previous table for overall treatment sum_JUVresp_means # view the table percentdiff <- ((sum_JUVresp_means[1,3] - sum_JUVresp_means[2,3])/sum_JUVresp_means[1,3])*100 # calculate percent difference percentdiff # 57.58% greater shell met activity from animals initally exposed to ambient under intiial trial # SHELL SIZE SUMMARY TABLE JUVsize_table_treatments_ALL <- JUVresp_geoduck %>% group_by(Treatment) %>% #group the dataset by BOTH INITIAL AND SECONDARY TREATMENT summarise(mean_size = mean(length_number.individuals), min_size = min(length_number.individuals), sd_size = sd(length_number.individuals), SEM = ((sd(length_number.individuals))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_size)) # makes table in descending order JUVsize_table_treatments_ALL # view table - IMPORTANT - looks like initial exposure exposure has the greatest shell size! # SIZE: INITIAL TREATMENT sUMMRAY TABLE JUVsize_table_treatments_INITIAL <- JUVresp_geoduck %>% group_by(Treat.initial) %>% #group the dataset by INITIAL TREATMENT summarise(mean_size = mean(length_number.individuals), min_size = min(length_number.individuals), sd_size = sd(length_number.individuals), SEM = ((sd(length_number.individuals))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_size)) # makes table in descending order JUVsize_table_treatments_INITIAL # view table - further exemplifies the difference in shell size from the initial treatment # SIZE: SECODNARY TREATMENT SUMMARY TABLE JUVsize_table_treatments_SECONDARY<- JUVresp_geoduck %>% group_by(Treat.Secondary) %>% #group the dataset by SECONDARY TREATMENT summarise(mean_size = mean(length_number.individuals), min_size = min(length_number.individuals), sd_size = sd(length_number.individuals), SEM = ((sd(length_number.individuals))/sqrt(n())), count =n()) %>% # get the count by leaving n open arrange(desc(min_size)) # makes table in descending order - however secodary exposure has a shorter shell length JUVsize_table_treatments_SECONDARY # view table # RUN A TWO WAY ANOVA ON TREATMENT AND SIZE 150 D POST EXPERIMENT JUVsize.mod <- aov(length_number.individuals~Treat.initial*Treat.Secondary, data = JUVresp_geoduck) anova(JUVsize.mod) # *significant difference under intial treatment and a marginal difference from secondary treatment TukeyHSD(JUVsize.mod) # tukey HSD of the entire model shows a signifcant difference between the A×E and E×A treatments par(mfrow=c(1,3)) #set plotting configuration par(mar=c(1,1,1,1)) #set margins for plots shapiro.test((residuals(JUVsize.mod))) # normal distributed via shapiro wilk test hist(residuals(JUVsize.mod)) #plot histogram of residuals boxplot(residuals(JUVsize.mod)) #plot boxplot of residuals plot(fitted(JUVsize.mod),residuals(JUVsize.mod)) library(Rmisc) sum_JUVsize_means <- summarySE(JUVsize.mod, measurevar="length_number.individuals", groupvars=c("Treat.Secondary")) # summarize previous table for overall treatment sum_JUVsize_means # view the table percentdiff <- ((sum_JUVsize_means[1,3] - sum_JUVsize_means[2,3])/sum_JUVsize_means[1,3])*100 # calculate percent difference percentdiff # 5.8% greater shell length from animals initally exposed to low pH in initial exp trial # PLOTS par(mfrow=c(2,1)) par(mar=c(1,1)) plot_size <- ggplot(JUVsize_table_treatments_ALL, aes(x=Treatment, y=mean_size)) + geom_errorbar(aes(ymin=mean_size-SEM , ymax=mean_size+SEM ), width=.1) + geom_line() + geom_point() + theme_classic() #Set the background color plot_size plot_resp <- ggplot(JUVresp_table_treatments_ALL, aes(x=Treatment, y=mean_resp)) + geom_errorbar(aes(ymin=mean_resp-SEM , ymax=mean_resp+SEM ), width=.1) + geom_line() + geom_point() + theme_classic() #Set the background color plot_resp <file_sep>/RAnalysis/Scripts/rShiny_scripts/Conical_rearing_geoduck.R #rm(list = ls()) library(shiny) ui <- shinyUI(fluidPage( mainPanel( numericInput("tank_volume", "tank_volume (L)", 250 ,min = 0, max = 5000), numericInput("how_many_tanks", "how_many_tanks of the same volume", 4,min = 1, max = 10), numericInput("flow_rate", "flow_rate (LPM)", 0.8,min = 0.00, max = 5.00), numericInput("target_cell_density", "target_cell_density (cells per mL)", 20000,min = 0, max = 1000000), numericInput("feed_conical", "target mL per hour continuous feed", 1000 ,min = 0, max = 1000), numericInput("algae_1", "Algae #1 cells mL-1 (pav, iso, tet, nano, etc.)", 3500000,min = 0, max = 2000000), numericInput("algae_2", "Algae #2 cells mL-1 (pav, iso, tet, nano, etc.)", 3500000,min = 0, max = 2000000), numericInput("algae_3", "Algae #3 cells mL-1 (pav, iso, tet, nano, etc.)", 3500000,min = 0, max = 2000000), textOutput("text_calc")) )) server <- shinyServer(function(input, output,session){ vals <- reactiveValues() observe({ vals$algae_mix_conc <- (input$algae_1 + input$algae_2 + input$algae_3)/3 # total cell concentration of mixed diet vals$x <- input$tank_volume*1000 # convert to cells per milliliter vals$t <- input$target_cell_density # in cells per milliliter vals$q <- input$how_many_tanks vals$f <- input$flow_rate*1000 # convert to milliliters vals$total_cells <- vals$x*vals$t vals$vol <- input$feed_conical vals$assumed_hourly_loss <- (vals$f*60)*vals$t # in cells per milliliter vals$percent_loss_hourly <- (vals$assumed_hourly_loss/vals$total_cells)*100 vals$Liters_algae_initial <- (vals$total_cells/vals$algae_mix_conc)/1000 vals$LPH_feed <- ((vals$percent_loss_hourly/100)*vals$Liters_algae_initial) }) output$text_calc <- renderText({ paste("Initial batch feed per tank (L) =", vals$Liters_algae_initial, "Hourly loss from flow through (cells mL) =", vals$assumed_hourly_loss, "Volume to replenish conical-1 hour-1 (L) =", (vals$assumed_hourly_loss/vals$algae_mix_conc)/1000, "Daily volume: MIXED ALGAE DIET (L) =", ((vals$percent_loss_hourly/100)*vals$Liters_algae_initial)*24*vals$q, "Daily Volume: FILTERED SEAWATER (L) =", ((1000-(((((vals$percent_loss_hourly/100)*vals$Liters_algae_initial)*24*vals$q)/24/vals$q)*input$feed_conical))*(vals$q)*(24))/1000, "How much algae (mL) conical-1 hour-1? =", ((((vals$percent_loss_hourly/100)*vals$Liters_algae_initial)*24*vals$q)/24/vals$q)*1000) }) }) shinyApp(ui = ui, server = server) <file_sep>/README.md # Geoduck_transgenerational_OA This repository contains chemistry and physiology data from a transgenerational study with Pacific Geoduck in spring 2019. More details in regard to the Data and Script TBA as data is collected...
85bb83c25ef09c501292fb589688514fde108d58
[ "Markdown", "R" ]
5
R
SamGurr/Geoduck_transgen_offspring_OA
b6943af94bab2fa8136198a103d37caa7f654456
ececaca9c7c0898262aa1ff9917c63467f529a8f
refs/heads/master
<repo_name>fureloka/Pong<file_sep>/Source/Input/JoystickController.hpp //============================================================================= // Date: 28 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Controller.hpp" namespace Pong { struct SJoystickController : public SController { // STUB! }; } <file_sep>/Source/Graphics/Font.cpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #include "Font.hpp" namespace Pong { CFont::CFont(TTF_Font* font, uchar size) : m_pFont(font), m_size(size) { } CFont::~CFont() { if(m_pFont) { TTF_CloseFont(m_pFont); m_pFont = nullptr; } } TTF_Font* CFont::GetFont() const { return m_pFont; } uchar CFont::GetSize() const { return m_size; } } <file_sep>/Source/Actions/ListAction.cpp //============================================================================= // Date: 06 Jan 2018 // Creator: <NAME> //============================================================================= #include "ListAction.hpp" #include "../Graphics/UI/DropdownList.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { CSetListSelectionAction::CSetListSelectionAction(const std::string& name, const std::string& selection) : m_name(name), m_selection(selection) {} bool CSetListSelectionAction::Execute(Engine& engine) { CDropdownList* list = dynamic_cast<CDropdownList*>(engine.GetSceneManager()->GetUIObjectByName(m_name)); if(!list) { return false; } list->SetSelection(m_selection); return true; } CApplyListSelectionAction::CApplyListSelectionAction(const std::string& name) : m_name(name) {} bool CApplyListSelectionAction::Execute(Engine& engine) { CDropdownList* list = dynamic_cast<CDropdownList*>(engine.GetSceneManager()->GetUIObjectByName(m_name)); if(!list) { return false; } list->ApplySelection(engine); return true; } } <file_sep>/Source/Graphics/UI/Text.hpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "../../Common/Typedef.h" #include "../../Math/Vector4.hpp" #include "../Alignment.hpp" #include "../Texture.hpp" #include <string> namespace Pong { class Engine; class CText : public CUIObject { std::string m_text; std::string m_font; SVector2<float> m_textPosition; SVector2<float> m_textSize; SVector2<float> m_textOffset; SVector4<uchar> m_fontColour; CTexture* m_pTextTexture; bool m_bTextChanged; public: CText(); CText(int id, const std::string& name); CText(int id, const std::string& name, const std::string& text, const std::string& fontName); // Getters std::string GetText() const; std::string GetFont() const; SVector2<float> GetTextPosition() const; SVector2<float> GetTextSize() const; SVector2<float> GetTextOffset() const; SVector4<uchar> GetFontColour() const; CTexture* const GetTexture() const; // Setters void SetText(const std::string& text); void SetFont(const std::string& fontName); void SetFontColour(const SVector4<uchar>& fontColour); void SetOffset(const SVector2<float>& offset); // UIObject IAction* GetAction(short hashName); void SetAction(short hashName, IAction* pAction); void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Managers/Event.cpp //============================================================================= // Date: 29 Dec 2017 // Creator: <NAME> //============================================================================= #include "Event.hpp" #include "../Actions/Action.hpp" namespace Pong { CEvent::CEvent(IAction* pAction) : m_pAction(pAction) {} void CEvent::SetAction(IAction* pAction) { m_pAction = pAction; } bool CEvent::Update(Engine& engine) { if(m_pAction == nullptr) { return true; } bool result = m_pAction->Execute(engine); // TODO: // Get the current time // Check if the current time is greater than the timeout // Execute the action and check if it succeeded // Reset timer but keep the remainder // Otherwise set the time to zero // Return execute result return result; } } <file_sep>/CMakeLists.txt cmake_minimum_required( VERSION 3.5 ) project(Pong) set(bin_output_dir "${PROJECT_SOURCE_DIR}/Bin") set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/CMake") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${bin_output_dir}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${bin_output_dir}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${bin_output_dir}) foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} ) string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG ) set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${bin_output_dir}) set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${bin_output_dir}) set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${bin_output_dir}) endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES ) find_package(SDL2 REQUIRED) if(SDL2_FOUND) include_directories(${SDL2_INCLUDE_DIRS}) message(STATUS "SDL2 Include Dir: " ${SDL2_INCLUDE_DIRS}) endif() find_package(SDL2_image REQUIRED) if(SDL2_image_FOUND) include_directories(${SDL2_IMAGE_INCLUDE_DIRS}) message(STATUS "SDL2_image Include Dir: " ${SDL2_IMAGE_INCLUDE_DIRS}) endif() find_package(SDL2_ttf REQUIRED) if(SDL2_ttf_FOUND) include_directories(${SDL2_TTF_INCLUDE_DIRS}) message(STATUS "SDL2_ttf Include Dir: " ${SDL2_TTF_INCLUDE_DIRS}) endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") if(WIN32) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -nologo -Gm- -EHa- -Od -Oi -WX -W4 -wd4100 -wd4189") add_definitions(-D_CRT_SECURE_NO_WARNINGS) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -pedantic") endif() set(src_files "Source/Actions/EnableAction.cpp" "Source/Actions/EventAction.cpp" "Source/Actions/GameAction.cpp" "Source/Actions/ListAction.cpp" "Source/Actions/MultiAction.cpp" "Source/Actions/QuitAction.cpp" "Source/Actions/SceneAction.cpp" "Source/Actions/VisibilityAction.cpp" "Source/Actions/WindowAction.cpp" "Source/Game/Ball.cpp" "Source/Game/Board.cpp" "Source/Game/Game.cpp" "Source/Game/GameScene.cpp" "Source/Game/MainMenu.cpp" "Source/Game/OptionsMenu.cpp" "Source/Game/PauseMenu.cpp" "Source/Game/Player.cpp" "Source/Graphics/UI/Button.cpp" "Source/Graphics/UI/Canvas.cpp" "Source/Graphics/UI/DropdownList.cpp" "Source/Graphics/UI/DropdownItem.cpp" "Source/Graphics/UI/Panel.cpp" "Source/Graphics/UI/Text.cpp" "Source/Graphics/UI/UIObject.cpp" "Source/Graphics/Font.cpp" "Source/Graphics/Layer.cpp" "Source/Graphics/Renderer.cpp" "Source/Graphics/Texture.cpp" "Source/Graphics/Window.cpp" "Source/Input/InputManager.cpp" "Source/Managers/Event.cpp" "Source/Managers/EventManager.cpp" "Source/Managers/FileManager.cpp" "Source/Managers/FontManager.cpp" "Source/Managers/Scene.cpp" "Source/Managers/SceneManager.cpp" "Source/Managers/TextureManager.cpp" "Source/Utils/DebugOverlay.cpp" "Source/Engine.cpp" "Source/GameObject.cpp" "Source/Object.cpp" "Source/Pong.cpp") add_executable(Pong ${src_files}) set(link_lib ${SDL2_LIBRARIES} ${SDL2_IMAGE_LIBRARIES} ${SDL2_TTF_LIBRARIES}) target_link_libraries(Pong ${link_lib}) <file_sep>/Source/Graphics/Texture.cpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #include "Texture.hpp" namespace Pong { CTexture::CTexture(SDL_Texture* pTexture, int width, int height) : m_pTexture(pTexture), m_width(width), m_height(height) {} CTexture::~CTexture() { if(m_pTexture) { SDL_DestroyTexture(m_pTexture); m_pTexture = nullptr; } } SDL_Texture* CTexture::GetSDLTexture() const { return m_pTexture; } int CTexture::GetWidth() const { return m_width; } int CTexture::GetHeight() const { return m_height; } } <file_sep>/Source/Game/Game.hpp //============================================================================= // Date: 31 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { class Engine; class MainMenu; class OptionsMenu; class PauseMenu; class GameScene; class Game { MainMenu* m_pMainMenu; OptionsMenu* m_pOptionsMenu; PauseMenu* m_pPauseMenu; GameScene* m_pGameScene; public: Game(Engine& engine); ~Game(); }; } <file_sep>/Source/Graphics/Window.cpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #include "Window.hpp" #include "Renderer.hpp" #include "../Utils/Exception.hpp" #include "../Engine.hpp" #include <iostream> #define ERROR(x) std::cout << "CWindow::Error - " << x << std::endl; namespace Pong { CWindow::CWindow(const std::string& title, int width, int height, int displayIndex) : m_title(title), m_displayIndex(displayIndex), m_bIsRunning(false) { m_windowResolution = {width, height}; m_windowMode.mode = EWindowMode::Windowed; if(SDL_Init(SDL_INIT_VIDEO) != 0) { throw CException(SDL_GetError()); } // Get supported display resolutions int numDisplayModes = SDL_GetNumDisplayModes(m_displayIndex); for(int i = 0; i < numDisplayModes; ++i) { SDL_DisplayMode sdl_mode; if(SDL_GetDisplayMode(m_displayIndex, i, &sdl_mode) != 0) { throw CException(SDL_GetError()); } // Ignore modes that are less than 60Hz if(sdl_mode.refresh_rate < 60) { continue; } SWindowResolution resolution = { sdl_mode.w, sdl_mode.h }; m_windowResolutions.push_back(resolution); } // TODO: Log this to file. std::cout << "Display Resolutions \n"; std::cout << "=================== \n"; for(auto mode : m_windowResolutions) { std::cout << mode.ToString() << "\n"; } std::cout << std::endl; m_pWindow = SDL_CreateWindow(m_title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, m_windowResolution.width, m_windowResolution.height, SDL_WINDOW_SHOWN); if(!m_pWindow) { throw CException(SDL_GetError()); } m_bIsRunning = true; } CWindow::~CWindow() { if(m_pWindow) { SDL_DestroyWindow(m_pWindow); } SDL_Quit(); } bool CWindow::IsRunning() { return m_bIsRunning; } void CWindow::HandleEvent(SDL_Event* event) { if(event->type == SDL_WINDOWEVENT) { switch(event->window.event) { case SDL_WINDOWEVENT_RESIZED: { m_windowResolution.width = event->window.data1; m_windowResolution.height = event->window.data2; break; } case SDL_WINDOWEVENT_CLOSE: { m_bIsRunning = false; break; } } } else { ERROR("Recived an event that was not a window event: " + std::to_string(event->type)); } } // We do not wish to mess about with the "real" fullscreen mode, thus faking // it with fullscreen desktop bool CWindow::SetWindowMode(EWindowMode eWindowMode) { int result = 0; if(eWindowMode == EWindowMode::Fullscreen) { result = SDL_SetWindowFullscreen(m_pWindow, SDL_WINDOW_FULLSCREEN_DESKTOP); } else { result = SDL_SetWindowFullscreen(m_pWindow, 0); } if(result != 0) { // TODO: Output to log ERROR(SDL_GetError()); return false; } m_windowMode.mode = eWindowMode; return true; } bool CWindow::SetWindowResolution(SWindowResolution resolution, Engine& engine) { if(m_windowMode.mode == EWindowMode::Windowed) { m_windowResolution = resolution; SDL_SetWindowSize(m_pWindow, m_windowResolution.width, m_windowResolution.height); engine.GetRenderer()->SetBufferSize(resolution.width, resolution.height); } else { // We do not know the resolution that SDL sets for fullscreen, thus we need to // retrive it. SDL_GetWindowSize(m_pWindow, &m_windowResolution.width, &m_windowResolution.height); engine.GetRenderer()->SetBufferSize(m_windowResolution.width, m_windowResolution.height); } return true; } SDL_Window* CWindow::GetWindow() { return m_pWindow; } int CWindow::GetWidth() const { return m_windowResolution.width; } int CWindow::GetHeight() const { return m_windowResolution.height; } const SWindowMode& CWindow::GetCurrentWindowMode() const { return m_windowMode; } const SWindowResolution& CWindow::GetWindowResolution() const { return m_windowResolution; } const std::vector<SWindowResolution>& CWindow::GetWindowResolutions() const { return m_windowResolutions; } } <file_sep>/Source/Managers/Scene.cpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #include "Scene.hpp" #define ERROR(x) std::cout << "ERROR - Scene::" << x << std::endl; namespace Pong { CScene::CScene(const std::string& name) : m_name(name) {} CScene::~CScene() {} void CScene::Add(CCanvas* pCanvas) { auto duplicate = m_canvasses.find(pCanvas->GetName()); if(duplicate != m_canvasses.end()) { ERROR("Add - Duplicate Canvas \"" + pCanvas->GetName() + "\" found in scene \"" + m_name + "\"") return; } m_canvasses.insert(std::make_pair(pCanvas->GetName(), pCanvas)); } void CScene::Add(CGameObject* pGameObject) { auto duplicate = m_gameObjects.find(pGameObject->GetName()); if(duplicate != m_gameObjects.end()) { ERROR("Add - Duplicate GameObject \"" + pGameObject->GetName() + "\" found in scene \"" + m_name + "\"") return; } m_gameObjects.insert(std::make_pair(pGameObject->GetName(), pGameObject)); } std::string CScene::GetName() const { return m_name; } CGameObject* CScene::GetGameObjectByName(const std::string& name) { for(auto object : m_gameObjects) { if(object.first == name) { return object.second; } } return nullptr; } CUIObject* CScene::GetUIObjectByName(const std::string& name) { for(auto object : m_canvasses) { if(object.first == name) { return object.second; } else { CUIObject* pObject = object.second->GetUIObjectByName(name); if(pObject != nullptr) { return pObject; } } } return nullptr; } void CScene::Update(Engine& engine) { // Update game objects for(auto gameObject : m_gameObjects) { gameObject.second->Update(engine); } // Update user interface for(auto uiObject : m_canvasses) { uiObject.second->Update(engine); } } void CScene::Render(Engine& engine) const { // Render game objects for(auto gameObject : m_gameObjects) { gameObject.second->Render(engine); } // Render user interface for(auto uiObject : m_canvasses) { uiObject.second->Render(engine); } } } <file_sep>/Source/Managers/FileManager.hpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include <string> namespace Pong { class CFileManager { std::string m_basePath; std::string m_binPath; std::string m_assetPath; std::string m_fontPath; std::string m_texturePath; public: CFileManager(); const std::string& GetAssetPath() const; const std::string& GetFontPath() const; const std::string& GetTexturePath() const; }; } <file_sep>/Source/Managers/FileManager.cpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #include "FileManager.hpp" #include <SDL2/SDL.h> namespace Pong { CFileManager::CFileManager() { char* pBasePath = SDL_GetBasePath(); if(!pBasePath) { pBasePath = SDL_strdup("./"); } m_basePath = pBasePath; SDL_free(pBasePath); std::size_t found = m_basePath.find("Bin"); if(found == std::string::npos) { m_binPath = m_basePath + "Bin/"; } else { m_binPath = m_basePath; m_basePath.erase(m_basePath.begin()+found, m_basePath.end()); } m_assetPath = m_basePath + "Assets/"; m_fontPath = m_assetPath + "Fonts/"; m_texturePath = m_assetPath + "Textures/"; } const std::string& CFileManager::GetAssetPath() const { return m_assetPath; } const std::string& CFileManager::GetFontPath() const { return m_fontPath; } const std::string& CFileManager::GetTexturePath() const { return m_texturePath; } } <file_sep>/Source/Actions/MultiAction.cpp //============================================================================= // Date: 06 Jan 2018 // Creator: <NAME> //============================================================================= #include "MultiAction.hpp" namespace Pong { void CMultiAction::Add(IAction* pAction) { if(pAction) { m_pActions.push_back(pAction); } } bool CMultiAction::Execute(Engine& engine) { for(auto action : m_pActions) { if(action) { action->Execute(engine); } } return true; } } <file_sep>/Source/Graphics/UI/DropdownList.hpp //============================================================================= // Date: 05 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "DropdownItem.hpp" #include "Text.hpp" #include <vector> namespace Pong { class CDropdownList : public CUIObject { std::vector<CDropdownItem*> m_pItems; CDropdownItem* m_pSelected; CText m_itemText; float m_padding; bool m_bInitialised; bool m_bHovered; bool m_bWasLeftClicked; bool m_bListExpanded; bool m_bItemSelected; // Methods void OnHover(Engine& engine, bool bIsWithinBounds); void OnMouseButtonPressed(Engine& engine, bool bIsWithinBounds); void OnMouseButtonReleased(Engine& engine, bool bIsWithinBounds); bool IsWithinBounds(const SVector2<float>& position) const; public: CDropdownList(); CDropdownList(const std::string& name, const SVector2<float>& position, const SVector2<float>& size, const std::string& defaultItem); void Initialise(Engine& engine); void Add(CDropdownItem* const pItem); void ApplySelection(Engine& engine) const; void SetPadding(float padding); void SetSelection(const std::string& selection); // IUIObject IAction* GetAction(short hashName); void SetAction(short hashName, IAction* action); void SetOffset(const SVector2<float>& offset) override; void SetEnabled(bool bEnabled) override; void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Graphics/UI/Panel.hpp //============================================================================= // Date: 26 Sep 2017 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "../../Common/Typedef.h" #include "../../Math/Vector2.hpp" #include "../Alignment.hpp" #include <vector> namespace Pong { class Engine; class CPanel : public CUIObject { std::vector<CUIObject*> m_objects; public: CPanel(); CPanel(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size, eAlignment alignment); void Add(CUIObject* pObject); void SetVisibility(bool bVisible) override; // UIObject IAction* GetAction(short hashName) override; void SetAction(short hashName, IAction* pAction) override; CUIObject* GetUIObjectByName(const std::string& name) override; void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Graphics/UI/Canvas.hpp //============================================================================= // Date: 20 Sep 2017 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "../Alignment.hpp" #include "../../Common/Typedef.h" #include "../../Math/Vector2.hpp" #include "../../Math/Vector4.hpp" #include <vector> namespace Pong { class CCanvas : public CUIObject { std::vector<CUIObject*> m_pObjects; bool m_bOverlay; public: CCanvas(); CCanvas(int id, const std::string& name); CCanvas(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size); void Add(CUIObject* object); CUIObject* GetUIObjectByName(const std::string& name); // UIObject IAction* GetAction(short hashName) override; void SetAction(short hashName, IAction* pAction) override; void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/GameObject.hpp //============================================================================= // Date: 10 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Object.hpp" #include "Common/Typedef.h" #include "Graphics/Texture.hpp" #include "Math/Vector4.hpp" namespace Pong { class Engine; class CGameObject : public CObject { protected: SVector2<float> m_position; SVector2<float> m_size; SVector2<float> m_offset; SVector4<uchar> m_colour; eTextureID m_eTextureID; bool m_bVisible; public: CGameObject(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size); virtual ~CGameObject(); virtual void Update(Engine& engine); virtual void Render(Engine& engine) const; SVector2<float> GetPosition() const; SVector2<float> GetSize() const; SVector2<float> GetOffset() const; SVector4<uchar> GetColour() const; eTextureID GetTextureID() const; void SetPosition(const SVector2<float>& position); void SetSize(const SVector2<float>& size); void SetOffset(const SVector2<float>& offset); void SetColour(const SVector4<uchar>& colour); }; } <file_sep>/Source/Game/GameScene.hpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #pragma once #include "GameState.hpp" #include "../Managers/Scene.hpp" namespace Pong { class CCanvas; class CText; class Ball; class Board; class Engine; class Player; class GameScene : public CScene { CCanvas* m_pCanvas; Board* m_pBoard; Player* m_pPlayer1; Player* m_pPlayer2; Ball* m_pBall; CText* m_pPlayer1Score; CText* m_pPlayer2Score; SVector2<float> m_boardPosition; SVector2<float> m_boardSize; SVector2<float> m_playerSize; SVector2<float> m_player1Spawn; SVector2<float> m_player2Spawn; SVector2<float> m_ballSize; SVector2<float> m_ballSpawn; float m_playerSpawnHorizontalPadding; float m_playerMoveSpeed; int m_player1Score; int m_player2Score; bool m_bGamePaused; void Reset(); public: GameScene(Engine& engine); virtual ~GameScene(); void ResizeGame(Engine& engine); void AIGame(Engine& engine); void NewGame(Engine& engine); void PauseGame(Engine& engine); void UnpauseGame(Engine& engine); void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Math/Vector4.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Vector3.hpp" #include <algorithm> namespace Pong { template<typename T> struct SVector4 { T x, y, z, w; SVector4<T>() : x(T()), y(T()), z(T()), w(T()) {} SVector4<T>(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {} SVector4<T>(const SVector3<T>& vector, T w) : x(vector.x), y(vector.y), z(vector.z), w(w) {} SVector4<T>(const SVector4<T>& vector) : x(vector.x), y(vector.y), z(vector.z), w(vector.w) {} SVector4<T>& operator()(T x, T y, T z, T w) { this->x = x; this->y = y; this->z = z; this->w = w; } SVector4<T>& operator()(const SVector4<T> vec) { this->x = vec.x; this->y = vec.y; this->z = vec.z; this->w = vec.w; } SVector4<T>& operator=(SVector4<T> rhs) { rhs.swap(*this); return *this; } void swap(SVector4<T>& vector) { std::swap(this->x, vector.x); std::swap(this->y, vector.y); std::swap(this->z, vector.z); std::swap(this->w, vector.w); } friend std::ostream& operator<<(std::ostream& stream, const SVector4<T>& vector) { stream << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w; return stream; } }; } <file_sep>/CMake/FindSDL2_image.cmake #============================================================================= # Copyright 2005-2009 Kitware, Inc. # Copyright 2012 <NAME> # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) # # SDL2_IMAGE_FOUND - System has SDL2_image # SDL2_IMAGE_INCLUDE_DIRS - The SDL2_image include directories # SDL2_IMAGE_LIBRARIES - The libraries needed to use SDL2_image find_path(SDL2_IMAGE_INCLUDE_DIR SDL2/SDL_image.h HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES include/SDL2 include SDL2 PATHS /usr/local /usr /opt ) # 64 bit if(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_IMAGE_LIBRARY SDL2_image HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib64 lib lib/x64 PATHS /opt ) # 32 bit else(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_IMAGE_LIBRARY SDL2_image HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib lib/x86 PATHS /opt ) endif(CMAKE_SIZEOF_VOID_P EQUAL 8) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(SDL2_image DEFAULT_MSG SDL2_IMAGE_LIBRARY SDL2_IMAGE_INCLUDE_DIR) mark_as_advanced(SDL2_IMAGE_INCLUDE_DIR SDL2_IMAGE_LIBRARY) set(SDL2_IMAGE_LIBRARIES ${SDL2_IMAGE_LIBRARY}) set(SDL2_IMAGE_INCLUDE_DIRS ${SDL2_IMAGE_INCLUDE_DIR}) <file_sep>/Source/Managers/EventManager.cpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #include "EventManager.hpp" #include "Event.hpp" #include "../Graphics/Window.hpp" #include "../Input/InputManager.hpp" namespace Pong { CEventManager::CEventManager(CWindow* pWindow, CInputManager* pInputManager) : m_pWindow(pWindow), m_pInputManager(pInputManager) { } short CEventManager::GetGameEventsInQueue() { return m_events.size(); } void CEventManager::AddEvent(const CEvent& event) { m_events.push_back(event); } void CEventManager::AddAction(IAction* pAction) { m_events.push_back(CEvent(pAction)); } void CEventManager::ProcessSystemEvents() { m_pInputManager->Reset(); SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: { m_pWindow->HandleEvent(&event); break; } case SDL_MOUSEMOTION: { m_pInputManager->HandleMouseMotionEvent(&event); break; } case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { m_pInputManager->HandleMouseButtonEvent(&event); break; } case SDL_KEYDOWN: case SDL_KEYUP: { m_pInputManager->HandleKeyboardEvent(&event); break; } } } } void CEventManager::UpdateGameEvents(Engine& engine) { for(auto it = m_events.begin(); it != m_events.end();) { if(it->Update(engine)) { it = m_events.erase(it); } else { ++it; } } } bool CEventManager::QuitGame() { SDL_Event event; event.type = SDL_WINDOWEVENT; event.window.event = SDL_WINDOWEVENT_CLOSE; int result = SDL_PushEvent(&event); if(result != 1) { // TODO: Log this to file std::cout << "CEventManager::QuitGame - ERROR: " << SDL_GetError() << std::endl; return false; } return true; } } <file_sep>/Source/Managers/TextureManager.hpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../Graphics/Texture.hpp" #include <SDL2/SDL.h> #include <map> namespace Pong { class CTextureManager { std::map<eTextureID, CTexture*> m_textures; std::string m_texturePath; SDL_Renderer* m_pRenderer; void CreateErrorTexture(); public: CTextureManager(const std::string& texturePath, SDL_Renderer* pRenderer); ~CTextureManager(); void CreateTexture(const std::string& filename, eTextureID textureID); CTexture* GetTexture(eTextureID textureID) const; }; } <file_sep>/Source/Utils/Hash.hpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { template <class T> constexpr T StringToIntT(const char* str) { T hash = 5381; char c = 0; while((c = *str++) != 0) { hash = ((hash << 5) + hash) + c; } return hash; } #define StringToInt16 StringToIntT<short> } <file_sep>/Source/Graphics/Layer.cpp //============================================================================= // Date: 30 May 2017 // Creator: <NAME> //============================================================================= #include "Layer.hpp" #include "UI/UIObject.hpp" #include "Renderer.hpp" #include "../GameObject.hpp" #include "../Engine.hpp" namespace Pong { CLayer::~CLayer() { for(auto it = m_pUIObjects.begin(); it != m_pUIObjects.end();) { delete *it; it = m_pUIObjects.erase(it); } for(auto it = m_pGameObjects.begin(); it != m_pGameObjects.end();) { delete *it; it = m_pGameObjects.erase(it); } } void CLayer::Add(CUIObject* pUIObject) { m_pUIObjects.push_back(pUIObject); } void CLayer::Add(CGameObject* pGameObject) { m_pGameObjects.push_back(pGameObject); } void CLayer::Update(Engine& engine) { for(CGameObject* pGameObject : m_pGameObjects) { pGameObject->Update(engine); } for(CUIObject* pUIObject : m_pUIObjects) { pUIObject->Update(engine); } } void CLayer::Render(Engine& engine) { engine.GetRenderer()->Begin(); for(const CGameObject* pGameObject : m_pGameObjects) { pGameObject->Render(engine); } for(const CUIObject* pUIObject : m_pUIObjects) { pUIObject->Render(engine); } engine.GetRenderer()->End(); engine.GetRenderer()->Flush(); } } <file_sep>/Source/Utils/DebugOverlay.hpp //============================================================================= // Date: 13 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "../Managers/Scene.hpp" #include "../Graphics/UI/Canvas.hpp" #include "../Graphics/UI/Text.hpp" namespace Pong { class DebugOverlay : public CScene { CCanvas m_canvas; CText m_fps; CText m_cursor; CText m_events; float m_time; int m_frames; public: DebugOverlay(); CScene* GetScene() const; void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Managers/TextureManager.cpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #include "TextureManager.hpp" #include "../Utils/Exception.hpp" #include <SDL2/SDL_image.h> #include <iostream> #define ERROR(x) std::cout << "CTextureManager::Error - " << x << std::endl; namespace Pong { CTextureManager::CTextureManager(const std::string& texturePath, SDL_Renderer* pRenderer) : m_texturePath(texturePath), m_pRenderer(pRenderer) { if(!IMG_Init(IMG_INIT_PNG)) { throw CException(IMG_GetError()); } CreateErrorTexture(); } CTextureManager::~CTextureManager() { for(std::map<eTextureID, CTexture*>::iterator itr = m_textures.begin(); itr != m_textures.end(); itr++) { delete (itr->second); } m_textures.clear(); } void CTextureManager::CreateErrorTexture() { SDL_Texture* pErrorTexture = SDL_CreateTexture(m_pRenderer, SDL_PIXELFORMAT_RGB888, SDL_TEXTUREACCESS_TARGET, 32, 32); SDL_SetRenderTarget(m_pRenderer, pErrorTexture); SDL_SetRenderDrawColor(m_pRenderer, 255, 0, 255, 255); SDL_RenderClear(m_pRenderer); SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255); SDL_Rect square = {0, 0, 8, 8}; for(int x = 0; x < 2; ++x) { for(int y = 0; y < 2; ++y) { SDL_RenderFillRect(m_pRenderer, &square); square.y += 16; } square.x += 16; square.y = 0; } square.x = 8; square.y = 8; for(int x = 0; x < 2; ++x) { for(int y = 0; y < 2; ++y) { SDL_RenderFillRect(m_pRenderer, &square); square.y += 16; } square.x += 16; square.y = 8; } SDL_SetRenderTarget(m_pRenderer, nullptr); SDL_RenderCopy(m_pRenderer, pErrorTexture, nullptr, nullptr); CTexture* pTexture = new CTexture(pErrorTexture, 32, 32); m_textures.insert(std::pair<eTextureID, CTexture*>(TEXTUREID_ERROR, pTexture)); } void CTextureManager::CreateTexture(const std::string& filename, eTextureID textureID) { std::string file = m_texturePath + filename; SDL_Surface* pSurface = IMG_Load(file.c_str()); int width = 0; int height = 0; if(!pSurface) { ERROR(IMG_GetError()); } else { width = pSurface->w; height = pSurface->h; } SDL_Texture* pSDLTexture = SDL_CreateTextureFromSurface(m_pRenderer, pSurface); CTexture* pTexture = new CTexture(pSDLTexture, width, height); m_textures.insert(std::pair<eTextureID, CTexture*>(textureID, pTexture)); SDL_FreeSurface(pSurface); } CTexture* CTextureManager::GetTexture(eTextureID textureID) const { std::map<eTextureID, CTexture*>::const_iterator m_iter; m_iter = m_textures.find(textureID); if(m_iter != m_textures.end()) { return m_iter->second; } return nullptr; } } <file_sep>/Source/Math/Vector3.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Vector2.hpp" #include <algorithm> namespace Pong { template<typename T> struct SVector3 { T x, y, z; SVector3<T>() : x(T()), y(T()), z(T()) {} SVector3<T>(T x, T y, T z) : x(x), y(y), z(z) {} SVector3<T>(T x, const SVector2<T>& vector) : x(x), y(vector.y), z(vector.z) {} SVector3<T>(const SVector2<T>& vector, T z) : x(vector.x), y(vector.y), z(z) {} SVector3<T>(const SVector3<T>& vector) : x(vector.x), y(vector.y), z(vector.z) {} SVector3<T>& operator()(T x, T y, T z) { this->x = x; this->y = y; this->z = z; } SVector3<T>& operator()(const SVector3<T> vec) { this->x = vec.x; this->y = vec.y; this->z = vec.z; } SVector3<T> operator+(const SVector3<T> rhs) { SVector3<T> result; result.x = x + rhs.x; result.y = y + rhs.y; result.z = z + rhs.z; return result; } SVector3<T> operator+=(const SVector3<T> rhs) { SVector3<T> result; result.x += x + rhs.x; result.y += y + rhs.y; result.z += z + rhs.z; return result; } SVector3<T>& operator=(SVector3<T> rhs) { rhs.swap(*this); return *this; } void swap(SVector3<T>& vector) { std::swap(this->x, vector.x); std::swap(this->y, vector.y); std::swap(this->z, vector.z); } friend std::ostream& operator<<(std::ostream& stream, const SVector3<T>& vector) { stream << vector.x << ", " << vector.y << ", " << vector.z; return stream; } }; } <file_sep>/Source/Actions/EventAction.cpp //============================================================================= // Date: 14 Jan 2018 // Creator: <NAME> //============================================================================= #include "EventAction.hpp" #include "../Managers/EventManager.hpp" #include "../Engine.hpp" namespace Pong { CAddEventAction::CAddEventAction(IAction* pAction) : m_pAction(pAction) {} bool CAddEventAction::Execute(Engine& engine) { engine.GetEventManager()->AddEvent(m_pAction); return true; } } <file_sep>/Source/Actions/WindowAction.hpp //============================================================================= // Date: 03 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include "../Graphics/Window.hpp" namespace Pong { class CSetWindowModeAction : public IAction { EWindowMode m_eWindowMode; public: CSetWindowModeAction(EWindowMode eWindowMode); bool Execute(Engine& engine) override; }; class CSetWindowResolutionAction : public IAction { SWindowResolution m_resolution; public: CSetWindowResolutionAction(const SWindowResolution& resolution); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Engine.hpp //============================================================================= // Date: 19 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Game/GameState.hpp" #include <string> namespace Pong { class Game; class CEventManager; class CFileManager; class CFontManager; class CInputManager; class CSceneManager; class CTextureManager; class CRenderer; class CWindow; class Engine { Game* m_pGame; EGameState m_eGameState; CEventManager* m_pEventManager; CFileManager* m_pFileManager; CFontManager* m_pFontManager; CInputManager* m_pInputManager; CSceneManager* m_pSceneManager; CTextureManager* m_pTextureManager; CRenderer* m_pRenderer; CWindow* m_pWindow; float m_lastTime; float m_currentTime; float m_deltaTime; public: Engine(); ~Engine(); void Play(); CEventManager* GetEventManager(); CInputManager* GetInputManager(); CSceneManager* GetSceneManager(); CRenderer* GetRenderer(); CWindow* GetWindow(); float GetDeltaTime() const; EGameState GetGameState(); void SetGameState(EGameState eGameState); }; } <file_sep>/Source/Input/KeyboardController.hpp //============================================================================= // Date: 28 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Controller.hpp" #include <map> namespace Pong { enum class EKeyboardKey { None, Escape, W, S, Up, Down }; struct SKeyboardController : public SController { std::map<EKeyboardKey, bool> keys; std::map<EKeyboardKey, eButtonState> keyStates; }; } <file_sep>/Source/Actions/SceneAction.hpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <string> namespace Pong { class CLoadSceneAction : public IAction { std::string m_name; public: CLoadSceneAction(const std::string& name); bool Execute(Engine& engine) override; }; class CUnloadSceneAction : public IAction { std::string m_name; public: CUnloadSceneAction(const std::string& name); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Common/Typedef.h //============================================================================= // Date: 26 Sep 2017 // Creator: <NAME> //============================================================================= #pragma once typedef unsigned char uchar; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; <file_sep>/Source/Game/OptionsMenu.cpp #include "OptionsMenu.hpp" #include "../Actions/EnableAction.hpp" #include "../Actions/EventAction.hpp" #include "../Actions/GameAction.hpp" #include "../Actions/ListAction.hpp" #include "../Actions/SceneAction.hpp" #include "../Actions/WindowAction.hpp" #include "../Utils/Hash.hpp" #include "../Engine.hpp" namespace Pong { OptionsMenu::OptionsMenu(Engine& engine) : CScene("OptionsMenu"), m_canvas(4, "OptionsMenu_Canvas") { Add(&m_canvas); // TODO: Rendering order is bonkers, needs fixing. m_optionsPanel = CPanel(10, "Options_Panel", SVector2<float>(0.0f, 0.0f), SVector2<float>(500.0f, 500.0f), ALIGN_CENTER); m_screenmodeList = CDropdownList("Options_ScreenMode_List", SVector2<float>(0.0f, 20.0f), SVector2<float>(400.0f, 40.0f), engine.GetWindow()->GetCurrentWindowMode().ToString()); m_screenmodeFullscreenItem = CDropdownItem("Options_ScreenMode_Item_Fullscreen", "Fullscreen"); m_screenmodeFullscreenItem.SetAction(StringToInt16("onapply"), new CSetWindowModeAction(EWindowMode::Fullscreen)); m_screenmodeFullscreenActions.Add(new CSetEnabledAction("Options_ScreenSize_List", false)); m_screenmodeFullscreenActions.Add(new CSetListSelectionAction("Options_ScreenMode_List", "Fullscreen")); m_screenmodeFullscreenItem.SetAction(StringToInt16("onclick"), &m_screenmodeFullscreenActions); m_screenmodeList.Add(&m_screenmodeFullscreenItem); m_screenmodeWindowedItem = CDropdownItem("Options_ScreenMode_Item_Windowed", "Windowed"); m_screenmodeWindowedItem.SetAction(StringToInt16("onapply"), new CSetWindowModeAction(EWindowMode::Windowed)); m_screenmodeWindowedActions.Add(new CSetEnabledAction("Options_ScreenSize_List", true)); m_screenmodeWindowedActions.Add(new CSetListSelectionAction("Options_ScreenMode_List", "Windowed")); m_screenmodeWindowedItem.SetAction(StringToInt16("onclick"), &m_screenmodeWindowedActions); m_screenmodeList.Add(&m_screenmodeWindowedItem); m_optionsPanel.Add(&m_screenmodeList); m_screenSize = CDropdownList("Options_ScreenSize_List", SVector2<float>(0.0f, 80.0f), SVector2<float>(400.0f, 40.0f), engine.GetWindow()->GetWindowResolution().ToString()); for(auto mode : engine.GetWindow()->GetWindowResolutions()) { m_screenResolutions.push_back(new CDropdownItem("Options_ScreenSize_Item_" + mode.ToString(), mode.ToString())); m_screenResolutions.back()->SetAction(StringToInt16("onapply"), new CSetWindowResolutionAction(mode)); m_screenResolutions.back()->SetAction(StringToInt16("onclick"), new CSetListSelectionAction("Options_ScreenSize_List", mode.ToString())); m_screenSize.Add(m_screenResolutions.back()); } m_optionsPanel.Add(&m_screenSize); m_optionsDoneButton = CButton(14, "Options_DoneButton", SVector2<float>(-20.0f, -20.0f), SVector2<float>(140.0f, 40.0f), "Done", "DroidSans20"); m_optionsDoneButton.SetAlignment(ALIGN_BOTTOM_RIGHT); m_optionsDoneButtonActions.Add(new CUnloadSceneAction("OptionsMenu")); m_optionsDoneButtonActions.Add(new CLoadSceneAction("MainMenu")); m_optionsDoneButton.SetAction(StringToInt16("onclick"), &m_optionsDoneButtonActions); m_optionsPanel.Add(&m_optionsDoneButton); m_optionsApplyButton = CButton(15, "Options_ApplyButton", SVector2<float>(20.0f, -20.0f), SVector2<float>(140.0f, 40.0f), "Apply", "DroidSans20"); m_optionsApplyButtonActions.Add(new CApplyListSelectionAction("Options_ScreenMode_List")); m_optionsApplyButtonActions.Add(new CApplyListSelectionAction("Options_ScreenSize_List")); m_optionsApplyButtonActions.Add(new CAddEventAction(new CResizeGameAction("Game"))); m_optionsApplyButton.SetAction(StringToInt16("onclick"), &m_optionsApplyButtonActions); m_optionsApplyButton.SetAlignment(ALIGN_BOTTOM_LEFT); m_optionsPanel.Add(&m_optionsApplyButton); m_canvas.Add(&m_optionsPanel); } OptionsMenu::~OptionsMenu() { for(auto itr = m_screenResolutions.begin(); itr != m_screenResolutions.end();) { delete *itr; itr = m_screenResolutions.erase(itr); } } } <file_sep>/Source/Graphics/UI/DropdownItem.hpp //============================================================================= // Date: 05 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "Text.hpp" #include <string> namespace Pong { class CDropdownItem : public CUIObject { CText m_itemText; IAction* m_pOnClickAction; IAction* m_pOnApplyAction; bool m_bEnabled; bool m_bHovered; bool m_bWasLeftClicked; // Methods void OnClick(Engine& engine); void OnHover(Engine& engine, bool bIsWithinBounds); void OnMouseButtonPressed(Engine& engine, bool bIsWithinBounds); void OnMouseButtonReleased(Engine& engine, bool bIsWithinBounds); bool IsWithinBounds(const SVector2<float>& position) const; public: CDropdownItem(); CDropdownItem(const std::string& name, const std::string& itemText); std::string GetText() const; void SetEnabled(bool bEnabled); IAction* GetAction(short hashName); void SetAction(short hashName, IAction* pAction); void SetOffset(const SVector2<float>& offset); void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Managers/FontManager.hpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #include "../Common/Typedef.h" #include "../Graphics/Font.hpp" #include "../Math/Vector4.hpp" #include <map> #include <string> namespace Pong { class CFontManager { std::map<std::string, CFont*> m_fonts; const std::string m_fontFolderPath; public: CFontManager(const std::string& fontFolderPath); ~CFontManager(); bool CreateFont(const std::string& fontFile, uchar size, const std::string& fontName, bool generateAtlas = false); SDL_Surface* GetSurface(const std::string& text, const std::string& fontName, const SVector4<uchar>& colour); }; } <file_sep>/Source/Math/Vector2.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include <algorithm> #include <iostream> namespace Pong { template<typename T> struct SVector2 { T x, y; SVector2<T>() : x(T()), y(T()) {} SVector2<T>(T x, T y) : x(x), y(y) {} SVector2<T>(const SVector2<T>& vector) : x(vector.x), y(vector.y) {} SVector2<T>& operator()(T x, T y) { this->x = x; this->y = y; } SVector2<T>& operator()(const SVector2<T> vec) { this->x = vec.x; this->y = vec.y; } SVector2<T> operator+(const SVector2<T> rhs) { SVector2<T> result; result.x = x + rhs.x; result.y = y + rhs.y; return result; } SVector2<T>& operator=(SVector2<T> rhs) { rhs.swap(*this); return *this; } void swap(SVector2<T>& vector) { std::swap(this->x, vector.x); std::swap(this->y, vector.y); } friend std::ostream& operator<<(std::ostream& stream, const SVector2<T>& vector) { stream << vector.x << ", " << vector.y; return stream; } }; } <file_sep>/Source/Game/Ball.hpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../GameObject.hpp" namespace Pong { class Ball : public CGameObject { public: Ball(int id, const std::string& name); }; } <file_sep>/Source/Game/MainMenu.cpp //============================================================================= // Date: 10 Jan 2017 // Creator: <NAME> //============================================================================= #include "MainMenu.hpp" #include "../Actions/GameAction.hpp" #include "../Actions/QuitAction.hpp" #include "../Actions/SceneAction.hpp" #include "../Utils/Hash.hpp" #include "../Engine.hpp" namespace Pong { MainMenu::MainMenu(Engine& engine) : CScene("MainMenu"), m_title(5, "MainMenu_Title", "Pong Enhanced", "DroidSans40"), m_canvas(4, "MainMenu_Canvas") { m_title.SetAlignment(ALIGN_TOP_CENTER); m_title.SetPosition(SVector2<float>(0, 60.0f)); m_canvas.Add(&m_title); Add(&m_canvas); m_mainMenuPanel = CPanel(6, "MainMenu_Panel", SVector2<float>(0.0f, 40.0f), SVector2<float>(240.0f, 240.0f), ALIGN_CENTER); m_mainMenuPanel.SetColour(SVector4<uchar>(0, 0, 0, 0)); m_newGameButton = CButton(7, "MainMenu_NewGame", SVector2<float>(0.0f, 20.0f), SVector2<float>(220.0f, 40.0f), "New Game", "DroidSans20"); m_newGameActions.Add(new CUnloadSceneAction("MainMenu")); m_newGameActions.Add(new CNewGameAction("Game")); m_newGameButton.SetAction(StringToInt16("onclick"), &m_newGameActions); m_mainMenuPanel.Add(&m_newGameButton); m_optionsButton = CButton(8, "Mainmenu_Options", SVector2<float>(0.0f, 73.0f), SVector2<float>(220.0f, 40.0f), "Options", "DroidSans20"); m_optionsButtonActions.Add(new CUnloadSceneAction("MainMenu")); m_optionsButtonActions.Add(new CLoadSceneAction("OptionsMenu")); m_optionsButton.SetAction(StringToInt16("onclick"), &m_optionsButtonActions); m_mainMenuPanel.Add(&m_optionsButton); m_quitGameButton = CButton(9, "MainMenu_QuitGame", SVector2<float>(0.0f, 126.0f), SVector2<float>(220.0f, 40.0f), "Quit Game", "DroidSans20"); m_quitGameButton.SetAction(StringToInt16("onclick"), new CQuitAction()); m_mainMenuPanel.Add(&m_quitGameButton); m_canvas.Add(&m_mainMenuPanel); } } <file_sep>/Source/Utils/Exception.hpp //============================================================================= // Date: 31 Jan 2018 // Creator: <NAME> //============================================================================= #include <exception> #include <string> namespace Pong { class CException : public std::exception { std::string m_msg; public: CException(const std::string& message) { m_msg = message; } virtual const char* what() const throw() { return m_msg.c_str(); } }; } <file_sep>/Source/Graphics/UI/Button.cpp //============================================================================= // Date: 06 Oct 2017 // Creator: <NAME> //============================================================================= #include "Button.hpp" #include "../Renderer.hpp" #include "../../Input/InputManager.hpp" #include "../../Managers/EventManager.hpp" #include "../../Utils/Hash.hpp" #include "../../Engine.hpp" namespace Pong { CButton::CButton() : CButton(-1, "DefaultButton", SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f), "DefaultButtonText", "DroidSans20") {} CButton::CButton(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size, const std::string& text, const std::string& font) : CUIObject(id, name, position, size), m_text(id, name, text, font), m_bEnabled(true), m_bHovered(false), m_bWasLeftClicked(false), m_bWasRightClicked(false) { m_colour(62, 67, 87, 255); m_eAlignment = ALIGN_TOP_CENTER; m_text.SetColour(SVector4<uchar>(0, 0, 0, 0)); } void CButton::SetEnabled(bool bEnabled) { m_bEnabled = bEnabled; } void CButton::SetVisibility(bool bVisible) { m_bVisible = bVisible; m_text.SetVisibility(bVisible); } bool CButton::IsWithinBounds(const SVector2<float>& position) const { return (position.x >= (m_position.x + m_offset.x) && position.x <= (m_position.x + m_offset.x) + m_size.x && position.y >= (m_position.y + m_offset.y) && position.y <= (m_position.y + m_offset.y) + m_size.y); } bool CButton::OnClick(Engine& engine) { if(m_bEnabled) { if(m_pClickAction != nullptr) { engine.GetEventManager()->AddEvent(m_pClickAction); return true; } } return false; } void CButton::OnHover(Engine& engine, bool withinBounds) { if(withinBounds) { if(!m_bHovered) { m_bHovered = true; if(m_pHoverEnterAction != nullptr) { // TODO: Add action to event queue } m_colour(88, 95, 123, 255); } } else { if(m_bHovered) { m_bHovered = false; if(m_pHoverLeaveAction != nullptr) { // TODO: Add action to event queue } m_colour(62, 67, 87, 255); } } } void CButton::OnMouseButtonPressed(Engine& engine, bool bWithinBounds) { if(!bWithinBounds) { return; } eMouseButton eButton = engine.GetInputManager()->GetMouseButtonPressed(); switch(eButton) { case eMouseButton::LEFT: { m_bWasLeftClicked = true; m_colour(128, 138, 178, 255); engine.GetInputManager()->ClearMouseButtonPressed(); } break; case eMouseButton::RIGHT: { m_bWasRightClicked = true; // TODO: Add right clicked action to event queue engine.GetInputManager()->ClearMouseButtonPressed(); } break; default: break; } } void CButton::OnMouseButtonReleased(Engine& engine, bool bWithinBounds) { eMouseButton eButton = engine.GetInputManager()->GetMouseButtonReleased(); switch(eButton) { case eMouseButton::LEFT: { if(!m_bWasLeftClicked) { break; } m_bWasLeftClicked = false; m_colour(62, 67, 87, 255); if(bWithinBounds) { std::cout << "OnMouseButtonReleased - OnClick()" << std::endl; if(OnClick(engine)) { engine.GetInputManager()->ClearMouseButtonReleased(); } } } break; case eMouseButton::RIGHT: { if(!m_bWasRightClicked) { break; } m_bWasRightClicked = false; if(bWithinBounds) { // TODO: Add right click action to event queue engine.GetInputManager()->ClearMouseButtonReleased(); } } break; default: break; } } //========================================================================= // UIObject //========================================================================= IAction* CButton::GetAction(short hashName) { } void CButton::SetAction(short hashName, IAction* pAction) { // TODO: Implement a hash function to handle this switch(hashName) { case StringToInt16("onclick"): { m_pClickAction = pAction; break; } default: break; } } void CButton::SetOffset(const SVector2<float>& offset) { m_offset = offset; // Calculate offset for centering text SVector2<float> textSize = m_text.GetSize(); float x = m_position.x + m_offset.x + (m_size.x / 2) - (textSize.x / 2); float y = m_position.y + m_offset.y + (m_size.y / 2) - (textSize.y / 2); SVector2<float> textOffset = {x, y}; m_text.SetOffset(textOffset); } void CButton::Update(Engine& engine) { if(!m_bVisible) { return; } bool bIsWithinBounds = IsWithinBounds(engine.GetInputManager()->GetMousePosition()); OnHover(engine, bIsWithinBounds); // TODO: Check mouse conditions and perform actions if(engine.GetInputManager()->WasMouseButtonPressed()) { OnMouseButtonPressed(engine, bIsWithinBounds); } else if(engine.GetInputManager()->WasMouseButtonReleased()) { OnMouseButtonReleased(engine, bIsWithinBounds); } m_text.Update(engine); } void CButton::Render(Engine& engine) const { if(m_bVisible) { engine.GetRenderer()->Submit(this); m_text.Render(engine); } } } <file_sep>/Source/Graphics/Renderer.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../Math/Vector4.hpp" #include "../Common/Typedef.h" #include "UI/UIObject.hpp" #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include <string> namespace Pong { class CText; class CWindow; class CTexture; class CTextureManager; class CFontManager; class CGameObject; class CRenderer { SDL_Renderer* m_pRenderer; SDL_Texture* m_pBufferTexture; CFontManager* m_pFontManager; CTextureManager* m_pTextureManager; CWindow* m_pWindow; int m_iBufferWidth; int m_iBufferHeight; public: CRenderer(CWindow* window); ~CRenderer(); bool CreateRenderer(); void SetBufferSize(int width, int height); void SetTextureManager(CTextureManager* pTextureManager); void SetFontManager(CFontManager* pFontManager); SDL_Renderer* GetRenderer() const; int GetBufferWidth() const; int GetBufferHeight() const; CTexture* GenerateString(const CText* textObject); void DrawString(const CText* object); void Clear(); void Begin(); void Submit(const CUIObject* pUIObject); void Submit(const CGameObject* pGameObject); void End(); void Flush(); void Present(); }; } <file_sep>/Source/Graphics/UI/Text.cpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #include "Text.hpp" #include "../Renderer.hpp" #include "../../Engine.hpp" #define ERROR(x) std::cout << "ERROR - CText:: " << x << std::endl; namespace Pong { CText::CText() : CText(-1, "DefaultText", "DefaultText", "DroidSans20") {} CText::CText(int id, const std::string& name) : CText(id, name, "DefaultText", "DroidSans20") {} CText::CText(int id, const std::string& name, const std::string& text, const std::string& font) : CUIObject(id, name, SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f)), m_text(text), m_font(font), m_fontColour(255, 255, 255, 255), m_bTextChanged(true), m_pTextTexture(nullptr) { m_colour(0, 0, 0, 255); } std::string CText::GetText() const { return m_text; } std::string CText::GetFont() const { return m_font; } SVector2<float> CText::GetTextPosition() const { return m_textPosition; } SVector2<float> CText::GetTextSize() const { return m_textSize; } SVector2<float> CText::GetTextOffset() const { return m_textOffset; } SVector4<uchar> CText::GetFontColour() const { return m_fontColour; } CTexture* const CText::GetTexture() const { return m_pTextTexture; } void CText::SetText(const std::string& text) { m_text = text; m_bTextChanged = true; } void CText::SetFont(const std::string& font) { m_font = font; m_bTextChanged = true; } void CText::SetFontColour(const SVector4<uchar>& fontColour) { m_fontColour = fontColour; m_bTextChanged = true; } void CText::SetOffset(const SVector2<float>& offset) { m_offset = offset; float x = m_position.x + m_offset.x + (m_size.x / 2) - (m_textSize.x / 2); float y = m_position.y + m_offset.y + (m_size.y / 2) - (m_textSize.y / 2); m_textOffset = {x, y}; } //========================================================================= // UIObject //========================================================================= IAction* CText::GetAction(short hashName) { } void CText::SetAction(short hashName, IAction* pAction) { } void CText::Update(Engine& engine) { if(m_bTextChanged && !m_text.empty()) { delete m_pTextTexture; m_pTextTexture = engine.GetRenderer()->GenerateString(this); if(!m_pTextTexture) { ERROR("Update - GenerateString returned nullptr"); } else { m_textSize(m_pTextTexture->GetWidth(), m_pTextTexture->GetHeight()); if(m_size.x < m_textSize.x) { m_size.x = m_textSize.x; } if(m_size.y < m_textSize.y) { m_size.y = m_textSize.y; } m_bTextChanged = false; } } } void CText::Render(Engine& engine) const { if(!m_bVisible) { return; } engine.GetRenderer()->Submit(this); if(!m_text.empty() && m_pTextTexture) { engine.GetRenderer()->DrawString(this); } } } <file_sep>/Source/Actions/VisibilityAction.hpp //============================================================================= // Date: 01 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <string> namespace Pong { class CSetVisibleAction : public IAction { std::string m_name; bool m_bVisible; public: CSetVisibleAction(const std::string& name, bool bVisible); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Actions/EventAction.hpp //============================================================================= // Date: 14 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" namespace Pong { class CAddEventAction : public IAction { IAction* m_pAction; public: CAddEventAction(IAction* pAction); bool Execute(Engine& engine); }; } <file_sep>/Source/Game/Ball.cpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #include "Ball.hpp" namespace Pong { Ball::Ball(int id, const std::string& name) : CGameObject(id, name, SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f)) {} } <file_sep>/Source/Game/Board.hpp //============================================================================= // Date: 13 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "../GameObject.hpp" namespace Pong { class CCanvas; class CText; class CScene; class Board : public CGameObject { CGameObject* m_pTopBar; CGameObject* m_pBottomBar; float m_barHeight; public: Board(int id, const std::string& name); virtual ~Board(); void CreateBoard(Engine& engine); void ResizeBoard(Engine& engine); void Reset(Engine& engine); void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Game/PauseMenu.cpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #include "PauseMenu.hpp" #include "../Actions/GameAction.hpp" #include "../Actions/SceneAction.hpp" #include "../Utils/Hash.hpp" namespace Pong { PauseMenu::PauseMenu() : CScene("PauseMenu") { m_canvas = CCanvas(-1, "PauseMenu_Canvas"); Add(&m_canvas); m_panel = CPanel(-1, "PauseMenu_Panel", SVector2<float>(0.0f, 0.0f), SVector2<float>(240.0f, 133.0f), ALIGN_CENTER); m_canvas.Add(&m_panel); m_continueButton = CButton(-1, "PauseMenu_Button_Continue", SVector2<float>(0.0f, 20.0f), SVector2<float>(220.0f, 40.0f), "Continue", "DroidSans20"); m_continueButton.SetAction(StringToInt16("onclick"), new CUnpauseGameAction("Game")); m_panel.Add(&m_continueButton); m_quitButton = CButton(-1, "PauseMenu_Button_Quit", SVector2<float>(0.0f, 73.0f), SVector2<float>(220.0f, 40.0f), "Quit to Menu", "DroidSans20"); m_quitButtonActions.Add(new CUnloadSceneAction("PauseMenu")); m_quitButtonActions.Add(new CAIGameAction("Game")); m_quitButtonActions.Add(new CLoadSceneAction("MainMenu")); m_quitButton.SetAction(StringToInt16("onclick"), &m_quitButtonActions); m_panel.Add(&m_quitButton); } } <file_sep>/Source/Managers/FontManager.cpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #include "FontManager.hpp" #include "../Common/Typedef.h" #include "../Utils/Exception.hpp" #include <iostream> #define ERROR(x) std::cout << "CFontManager::Error - " << x << std::endl; namespace Pong { CFontManager::CFontManager(const std::string& fontFolderPath) : m_fontFolderPath(fontFolderPath) { if(TTF_Init() != 0) { throw CException(TTF_GetError()); } } CFontManager::~CFontManager() { for(std::map<std::string, CFont*>::iterator iter = m_fonts.begin(); iter != m_fonts.end(); ++iter) { delete iter->second; } } bool CFontManager::CreateFont(const std::string& fontFile, uchar size, const std::string& fontName, bool generateAtlas) { //TODO: Implement atlas generation. std::string fontPath = m_fontFolderPath + fontFile; TTF_Font* ttfFont = TTF_OpenFont(fontPath.c_str(), size); if(!ttfFont) { ERROR(TTF_GetError()); return false; } CFont* font = new CFont(ttfFont, size); m_fonts.insert(std::pair<std::string, CFont*>(fontName, font)); return true; } SDL_Surface* CFontManager::GetSurface(const std::string& text, const std::string& fontName, const SVector4<uchar>& colour) { std::map<std::string, CFont*>::iterator iter; iter = m_fonts.find(fontName); if(iter == m_fonts.end()) { return nullptr; } SDL_Color sdlColour = SDL_Color{colour.x, colour.y, colour.z}; SDL_Surface* texture = TTF_RenderText_Blended(iter->second->GetFont(), text.c_str(), sdlColour); if(!texture) { ERROR(TTF_GetError()); return nullptr; } return texture; } } <file_sep>/Source/Managers/Scene.hpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../Graphics/UI/Canvas.hpp" #include "../GameObject.hpp" #include <map> #include <vector> #include <string> namespace Pong { class CScene { std::string m_name; std::map<std::string, CCanvas*> m_canvasses; std::map<std::string, CGameObject*> m_gameObjects; public: CScene(const std::string& name); virtual ~CScene(); void Add(CCanvas* pCanvas); void Add(CGameObject* pGameObject); std::string GetName() const; CGameObject* GetGameObjectByName(const std::string& name); CUIObject* GetUIObjectByName(const std::string& name); virtual void Update(Engine& engine); virtual void Render(Engine& engine) const; }; } <file_sep>/Source/Game/GameScene.cpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #include "GameScene.hpp" #include "Ball.hpp" #include "Board.hpp" #include "Player.hpp" #include "../Graphics/UI/Canvas.hpp" #include "../Graphics/UI/Text.hpp" #include "../Graphics/Renderer.hpp" #include "../Input/InputManager.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { GameScene::GameScene(Engine& engine) : CScene("Game"), m_pPlayer1Score(nullptr), m_pPlayer2Score(nullptr), m_playerSize(SVector2<float>(20.0f, 140.0f)), m_ballSize(SVector2<float>(40.0f, 40.0f)), m_playerSpawnHorizontalPadding(20.0f), m_playerMoveSpeed(250.0f), m_player1Score(0), m_player2Score(0), m_bGamePaused(false) { m_pCanvas = new CCanvas(-1, "Game_Canvas"); Add(m_pCanvas); m_pPlayer1Score = new CText(-1, "Game_Player1_Score", "00", "DroidSans20"); m_pPlayer1Score->SetAlignment(ALIGN_TOP_LEFT); m_pPlayer1Score->SetPosition(SVector2<float>(40.0f, 2.0f)); m_pPlayer1Score->SetSize(SVector2<float>(100.0f, 26.0f)); m_pPlayer1Score->SetFontColour(SVector4<uchar>(255, 255, 255, 255)); m_pCanvas->Add(m_pPlayer1Score); m_pPlayer2Score = new CText(-1, "Game_Player2_Score", "00", "DroidSans20"); m_pPlayer2Score->SetAlignment(ALIGN_TOP_RIGHT); m_pPlayer2Score->SetPosition(SVector2<float>(-40.0f, 2.0f)); m_pPlayer2Score->SetSize(SVector2<float>(100.0f, 26.0f)); m_pPlayer2Score->SetFontColour(SVector4<uchar>(255, 255, 255, 255)); m_pCanvas->Add(m_pPlayer2Score); m_pBoard = new Board(-1, "Game_Board"); m_pBoard->CreateBoard(engine); m_boardPosition = m_pBoard->GetPosition(); m_boardSize = m_pBoard->GetSize(); Add(m_pBoard); SVector2<float> boardMidPoint = {(m_boardPosition.x + m_boardSize.x) / 2, (m_boardPosition.y + m_boardSize.y) / 2}; m_pPlayer1 = new Player(-1, "Game_Player1"); m_player1Spawn = {m_playerSpawnHorizontalPadding, boardMidPoint.y - (m_playerSize.y / 2) }; m_pPlayer1->SetPosition(m_player1Spawn); m_pPlayer1->SetSize(SVector2<float>(m_playerSize.x, m_playerSize.y)); m_pPlayer1->SetColour(SVector4<uchar>(255, 255, 255, 255)); Add(m_pPlayer1); m_pPlayer2 = new Player(-1, "Game_Player2"); m_player2Spawn = {m_boardSize.x - m_playerSize.x - m_playerSpawnHorizontalPadding, boardMidPoint.y - (m_playerSize.y / 2)}; m_pPlayer2->SetPosition(m_player2Spawn); m_pPlayer2->SetSize(SVector2<float>(m_playerSize.x, m_playerSize.y)); m_pPlayer2->SetColour(SVector4<uchar>(255, 255, 255, 255)); Add(m_pPlayer2); m_pBall = new Ball(-1, "Game_Ball"); m_ballSpawn = {boardMidPoint.x - (m_ballSize.x / 2), boardMidPoint.y - (m_ballSize.y / 2)}; m_pBall->SetPosition(m_ballSpawn); m_pBall->SetSize(SVector2<float>(m_ballSize.x, m_ballSize.y)); m_pBall->SetColour(SVector4<uchar>(255, 255, 255, 255)); Add(m_pBall); } GameScene::~GameScene() { delete m_pBall; delete m_pPlayer2; delete m_pPlayer1; delete m_pBoard; delete m_pPlayer2Score; delete m_pPlayer1Score; delete m_pCanvas; } void GameScene::Reset() { m_player1Score = 0; m_player2Score = 0; m_bGamePaused = false; m_pPlayer1->SetPosition(m_player1Spawn); m_pPlayer2->SetPosition(m_player2Spawn); m_pBall->SetPosition(m_ballSpawn); } void GameScene::ResizeGame(Engine& engine) { m_pBoard->ResizeBoard(engine); m_boardPosition = m_pBoard->GetPosition(); m_boardSize = m_pBoard->GetSize(); SVector2<float> boardMidPoint = {(m_boardPosition.x + m_boardSize.x) / 2, (m_boardPosition.y + m_boardSize.y) / 2}; m_player1Spawn = {m_playerSpawnHorizontalPadding, boardMidPoint.y - (m_playerSize.y / 2) }; m_pPlayer1->SetPosition(m_player1Spawn); m_player2Spawn = {m_boardSize.x - m_playerSize.x - m_playerSpawnHorizontalPadding, boardMidPoint.y - (m_playerSize.y / 2)}; m_pPlayer2->SetPosition(m_player2Spawn); m_ballSpawn = {boardMidPoint.x - (m_ballSize.x / 2), boardMidPoint.y - (m_ballSize.y / 2)}; m_pBall->SetPosition(m_ballSpawn); } void GameScene::AIGame(Engine& engine) { engine.SetGameState(EGameState::MainMenu); Reset(); } void GameScene::NewGame(Engine& engine) { engine.SetGameState(EGameState::Playing); Reset(); } void GameScene::PauseGame(Engine& engine) { if(!m_bGamePaused) { engine.SetGameState(EGameState::Paused); engine.GetSceneManager()->LoadScene("PauseMenu"); m_bGamePaused = true; } } void GameScene::UnpauseGame(Engine& engine) { if(m_bGamePaused) { engine.SetGameState(EGameState::Playing); engine.GetSceneManager()->UnloadScene("PauseMenu"); m_bGamePaused = false; } } void GameScene::Update(Engine& engine) { CScene::Update(engine); switch(engine.GetGameState()) { case EGameState::MainMenu: { // TODO: Implement AI } break; case EGameState::Playing: { if(engine.GetInputManager()->WasKeyboardKeyReleased()) { EKeyboardKey key = engine.GetInputManager()->GetKeyboardKeyReleased(); switch(key) { case EKeyboardKey::Escape: { PauseGame(engine); engine.GetInputManager()->ClearKeyboardKeyReleased(); break; } default: break; } } // Player 1 SVector2<float> mouse_position = engine.GetInputManager()->GetMousePosition(); SVector2<float> playerPosition = m_pPlayer1->GetPosition(); float newYPosition = 0.0f; // Checks if the mouse cursor is above or below the player, and that the difference is greater than the deadzone. if((playerPosition.y > (mouse_position.y - m_playerSize.y / 2)) && ((playerPosition.y - (mouse_position.y - m_playerSize.y / 2)) > 1.0f)) { newYPosition = playerPosition.y - (m_playerMoveSpeed * engine.GetDeltaTime()); } else if((playerPosition.y < (mouse_position.y - m_playerSize.y / 2)) && ((mouse_position.y - playerPosition.y) > 1.0f)) { newYPosition = playerPosition.y + (m_playerMoveSpeed * engine.GetDeltaTime()); } else { newYPosition = playerPosition.y; } if(newYPosition < m_boardPosition.y) { m_pPlayer1->SetPosition(SVector2<float>(m_playerSpawnHorizontalPadding, m_boardPosition.y)); } else if((newYPosition + m_playerSize.y) > m_boardSize.y) { m_pPlayer1->SetPosition(SVector2<float>(m_playerSpawnHorizontalPadding, m_boardSize.y - m_playerSize.y)); } else { m_pPlayer1->SetPosition(SVector2<float>(m_playerSpawnHorizontalPadding, newYPosition)); } // Player 2 SVector2<float> player_position = m_pPlayer2->GetPosition(); newYPosition = 0.0f; if(engine.GetInputManager()->GetKeyboardKeyDown(EKeyboardKey::W)) { newYPosition = player_position.y - (m_playerMoveSpeed * engine.GetDeltaTime()); } else if(engine.GetInputManager()->GetKeyboardKeyDown(EKeyboardKey::S)) { newYPosition = player_position.y + (m_playerMoveSpeed * engine.GetDeltaTime()); } else { newYPosition = player_position.y; } if(newYPosition < m_boardPosition.y) { m_pPlayer2->SetPosition(SVector2<float>(player_position.x, m_boardPosition.y)); } else if(newYPosition + m_playerSize.y > m_boardSize.y) { m_pPlayer2->SetPosition(SVector2<float>(player_position.x, m_boardSize.y - m_playerSize.y)); } else { m_pPlayer2->SetPosition(SVector2<float>(player_position.x, newYPosition)); } break; } case EGameState::Paused: { if(engine.GetInputManager()->WasKeyboardKeyReleased()) { EKeyboardKey key = engine.GetInputManager()->GetKeyboardKeyReleased(); switch(key) { case EKeyboardKey::Escape: { UnpauseGame(engine); engine.GetInputManager()->ClearKeyboardKeyReleased(); break; } } } } default: break; } } void GameScene::Render(Engine& engine) const { CScene::Render(engine); } } <file_sep>/Source/Actions/EnableAction.hpp //============================================================================= // Date: 10 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <string> namespace Pong { class CSetEnabledAction : public IAction { std::string m_name; bool m_bEnabled; public: CSetEnabledAction(const std::string& name, bool bEnabled); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Actions/SceneAction.cpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #include "SceneAction.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { CLoadSceneAction::CLoadSceneAction(const std::string& name) : m_name(name) {} bool CLoadSceneAction::Execute(Engine& engine) { if(engine.GetSceneManager()->LoadScene(m_name)) { return true; } return false; } CUnloadSceneAction::CUnloadSceneAction(const std::string& name) : m_name(name) {} bool CUnloadSceneAction::Execute(Engine& engine) { if(engine.GetSceneManager()->UnloadScene(m_name)) { return true; } return false; } } <file_sep>/Source/Graphics/UI/Panel.cpp //============================================================================= // Date: 26 Sep 2017 // Creator: <NAME> //============================================================================= #include "Panel.hpp" #include "../Renderer.hpp" #include "../../Engine.hpp" namespace Pong { CPanel::CPanel() : CPanel(-1, "DefaultPanel", SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f), ALIGN_CENTER) {} CPanel::CPanel(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size, eAlignment alignment) : CUIObject(id, name, position, size) { m_colour(204, 204, 204, 255); m_eAlignment = alignment; } void CPanel::Add(CUIObject* pObject) { m_objects.push_back(pObject); } // UIObject IAction* CPanel::GetAction(short hashName) { } void CPanel::SetAction(short hashName, IAction* pAction) { } CUIObject* CPanel::GetUIObjectByName(const std::string& name) { if(name == m_name) { return this; } for(auto object : m_objects) { CUIObject* subObject = object->GetUIObjectByName(name); if(subObject) { return subObject; } } return nullptr; } void CPanel::SetVisibility(bool bVisible) { m_bVisible = bVisible; } void CPanel::Update(Engine& engine) { if(!m_bVisible) { return; } for(CUIObject* object : m_objects) { object->Update(engine); SVector2<float> objectPosition = object->GetPosition(); SVector2<float> objectSize = object->GetSize(); float x, y = 0.0f; eAlignment alignment = object->GetAlignment(); switch(alignment) { case ALIGN_TOP_LEFT: { x = m_position.x + m_offset.x; y = m_position.y + m_offset.y; break; } case ALIGN_TOP_CENTER: { x = m_offset.x + m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_offset.y + m_position.y; break; } case ALIGN_TOP_RIGHT: { x = m_offset.x + m_position.x + m_size.x - objectSize.x; y = m_offset.y + m_position.y; break; } case ALIGN_CENTER_LEFT: { x = m_offset.x + m_position.x; y = m_offset.y + m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_CENTER: { x = m_offset.x + m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_offset.y + m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_CENTER_RIGHT: { x = m_offset.x + m_position.x + m_size.x - objectSize.x; y = m_offset.y + m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_BOTTOM_LEFT: { x = m_offset.x + m_position.x; y = m_offset.y + m_position.y + m_size.y - objectSize.y; break; } case ALIGN_BOTTOM_CENTER: { x = m_offset.x + m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_offset.y + m_position.y + m_size.y - objectSize.y; break; } case ALIGN_BOTTOM_RIGHT: { x = m_offset.x + m_position.x + m_size.x - objectSize.x; y = m_offset.y + m_position.y + m_size.y - objectSize.y; break; } } object->SetOffset(SVector2<float>(x, y)); } } void CPanel::Render(Engine& engine) const { if(!m_bVisible) { return; } engine.GetRenderer()->Submit(this); for(CUIObject* object : m_objects) { object->Render(engine); } } } <file_sep>/Source/Graphics/Layer.hpp //============================================================================= // Date: 30 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include <vector> namespace Pong { class CUIObject; class CGameObject; class Engine; class CLayer { std::vector<CUIObject*> m_pUIObjects; std::vector<CGameObject*> m_pGameObjects; public: ~CLayer(); void Add(CUIObject* pUIObject); void Add(CGameObject* pGameObject); void Update(Engine& engine); void Render(Engine& engine); }; } <file_sep>/Source/Graphics/UI/UIObject.hpp //============================================================================= // Date: 18 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../../Object.hpp" #include "../../Actions/Action.hpp" #include "../Alignment.hpp" #include "../../Common/Typedef.h" #include "../../Math/Vector2.hpp" #include "../../Math/Vector4.hpp" namespace Pong { class Engine; class CUIObject : public CObject { protected: SVector2<float> m_position; SVector2<float> m_size; SVector2<float> m_offset; SVector4<uchar> m_colour; eAlignment m_eAlignment; bool m_bVisible; bool m_bEnabled; protected: CUIObject(int id, const std::string& name); CUIObject(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size); public: virtual ~CUIObject(); // Actions virtual IAction* GetAction(short hashName) = 0; virtual void SetAction(short hashName, IAction* action) = 0; // Getters virtual SVector2<float> GetPosition() const; virtual SVector2<float> GetSize() const; virtual SVector2<float> GetOffset() const; virtual SVector4<uchar> GetColour() const; virtual eAlignment GetAlignment() const; virtual bool GetVisibility() const; virtual CUIObject* GetUIObjectByName(const std::string& name); // Setters virtual void SetPosition(const SVector2<float>& position); virtual void SetSize(const SVector2<float>& size); virtual void SetOffset(const SVector2<float>& offset); virtual void SetColour(const SVector4<uchar>& colour); virtual void SetAlignment(eAlignment eAlign); virtual void SetVisibility(bool bVisible); virtual void SetEnabled(bool bEnabled); // Update and Render virtual void Update(Engine& engine) = 0; virtual void Render(Engine& engine) const = 0; }; } <file_sep>/Source/Graphics/UI/DropdownList.cpp //============================================================================= // Date: 05 Jan 2018 // Creator: <NAME> //============================================================================= #include "DropdownList.hpp" #include "../Renderer.hpp" #include "../Window.hpp" #include "../../Managers/EventManager.hpp" #include "../../Input/InputManager.hpp" #include "../../Utils/Hash.hpp" #include "../../Engine.hpp" namespace Pong { CDropdownList::CDropdownList() : CDropdownList("DefaultDropdownList", SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f), "DefaultItem") {} CDropdownList::CDropdownList(const std::string& name, const SVector2<float>& position, const SVector2<float>& size, const std::string& defaultItem) : CUIObject(-1, name, position, size), m_itemText(-1, name + "_Text", defaultItem, "DroidSans20"), m_padding(0.0f), m_bInitialised(false), m_bHovered(false), m_bWasLeftClicked(false), m_bListExpanded(false), m_bItemSelected(false) { m_itemText.SetPosition(position); m_itemText.SetColour(SVector4<uchar>(0, 0, 0, 0)); m_colour(62, 67, 87, 255); m_eAlignment = ALIGN_TOP_CENTER; m_bEnabled = true; } void CDropdownList::Initialise(Engine& engine) { for(auto item : m_pItems) { if(item->GetText() == m_itemText.GetText()) { m_pSelected = item; m_itemText.SetText(item->GetText()); } item->SetPosition(m_position); item->SetSize(m_size); } m_bInitialised = true; } void CDropdownList::Add(CDropdownItem* const pItem) { if(!pItem) { return; } m_pItems.push_back(pItem); m_bInitialised = false; } void CDropdownList::ApplySelection(Engine& engine) const { if(m_pSelected) { IAction* pAction = m_pSelected->GetAction(StringToInt16("onapply")); if(pAction) { engine.GetEventManager()->AddAction(pAction); } } } void CDropdownList::SetPadding(float padding) { m_padding = padding; } void CDropdownList::SetSelection(const std::string& selection) { for(auto item : m_pItems) { if(item->GetText() == selection) { m_pSelected = item; m_itemText.SetText(item->GetText()); } } } bool CDropdownList::IsWithinBounds(const SVector2<float>& position) const { return (position.x >= (m_position.x + m_offset.x) && position.x <= (m_position.x + m_offset.x) + m_size.x && position.y >= (m_position.y + m_offset.y) && position.y <= (m_position.y + m_offset.y) + m_size.y); } void CDropdownList::OnHover(Engine& engine, bool bIsWithinBounds) { if(bIsWithinBounds) { if(!m_bHovered && !m_bListExpanded) { m_bHovered = true; m_colour(88, 95, 123, 255); } } else { if(m_bHovered && !m_bListExpanded) { m_bHovered = false; m_colour(62, 67, 87, 255); } } } void CDropdownList::OnMouseButtonPressed(Engine& engine, bool bIsWithinBounds) { if(!bIsWithinBounds) { return; } eMouseButton eButton = engine.GetInputManager()->GetMouseButtonPressed(); switch(eButton) { case eMouseButton::LEFT: { m_bWasLeftClicked = true; engine.GetInputManager()->ClearMouseButtonPressed(); } break; default: break; } } void CDropdownList::OnMouseButtonReleased(Engine& engine, bool bIsWithinBounds) { eMouseButton eButton = engine.GetInputManager()->GetMouseButtonReleased(); switch(eButton) { case eMouseButton::LEFT: { if(m_bWasLeftClicked) { m_bWasLeftClicked = false; m_colour(62, 67, 87, 255); } if(bIsWithinBounds) { if(!m_bListExpanded) { m_colour(106, 105, 102, 255); m_bListExpanded = true; for(auto item : m_pItems) { item->SetVisibility(true); } } else { m_bListExpanded = false; for(auto item : m_pItems) { item->SetVisibility(false); } } engine.GetInputManager()->ClearMouseButtonReleased(); } else { if(m_bListExpanded) { m_bListExpanded = false; for(auto item : m_pItems) { item->SetVisibility(false); } } } } break; default: break; } } IAction* CDropdownList::GetAction(short hashName) { } void CDropdownList::SetAction(short hashName, IAction* action) { } void CDropdownList::SetOffset(const SVector2<float>& offset) { m_offset = offset; // Calculate offset for centering text SVector2<float> textSize = m_itemText.GetSize(); float x = m_position.x + m_offset.x + (m_size.x / 2) - (textSize.x / 2); float y = m_offset.y + (m_size.y / 2) - (textSize.y / 2); SVector2<float> textOffset = {x, y}; m_itemText.SetOffset(textOffset); // Item offsets float y_spacing = m_size.y + 5.0f; for(auto item : m_pItems) { item->SetOffset(SVector2<float>(m_offset.x, m_offset.y + y_spacing)); y_spacing += m_size.y + m_padding; } } void CDropdownList::SetEnabled(bool bEnabled) { if((m_bEnabled && bEnabled) || (!m_bEnabled && !bEnabled)) { return; } m_bEnabled = bEnabled; if(m_bEnabled) { m_colour = SVector4<uchar>(62, 67, 87, 255); } else { m_colour = SVector4<uchar>(106, 105, 102, 255); } } void CDropdownList::Update(Engine& engine) { if(!m_bVisible) { return; } if(!m_bInitialised) { Initialise(engine); } m_itemText.Update(engine); if(m_bListExpanded) { for(auto item : m_pItems) { item->Update(engine); } } if(!m_bEnabled) { return; } SVector2<float> position = engine.GetInputManager()->GetMousePosition(); bool bIsWithinBounds = IsWithinBounds(position); OnHover(engine, bIsWithinBounds); if(engine.GetInputManager()->WasMouseButtonPressed()) { OnMouseButtonPressed(engine, bIsWithinBounds); } else if(engine.GetInputManager()->WasMouseButtonReleased()) { OnMouseButtonReleased(engine, bIsWithinBounds); } } void CDropdownList::Render(Engine& engine) const { if(!m_bVisible) { return; } engine.GetRenderer()->Submit(this); m_itemText.Render(engine); if(m_bListExpanded) { for(auto item : m_pItems) { item->Render(engine); } } } } <file_sep>/Source/Actions/Action.hpp //============================================================================= // Date: 25 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { class Engine; class IAction { public: virtual ~IAction() {}; virtual bool Execute(Engine& engine) = 0; }; } <file_sep>/Source/Managers/Event.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { class Engine; class IAction; class CEvent { IAction* m_pAction; public: CEvent(IAction* pAction); void SetAction(IAction* pAction); bool Update(Engine& engine); }; } <file_sep>/Source/Input/MouseController.hpp //============================================================================= // Date: 28 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Controller.hpp" #include "../Math/Vector2.hpp" #include <map> namespace Pong { enum class eMouseButton { NONE, LEFT, MIDDLE, RIGHT, X1, X2, }; struct SMouseController : public SController { SVector2<float> position; SVector2<float> clickPosition; std::map<eMouseButton, bool> buttons; std::map<eMouseButton, eButtonState> states; std::map<eMouseButton, bool> doubleClicks; }; } <file_sep>/Source/Graphics/Texture.hpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include <SDL2/SDL.h> namespace Pong { enum eTextureID { TEXTUREID_NULL, TEXTUREID_ERROR, TEXTUREID_BALL = 10, TEXTUREID_PLAYER_ONE, TEXTUREID_PLAYER_TWO, TEXTUREID_PLAYER_AI }; class CTexture { SDL_Texture* m_pTexture; int m_width, m_height; public: CTexture(SDL_Texture* pTexture, int width, int height); ~CTexture(); SDL_Texture* GetSDLTexture() const; int GetWidth() const; int GetHeight() const; }; } <file_sep>/Source/Graphics/UI/Canvas.cpp //============================================================================= // Date: 20 Sep 2017 // Creator: <NAME> //============================================================================= #include "Canvas.hpp" #include "../Renderer.hpp" #include "../../Common/Typedef.h" #include "../../Engine.hpp" namespace Pong { CCanvas::CCanvas() : CCanvas(-1, "DefaultCanvas") {} CCanvas::CCanvas(int id, const std::string& name) : CUIObject(id, name), m_bOverlay(true) { m_bVisible = false; } CCanvas::CCanvas(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size) : CUIObject(id, name, position, size), m_bOverlay(false) { m_bVisible = false; } void CCanvas::Add(CUIObject* pObject) { m_pObjects.push_back(pObject); } CUIObject* CCanvas::GetUIObjectByName(const std::string& name) { for(auto object : m_pObjects) { CUIObject* subObject = object->GetUIObjectByName(name); if(subObject) { return subObject; } } return nullptr; } //========================================================================= // UIObject //========================================================================= IAction* CCanvas::GetAction(short hashName) { } void CCanvas::SetAction(short hashName, IAction* pAction) { } void CCanvas::Update(Engine& engine) { if(m_bOverlay) { m_size.x = engine.GetRenderer()->GetBufferWidth(); m_size.y = engine.GetRenderer()->GetBufferHeight(); } for(CUIObject* object : m_pObjects) { object->Update(engine); SVector2<float> objectPosition = object->GetPosition(); SVector2<float> objectSize = object->GetSize(); float x, y = 0.0f; eAlignment alignment = object->GetAlignment(); switch(alignment) { case ALIGN_TOP_LEFT: { x = m_position.x; y = m_position.y; break; } case ALIGN_TOP_CENTER: { x = m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_position.y; break; } case ALIGN_TOP_RIGHT: { x = m_position.x + m_size.x - objectSize.x; y = m_position.y; break; } case ALIGN_CENTER_LEFT: { x = m_position.x; y = m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_CENTER: { x = m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_CENTER_RIGHT: { x = m_position.x + m_size.x - objectSize.x; y = m_position.y + (m_size.y / 2) - (objectSize.y / 2); break; } case ALIGN_BOTTOM_LEFT: { x = m_position.x; y = m_position.y + m_size.y - objectSize.y; break; } case ALIGN_BOTTOM_CENTER: { x = m_position.x + (m_size.x / 2) - (objectSize.x / 2); y = m_position.y + m_size.y - objectSize.y; break; } case ALIGN_BOTTOM_RIGHT: { x = m_position.x + m_size.x - objectSize.x; y = m_position.y + m_size.y - objectSize.y; break; } } object->SetOffset(SVector2<float>(x, y)); } } void CCanvas::Render(Engine& engine) const { if(m_bVisible) { engine.GetRenderer()->Submit(this); } for(const CUIObject* object : m_pObjects) { object->Render(engine); } } } <file_sep>/Source/Actions/VisibilityAction.cpp //============================================================================= // Date: 01 Jan 2018 // Creator: <NAME> //============================================================================= #include "VisibilityAction.hpp" #include "../Graphics/UI/UIObject.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { CSetVisibleAction::CSetVisibleAction(const std::string& name, bool bVisible) : m_name(name), m_bVisible(bVisible) {} bool CSetVisibleAction::Execute(Engine& engine) { CUIObject* object = engine.GetSceneManager()->GetUIObjectByName(m_name); if(object != nullptr) { object->SetVisibility(m_bVisible); return true; } return false; } } <file_sep>/Source/Object.hpp //============================================================================= // Date: 01 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include <string> namespace Pong { class CObject { protected: int m_id; std::string m_name; protected: CObject(int id, const std::string& name); public: virtual ~CObject() {}; // Getters virtual int GetID() const; virtual std::string GetName() const; }; } <file_sep>/Source/Input/InputManager.hpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "KeyboardController.hpp" #include "MouseController.hpp" #include "../Math/Vector2.hpp" #include <SDL2/SDL.h> #include <map> namespace Pong { enum class eControllerIndex { KEYBOARD, MOUSE, GAMEPAD_ONE, GAMEPAD_TWO, MAX }; enum eButtonEventType { DOWN, UP, }; class CInputManager { SController* m_pControllers[static_cast<int>(eControllerIndex::MAX)]; // Mouse bool m_bMouseButtonPressed; bool m_bMouseButtonReleased; eMouseButton m_eMouseButtonPressed; eMouseButton m_eMouseButtonReleased; void SetMouseButton(eMouseButton button, eButtonEventType type, eButtonState state, bool dDoubleClick, SMouseController* mouse); // Keyboard bool m_bKeyboardKeyPressed; bool m_bKeyboardKeyReleased; EKeyboardKey m_eKeyboardKeyPressed; EKeyboardKey m_eKeyboardKeyReleased; void SetKeyboardKey(EKeyboardKey key, eButtonEventType type, eButtonState state, SKeyboardController* keyboard); public: CInputManager(); ~CInputManager(); void Reset(); // Mouse void HandleMouseMotionEvent(const SDL_Event* event); void HandleMouseButtonEvent(const SDL_Event* event); void ClearMouseButtonPressed(); void ClearMouseButtonReleased(); SVector2<float> GetMousePosition() const; SVector2<float> GetMouseClickPosition() const; eMouseButton GetMouseButtonPressed() const; eMouseButton GetMouseButtonReleased() const; bool GetMouseButtonDown(eMouseButton button) const; bool GetMouseButtonUp(eMouseButton button) const; bool WasMouseButtonPressed() const; bool WasMouseButtonReleased() const; // Keyboard void HandleKeyboardEvent(const SDL_Event* event); void ClearKeyboardKeyPressed(); void ClearKeyboardKeyReleased(); EKeyboardKey GetKeyboardKeyPressed() const; EKeyboardKey GetKeyboardKeyReleased() const; bool GetKeyboardKeyDown(EKeyboardKey key) const; bool GetKeyboardKeyUp(EKeyboardKey key) const; bool WasKeyboardKeyPressed() const; bool WasKeyboardKeyReleased() const; }; } <file_sep>/Source/Actions/MultiAction.hpp //============================================================================= // Date: 06 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <vector> namespace Pong { class CMultiAction : public IAction { std::vector<IAction*> m_pActions; public: void Add(IAction* pAction); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Engine.cpp //============================================================================= // Date: 19 Dec 2017 // Creator: <NAME> //============================================================================= #include "Engine.hpp" #include "Game/Game.hpp" #include "Graphics/Renderer.hpp" #include "Graphics/Window.hpp" #include "Input/InputManager.hpp" #include "Managers/EventManager.hpp" #include "Managers/FileManager.hpp" #include "Managers/FontManager.hpp" #include "Managers/SceneManager.hpp" #include "Managers/TextureManager.hpp" #include "Utils/DebugOverlay.hpp" #include "Utils/Hash.hpp" namespace Pong { Engine::Engine() { m_pWindow = new CWindow("Pong", 800, 600, 0); m_pInputManager = new CInputManager(); m_pEventManager = new CEventManager(m_pWindow, m_pInputManager); m_pFileManager = new CFileManager(); m_pRenderer = new CRenderer(m_pWindow); m_pTextureManager = new CTextureManager(m_pFileManager->GetTexturePath(), m_pRenderer->GetRenderer()); m_pRenderer->SetTextureManager(m_pTextureManager); m_pFontManager = new CFontManager(m_pFileManager->GetFontPath()); m_pFontManager->CreateFont("DroidSans-Regular.ttf", 12, "DroidSans12"); m_pFontManager->CreateFont("DroidSans-Regular.ttf", 20, "DroidSans20"); m_pFontManager->CreateFont("DroidSans-Regular.ttf", 40, "DroidSans40"); m_pRenderer->SetFontManager(m_pFontManager); m_pSceneManager = new CSceneManager(); m_pGame = new Game(*this); } Engine::~Engine() { delete m_pGame; delete m_pSceneManager; delete m_pFontManager; delete m_pTextureManager; delete m_pRenderer; delete m_pFileManager; delete m_pEventManager; delete m_pInputManager; delete m_pWindow; } CEventManager* Engine::GetEventManager() { return m_pEventManager; } CInputManager* Engine::GetInputManager() { return m_pInputManager; } CSceneManager* Engine::GetSceneManager() { return m_pSceneManager; } CRenderer* Engine::GetRenderer() { return m_pRenderer; } CWindow* Engine::GetWindow() { return m_pWindow; } float Engine::GetDeltaTime() const { return m_deltaTime; } void Engine::SetGameState(EGameState eGameState) { m_eGameState = eGameState; } EGameState Engine::GetGameState() { return m_eGameState; } void Engine::Play() { DebugOverlay debug; m_pSceneManager->AddScene(&debug); m_lastTime = (float)SDL_GetTicks() / 1000.0f; m_currentTime = m_lastTime; m_pSceneManager->LoadScene("DebugOverlay"); while(m_pWindow->IsRunning()) { m_pEventManager->ProcessSystemEvents(); m_pEventManager->UpdateGameEvents(*this); m_pRenderer->Clear(); m_pSceneManager->Update(*this); m_pSceneManager->Render(*this); m_pRenderer->Present(); m_currentTime = (float)SDL_GetTicks() / 1000.0f; m_deltaTime = m_currentTime - m_lastTime; m_lastTime = m_currentTime; } } } <file_sep>/Source/Managers/SceneManager.cpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #include "SceneManager.hpp" #include "../Graphics/Renderer.hpp" #include "../Engine.hpp" namespace Pong { CSceneManager::CSceneManager() { } void CSceneManager::AddScene(CScene* pScene) { m_scenes.insert(std::make_pair(pScene->GetName(), pScene)); } bool CSceneManager::RemoveScene(const std::string& name) { for(auto it = m_scenes.begin(); it != m_scenes.end();) { if(it->first == name) { m_scenes.erase(it); return true; } else { ++it; } } return false; } bool CSceneManager::LoadScene(const std::string& name) { for(auto scene : m_scenes) { if(scene.first == name) { m_pActiveScenes.push_back(scene.second); return true; } } return false; } bool CSceneManager::UnloadScene(const std::string& name) { for(auto Iter = m_pActiveScenes.begin(); Iter != m_pActiveScenes.end();) { if((*Iter)->GetName() == name) { m_pActiveScenes.erase(Iter); return true; } else { ++Iter; } } return false; } CScene* CSceneManager::GetSceneByName(const std::string& name) { for(auto scene : m_pActiveScenes) { if(scene->GetName() == name) { return scene; } } return nullptr; } CUIObject* CSceneManager::GetUIObjectByName(const std::string& name) { for(auto scene : m_pActiveScenes) { CUIObject* object = scene->GetUIObjectByName(name); if(object != nullptr) { return object; } } return nullptr; } CGameObject* CSceneManager::GetGameObjectByName(const std::string& name) { for(auto scene : m_pActiveScenes) { CGameObject* object = scene->GetGameObjectByName(name); if(object != nullptr) { return object; } } return nullptr; } void CSceneManager::Update(Engine& engine) { for(auto scene : m_pActiveScenes) { scene->Update(engine); } } void CSceneManager::Render(Engine& engine) const { engine.GetRenderer()->Begin(); for(auto scene : m_pActiveScenes) { scene->Render(engine); } engine.GetRenderer()->End(); engine.GetRenderer()->Flush(); } } <file_sep>/Source/Graphics/Alignment.hpp //============================================================================= // Date: 19 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { enum eAlignment { ALIGN_TOP_LEFT, ALIGN_TOP_CENTER, ALIGN_TOP_RIGHT, ALIGN_CENTER_LEFT, ALIGN_CENTER, ALIGN_CENTER_RIGHT, ALIGN_BOTTOM_LEFT, ALIGN_BOTTOM_CENTER, ALIGN_BOTTOM_RIGHT }; } <file_sep>/Source/Graphics/UI/UIObject.cpp //============================================================================= // Date: 01 Jan 2017 // Creator: <NAME> //============================================================================= #include "UIObject.hpp" namespace Pong { CUIObject::CUIObject(int id, const std::string& name) : CObject(id, name), m_position(0.0f, 0.0f), m_size(0.0f, 0.0f), m_offset(0.0f, 0.0f), m_colour(0, 0, 0, 255), m_eAlignment(ALIGN_TOP_LEFT), m_bVisible(true), m_bEnabled(true) {} CUIObject::CUIObject(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size) : CObject(id, name), m_position(position), m_size(size), m_offset(0.0f, 0.0f), m_colour(0, 0, 0, 255), m_eAlignment(ALIGN_TOP_LEFT), m_bVisible(true), m_bEnabled(true) {} CUIObject::~CUIObject() {} SVector2<float> CUIObject::GetPosition() const { return m_position; } SVector2<float> CUIObject::GetSize() const { return m_size; } SVector2<float> CUIObject::GetOffset() const { return m_offset; } SVector4<uchar> CUIObject::GetColour() const { return m_colour; } eAlignment CUIObject::GetAlignment() const { return m_eAlignment; } bool CUIObject::GetVisibility() const { return m_bVisible; } CUIObject* CUIObject::GetUIObjectByName(const std::string& name) { if(name == m_name) { return this; } } void CUIObject::SetPosition(const SVector2<float>& position) { m_position = position; } void CUIObject::SetSize(const SVector2<float>& size) { m_size = size; } void CUIObject::SetOffset(const SVector2<float>& offset) { m_offset = offset; } void CUIObject::SetColour(const SVector4<uchar>& colour) { m_colour = colour; } void CUIObject::SetAlignment(eAlignment eAlign) { m_eAlignment = eAlign; } void CUIObject::SetVisibility(bool bVisible) { m_bVisible = bVisible; } void CUIObject::SetEnabled(bool bEnabled) { m_bEnabled = bEnabled; } } <file_sep>/Source/Game/GameState.hpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { enum class EGameState { MainMenu, Playing, Paused, GameOver }; } <file_sep>/Source/Graphics/Font.hpp //============================================================================= // Date: 22 Sep 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../Common/Typedef.h" #include <SDL2/SDL_ttf.h> namespace Pong { class CFont { TTF_Font* m_pFont; uchar m_size; public: CFont(TTF_Font* font, uchar size); ~CFont(); TTF_Font* GetFont() const; uchar GetSize() const; }; } <file_sep>/Source/Object.cpp //============================================================================= // Date: 01 Jan 2018 // Creator: <NAME> //============================================================================= #include "Object.hpp" namespace Pong { CObject::CObject(int id, const std::string& name) : m_id(id), m_name(name) {} int CObject::GetID() const { return m_id; } std::string CObject::GetName() const { return m_name; } } <file_sep>/Source/Game/Board.cpp //============================================================================= // Date: 13 Jan 2018 // Creator: <NAME> //============================================================================= #include "Board.hpp" #include "../Graphics/UI/Canvas.hpp" #include "../Graphics/UI/Text.hpp" #include "../Graphics/Renderer.hpp" #include "../Managers/Scene.hpp" #include "../Engine.hpp" namespace Pong { Board::Board(int id, const std::string& name) : CGameObject(id, name, SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f)), m_pTopBar(nullptr), m_pBottomBar(nullptr), m_barHeight(30.0f) {} Board::~Board() { delete m_pBottomBar; delete m_pTopBar; } void Board::CreateBoard(Engine& engine) { float bufferWidth = (float)engine.GetRenderer()->GetBufferWidth(); float bufferHeight = (float)engine.GetRenderer()->GetBufferHeight(); m_position = {0.0f, m_barHeight}; m_size = {bufferWidth, bufferHeight - m_barHeight}; m_pTopBar = new CGameObject(-1, "Board_TopBar", SVector2<float>(0.0f, 0.0f), SVector2<float>(bufferWidth, m_barHeight)); m_pTopBar->SetColour(SVector4<uchar>(255, 255, 255, 255)); m_pBottomBar = new CGameObject(-1, "Board_BottomBar", SVector2<float>(0.0f, bufferHeight - m_barHeight), SVector2<float>(bufferWidth, bufferHeight)); m_pBottomBar->SetColour(SVector4<uchar>(255, 255, 255, 255)); } void Board::ResizeBoard(Engine& engine) { float bufferWidth = (float)engine.GetRenderer()->GetBufferWidth(); float bufferHeight = (float)engine.GetRenderer()->GetBufferHeight(); m_size = {bufferWidth, bufferHeight - m_barHeight}; m_pTopBar->SetSize(SVector2<float>(bufferWidth, m_barHeight)); m_pBottomBar->SetPosition(SVector2<float>(0.0f, bufferHeight - m_barHeight)); m_pBottomBar->SetSize(SVector2<float>(bufferWidth, bufferHeight)); } void Board::Reset(Engine& engine) { } void Board::Update(Engine& engine) { if(!m_bVisible) { return; } } void Board::Render(Engine& engine) const { if(!m_bVisible) { return; } engine.GetRenderer()->Submit(this); engine.GetRenderer()->Submit(m_pTopBar); engine.GetRenderer()->Submit(m_pBottomBar); } } <file_sep>/Source/Actions/GameAction.cpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #include "GameAction.hpp" #include "../Game/GameScene.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { CResizeGameAction::CResizeGameAction(const std::string& name) : m_name(name) {} bool CResizeGameAction::Execute(Engine& engine) { GameScene* pGameScene = static_cast<GameScene*>(engine.GetSceneManager()->GetSceneByName(m_name)); if(pGameScene) { pGameScene->ResizeGame(engine); return true; } return false; } CAIGameAction::CAIGameAction(const std::string& name) : m_name(name) {} bool CAIGameAction::Execute(Engine& engine) { GameScene* pGameScene = static_cast<GameScene*>(engine.GetSceneManager()->GetSceneByName(m_name)); if(pGameScene) { pGameScene->AIGame(engine); return true; } return false; } CNewGameAction::CNewGameAction(const std::string& name) : m_name(name) {} bool CNewGameAction::Execute(Engine& engine) { GameScene* pGameScene = static_cast<GameScene*>(engine.GetSceneManager()->GetSceneByName(m_name)); if(pGameScene) { pGameScene->NewGame(engine); return true; } return false; } CUnpauseGameAction::CUnpauseGameAction(const std::string& name) : m_name(name) {} bool CUnpauseGameAction::Execute(Engine& engine) { GameScene* pGameScene = static_cast<GameScene*>(engine.GetSceneManager()->GetSceneByName(m_name)); if(pGameScene) { pGameScene->UnpauseGame(engine); return true; } return false; } } <file_sep>/Source/Actions/GameAction.hpp //============================================================================= // Date: 16 Jan 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <string> namespace Pong { class CResizeGameAction : public IAction { std::string m_name; public: CResizeGameAction(const std::string& name); bool Execute(Engine& engine) override; }; class CAIGameAction : public IAction { std::string m_name; public: CAIGameAction(const std::string& name); bool Execute(Engine& engine) override; }; class CNewGameAction : public IAction { std::string m_name; public: CNewGameAction(const std::string& name); bool Execute(Engine& engine) override; }; class CUnpauseGameAction : public IAction { std::string m_name; public: CUnpauseGameAction(const std::string& name); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Graphics/Renderer.cpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #include "Renderer.hpp" #include "UI/Text.hpp" #include "Texture.hpp" #include "Window.hpp" #include "../Common/Typedef.h" #include "../Managers/TextureManager.hpp" #include "../Managers/FontManager.hpp" #include "../GameObject.hpp" #include <iostream> #define ERROR(x) std::cout << "CRenderer::Error - " << x << std::endl; namespace Pong { CRenderer::CRenderer(CWindow* window) : m_pRenderer(nullptr), m_pBufferTexture(nullptr), m_pFontManager(nullptr), m_pTextureManager(nullptr), m_pWindow(window) { if(!m_pWindow) { ERROR("Window pointer is null!") return; } m_pRenderer = SDL_CreateRenderer(m_pWindow->GetWindow(), -1, SDL_RENDERER_ACCELERATED); if(!m_pRenderer) { ERROR(SDL_GetError()) return; } m_iBufferWidth = m_pWindow->GetWidth(); m_iBufferHeight = m_pWindow->GetHeight(); SetBufferSize(m_iBufferWidth, m_iBufferHeight); SDL_SetRenderDrawBlendMode(m_pRenderer, SDL_BLENDMODE_BLEND); } CRenderer::~CRenderer() { if(m_pBufferTexture) { SDL_DestroyTexture(m_pBufferTexture); m_pBufferTexture = nullptr; } if(m_pRenderer) { SDL_DestroyRenderer(m_pRenderer); m_pRenderer = nullptr; } m_pWindow = nullptr; m_pTextureManager = nullptr; m_pFontManager = nullptr; } void CRenderer::SetBufferSize(int width, int height) { m_iBufferWidth = width; m_iBufferHeight = height; if(m_pBufferTexture) { SDL_DestroyTexture(m_pBufferTexture); m_pBufferTexture = nullptr; } m_pBufferTexture = SDL_CreateTexture(m_pRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, m_iBufferWidth, m_iBufferHeight); if(!m_pBufferTexture) { ERROR(SDL_GetError()); } } void CRenderer::SetTextureManager(CTextureManager* pTextureManager) { m_pTextureManager = pTextureManager; } void CRenderer::SetFontManager(CFontManager* pFontManager) { m_pFontManager = pFontManager; } SDL_Renderer* CRenderer::GetRenderer() const { return m_pRenderer; } int CRenderer::GetBufferWidth() const { return m_iBufferWidth; } int CRenderer::GetBufferHeight() const { return m_iBufferHeight; } void CRenderer::Clear() { SDL_SetRenderTarget(m_pRenderer, m_pBufferTexture); SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255); SDL_RenderClear(m_pRenderer); SDL_SetRenderTarget(m_pRenderer, nullptr); } void CRenderer::Begin() { SDL_SetRenderTarget(m_pRenderer, m_pBufferTexture); } void CRenderer::Submit(const CUIObject* pUIObject) { SVector2<float> position = pUIObject->GetPosition(); SVector2<float> offset = pUIObject->GetOffset(); SVector2<float> size = pUIObject->GetSize(); SDL_Rect destination = SDL_Rect{int(offset.x + position.x), int(offset.y + position.y), (int)size.x, (int)size.y}; SVector4<uchar> colour = pUIObject->GetColour(); SDL_SetRenderDrawColor(m_pRenderer, colour.x, colour.y, colour.z, colour.w); SDL_RenderFillRect(m_pRenderer, &destination); } void CRenderer::Submit(const CGameObject* pGameObject) { SVector2<float> position = pGameObject->GetPosition(); SVector2<float> offset = pGameObject->GetOffset(); SVector2<float> size = pGameObject->GetSize(); SDL_Rect destination = SDL_Rect{int(offset.x + position.x), int(offset.y + position.y), (int)size.x, (int)size.y}; eTextureID textureID = pGameObject->GetTextureID(); if(textureID == TEXTUREID_NULL) { SVector4<uchar> colour = pGameObject->GetColour(); SDL_SetRenderDrawColor(m_pRenderer, colour.x, colour.y, colour.z, colour.w); SDL_RenderFillRect(m_pRenderer, &destination); } else { CTexture* pTexture = m_pTextureManager->GetTexture(pGameObject->GetTextureID()); if(pTexture) { SDL_RenderCopy(m_pRenderer, pTexture->GetSDLTexture(), nullptr, &destination); } else { CTexture* pErrorTexture = m_pTextureManager->GetTexture(TEXTUREID_ERROR); SDL_RenderCopy(m_pRenderer, pErrorTexture->GetSDLTexture(), nullptr, &destination); } } } CTexture* CRenderer::GenerateString(const CText* object) { if(object == nullptr) { ERROR("GenerateString: object is nullptr"); return nullptr; } if(m_pFontManager == nullptr) { ERROR("GenerateString: m_pFontManager is nullptr"); return nullptr; } SDL_Surface* sdlSurface = m_pFontManager->GetSurface(object->GetText(), object->GetFont(), object->GetFontColour()); if(!sdlSurface) { ERROR("GenerateStringTexture - FontManager returned nullptr"); return nullptr; } int width = sdlSurface->w; int height = sdlSurface->h; SDL_Texture* sdlTexture = SDL_CreateTextureFromSurface(m_pRenderer, sdlSurface); SDL_FreeSurface(sdlSurface); if(!sdlTexture) { ERROR(SDL_GetError()); return nullptr; } CTexture* texture = new CTexture(sdlTexture, width, height); return texture; } void CRenderer::DrawString(const CText* object) { SVector2<float> position = object->GetTextPosition(); SVector2<float> size = object->GetTextSize(); SVector2<float> offset = object->GetTextOffset(); SDL_Rect destination = SDL_Rect{int(offset.x + position.x), int(offset.y + position.y), (int)size.x, (int)size.y}; SDL_RenderCopy(m_pRenderer, object->GetTexture()->GetSDLTexture(), nullptr, &destination); } void CRenderer::End() { SDL_SetRenderTarget(m_pRenderer, nullptr); } void CRenderer::Flush() { SDL_RenderCopy(m_pRenderer, m_pBufferTexture, nullptr, nullptr); } void CRenderer::Present() { SDL_RenderPresent(m_pRenderer); } } <file_sep>/Source/Game/Game.cpp //============================================================================= // Date: 31 Jan 2018 // Creator: <NAME> //============================================================================= #include "Game.hpp" #include "GameScene.hpp" #include "MainMenu.hpp" #include "OptionsMenu.hpp" #include "PauseMenu.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { Game::Game(Engine& engine) { m_pMainMenu = new MainMenu(engine); engine.GetSceneManager()->AddScene(m_pMainMenu); m_pOptionsMenu = new OptionsMenu(engine); engine.GetSceneManager()->AddScene(m_pOptionsMenu); m_pPauseMenu = new PauseMenu(); engine.GetSceneManager()->AddScene(m_pPauseMenu); m_pGameScene = new GameScene(engine); engine.GetSceneManager()->AddScene(m_pGameScene); engine.GetSceneManager()->LoadScene("Game"); engine.GetSceneManager()->LoadScene("MainMenu"); engine.SetGameState(EGameState::MainMenu); } Game::~Game() { delete m_pGameScene; delete m_pPauseMenu; delete m_pOptionsMenu; delete m_pMainMenu; } } <file_sep>/Source/Actions/WindowAction.cpp //============================================================================= // Date: 04 Jan 2018 // Creator: <NAME> //============================================================================= #include "WindowAction.hpp" #include "../Engine.hpp" namespace Pong { CSetWindowModeAction::CSetWindowModeAction(EWindowMode eWindowMode) : m_eWindowMode(eWindowMode) {} bool CSetWindowModeAction::Execute(Engine& engine) { if(engine.GetWindow()->SetWindowMode(m_eWindowMode)) { return true; } return false; } CSetWindowResolutionAction::CSetWindowResolutionAction(const SWindowResolution& resolution) : m_resolution(resolution) {} bool CSetWindowResolutionAction::Execute(Engine& engine) { if(engine.GetWindow()->SetWindowResolution(m_resolution, engine)) { return true; } return false; } } <file_sep>/Source/Managers/SceneManager.hpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Scene.hpp" namespace Pong { class CSceneManager { std::map<const std::string, CScene*> m_scenes; std::vector<CScene*> m_pActiveScenes; public: CSceneManager(); void AddScene(CScene* scene); bool RemoveScene(const std::string& name); bool LoadScene(const std::string& name); bool UnloadScene(const std::string& name); CScene* GetSceneByName(const std::string& name); CUIObject* GetUIObjectByName(const std::string& name); CGameObject* GetGameObjectByName(const std::string& name); void Update(Engine& engine); void Render(Engine& engine) const; }; } <file_sep>/Source/Actions/ListAction.hpp //============================================================================= // Date: 06 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "Action.hpp" #include <string> namespace Pong { class CSetListSelectionAction : public IAction { std::string m_name; std::string m_selection; public: CSetListSelectionAction(const std::string& name, const std::string& selection); bool Execute(Engine& engine) override; }; class CApplyListSelectionAction : public IAction { std::string m_name; std::string m_selection; public: CApplyListSelectionAction(const std::string& name); bool Execute(Engine& engine) override; }; } <file_sep>/Source/Pong.cpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #include "Engine.hpp" #include <iostream> int main(int argc, char* argv[]) { try { Pong::Engine engine; engine.Play(); } catch(std::exception& ex) { std::cerr << ex.what() << std::endl; } return 0; } <file_sep>/Source/Actions/QuitAction.cpp //============================================================================= // Date: 31 Dec 2017 // Creator: <NAME> //============================================================================= #include "QuitAction.hpp" #include "../Managers/EventManager.hpp" #include "../Engine.hpp" namespace Pong { CQuitAction::CQuitAction() {} bool CQuitAction::Execute(Engine& engine) { return engine.GetEventManager()->QuitGame(); } } <file_sep>/Source/Graphics/UI/Button.hpp //============================================================================= // Date: 06 Oct 2017 // Creator: <NAME> //============================================================================= #pragma once #include "UIObject.hpp" #include "Text.hpp" #include "../../Math/Vector2.hpp" #include "../Alignment.hpp" #include <string> namespace Pong { class CButton : public CUIObject { CText m_text; bool m_bEnabled; bool m_bHovered; bool m_bWasLeftClicked; bool m_bWasRightClicked; IAction* m_pClickAction; IAction* m_pHoverEnterAction; IAction* m_pHoverLeaveAction; bool IsWithinBounds(const SVector2<float>& position) const; bool OnClick(Engine& engine); void OnHover(Engine& engine, bool withinBounds); void OnMouseButtonPressed(Engine& engine, bool bWithinBounds); void OnMouseButtonReleased(Engine& engine, bool bWithinBounds); public: CButton(); CButton(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size, const std::string& text, const std::string& fontName); void SetEnabled(bool bEnabled); void SetVisibility(bool bVisible) override; // UIObject IAction* GetAction(short hashName); void SetAction(short hashName, IAction* action); void SetOffset(const SVector2<float>& offset) override; void Update(Engine& engine) override; void Render(Engine& engine) const override; }; } <file_sep>/Source/Managers/EventManager.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include "Event.hpp" #include <list> namespace Pong { class CWindow; class CInputManager; class CEventManager { CWindow* m_pWindow; CInputManager* m_pInputManager; std::list<CEvent> m_events; public: CEventManager(CWindow* pWindow, CInputManager* pInputManager); short GetGameEventsInQueue(); void AddEvent(const CEvent& event); void AddAction(IAction* action); void ProcessSystemEvents(); void UpdateGameEvents(Engine& engine); bool QuitGame(); }; } <file_sep>/Source/Game/OptionsMenu.hpp //============================================================================= // Date: 01 Feb 2018 // Creator: <NAME> //============================================================================= #pragma once #include "../Actions/MultiAction.hpp" #include "../Graphics/UI/Button.hpp" #include "../Graphics/UI/DropdownList.hpp" #include "../Graphics/UI/DropdownItem.hpp" #include "../Graphics/UI/Panel.hpp" #include "../Managers/Scene.hpp" namespace Pong { class Engine; class OptionsMenu : public CScene { CCanvas m_canvas; CPanel m_optionsPanel; CDropdownList m_screenmodeList; CDropdownList m_screenSize; CDropdownItem m_screenmodeFullscreenItem; CDropdownItem m_screenmodeWindowedItem; CButton m_optionsDoneButton; CButton m_optionsApplyButton; CMultiAction m_screenmodeFullscreenActions; CMultiAction m_screenmodeWindowedActions; CMultiAction m_optionsDoneButtonActions; CMultiAction m_optionsApplyButtonActions; std::vector<CDropdownItem*> m_screenResolutions; public: OptionsMenu(Engine& engine); ~OptionsMenu(); }; } <file_sep>/Source/Graphics/Window.hpp //============================================================================= // Date: 16 May 2017 // Creator: <NAME> //============================================================================= #pragma once #include <SDL2/SDL.h> #include <string> #include <vector> namespace Pong { enum class EWindowMode { Fullscreen, Windowed }; struct SWindowMode { EWindowMode mode; std::string ToString() const { switch(mode) { case EWindowMode::Fullscreen: { return "Fullscreen"; } break; case EWindowMode::Windowed: { return "Windowed"; } default: break; } return std::string(); } }; struct SWindowResolution { int width; int height; std::string ToString() const { return std::to_string(width) + "x" + std::to_string(height); } }; class Engine; class CRenderer; class CWindow { SDL_Window* m_pWindow; std::vector<SWindowResolution> m_windowResolutions; SWindowResolution m_windowResolution; SWindowMode m_windowMode; std::string m_title; int m_displayIndex; bool m_bIsRunning; public: CWindow(const std::string& title, int width, int height, int displayIndex); ~CWindow(); bool IsRunning(); void HandleEvent(SDL_Event* event); bool SetWindowMode(EWindowMode eWindowMode); bool SetWindowResolution(SWindowResolution resolution, Engine& engine); SDL_Window* GetWindow(); int GetWidth() const; int GetHeight() const; const SWindowMode& GetCurrentWindowMode() const; const SWindowResolution& GetWindowResolution() const; const std::vector<SWindowResolution>& GetWindowResolutions() const; }; } <file_sep>/Source/Game/MainMenu.hpp //============================================================================= // Date: 10 Jan 2017 // Creator: <NAME> //============================================================================= #pragma once #include "../Actions/MultiAction.hpp" #include "../Graphics/UI/Button.hpp" #include "../Graphics/UI/Panel.hpp" #include "../Graphics/UI/Text.hpp" #include "../Managers/Scene.hpp" namespace Pong { class Engine; class MainMenu : public CScene { CCanvas m_canvas; CText m_title; CPanel m_mainMenuPanel; CButton m_newGameButton; CButton m_optionsButton; CButton m_quitGameButton; CMultiAction m_newGameActions; CMultiAction m_optionsButtonActions; public: MainMenu(Engine& engine); }; } <file_sep>/Source/Game/Player.hpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "../GameObject.hpp" namespace Pong { class Game; class Player : public CGameObject { public: Player(int id, const std::string& name); }; } <file_sep>/CMake/FindSDL2.cmake #============================================================================= # Copyright 2003-2009 Kitware, Inc. # # CMake - Cross Platform Makefile Generator # Copyright 2000-2014 Kitware, Inc. # Copyright 2000-2011 Insight Software Consortium # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the names of Kitware, Inc., the Insight Software Consortium, # nor the names of their contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= # (To distribute this file outside of CMake, substitute the full # License text for the above reference.) # # SDL2_FOUND - System has SDL2 # SDL2_INCLUDE_DIRS - The SDL2 include directories # SDL2_LIBRARIES - The libraries needed to use SDL2 find_path(SDL2_INCLUDE_DIR SDL2/SDL.h HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES include/SDL2 include SDL2 PATHS /usr/local /usr /opt ) # 64 bit if(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_LIBRARY SDL2 HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib64 lib lib/x64 PATHS /opt ) # 32 bit else(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_LIBRARY SDL2 HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib lib/x86 PATHS /opt ) endif(CMAKE_SIZEOF_VOID_P EQUAL 8) # 64 bit if(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_MAIN_LIBRARY SDL2main HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib64 lib lib/x64 PATHS /opt ) # 32 bit else(CMAKE_SIZEOF_VOID_P EQUAL 8) FIND_LIBRARY(SDL2_MAIN_LIBRARY SDL2main HINTS ${CMAKE_SOURCE_DIR} $ENV{SDL2_DIR} PATH_SUFFIXES lib lib/x86 PATHS /opt ) endif(CMAKE_SIZEOF_VOID_P EQUAL 8) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(SDL2 DEFAULT_MSG SDL2_LIBRARY SDL2_INCLUDE_DIR) mark_as_advanced(SDL2_INCLUDE_DIR SDL2_LIBRARY SDL2_MAIN_LIBRARY) set(SDL2_LIBRARIES ${SDL2_LIBRARY} ${SDL2_MAIN_LIBRARY}) set(SDL2_INCLUDE_DIRS ${SDL2_INCLUDE_DIR}) <file_sep>/Source/Input/InputManager.cpp //============================================================================= // Date: 17 May 2017 // Creator: <NAME> //============================================================================= #include "InputManager.hpp" #include <iostream> #include <string> #define ERROR(x) std::cout << "CInputManager::Error - " << x << std::endl; namespace Pong { CInputManager::CInputManager() : m_bMouseButtonPressed(false), m_bMouseButtonReleased(false), m_eMouseButtonPressed(eMouseButton::NONE), m_eMouseButtonReleased(eMouseButton::NONE), m_bKeyboardKeyPressed(false), m_bKeyboardKeyReleased(false), m_eKeyboardKeyPressed(EKeyboardKey::None), m_eKeyboardKeyReleased(EKeyboardKey::None) { for(unsigned int i = 0; i < static_cast<int>(eControllerIndex::MAX); i++) { m_pControllers[i] = nullptr; } SKeyboardController* keyboard = new SKeyboardController(); keyboard->type = eControllerType::KEYBOARD; keyboard->bIsInitialised = true; m_pControllers[static_cast<int>(eControllerIndex::KEYBOARD)] = keyboard; SMouseController* mouse = new SMouseController(); mouse->type = eControllerType::MOUSE; mouse->bIsInitialised = true; m_pControllers[static_cast<int>(eControllerIndex::MOUSE)] = mouse; } CInputManager::~CInputManager() { for(unsigned int i = 0; i < static_cast<int>(eControllerIndex::MAX); i++) { if(m_pControllers[i]) { delete m_pControllers[i]; m_pControllers[i] = nullptr; } } } void CInputManager::Reset() { m_bMouseButtonPressed = false; m_bMouseButtonReleased = false; m_bKeyboardKeyPressed = false; m_bKeyboardKeyReleased = false; } //========================================================================= // Mouse Events //========================================================================= void CInputManager::HandleMouseMotionEvent(const SDL_Event* event) { if(event->type != SDL_MOUSEMOTION) { ERROR("Recived an event that was not a mouse motion event: " + std::to_string(event->type)); return; } static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)])->position((float)event->motion.x, (float)event->motion.y); } void CInputManager::HandleMouseButtonEvent(const SDL_Event* event) { if(event->type != SDL_MOUSEBUTTONDOWN && event->type != SDL_MOUSEBUTTONUP) { ERROR("Recived an event that was not a mouse button event: " + std::to_string(event->type)); return; } SMouseController* mouse = static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)]); mouse->clickPosition(event->button.x, event->button.y); eButtonEventType eEventType = eButtonEventType::UP; if(event->type == SDL_MOUSEBUTTONDOWN) { eEventType = eButtonEventType::DOWN; } eButtonState eState = eButtonState::RELEASED; if(event->button.state == SDL_PRESSED) { eState = eButtonState::PRESSED; m_bMouseButtonPressed = true; m_bMouseButtonReleased = false; } else { m_bMouseButtonPressed = false; m_bMouseButtonReleased = true; } bool bDoubleClicked = false; if(event->button.clicks == 2) { bDoubleClicked = true; } switch(event->button.button) { case SDL_BUTTON_LEFT: { SetMouseButton(eMouseButton::LEFT, eEventType, eState, bDoubleClicked, mouse); break; } case SDL_BUTTON_MIDDLE: { SetMouseButton(eMouseButton::MIDDLE, eEventType, eState, bDoubleClicked, mouse); break; } case SDL_BUTTON_RIGHT: { SetMouseButton(eMouseButton::RIGHT, eEventType, eState, bDoubleClicked, mouse); break; } case SDL_BUTTON_X1: { SetMouseButton(eMouseButton::X1, eEventType, eState, bDoubleClicked, mouse); break; } case SDL_BUTTON_X2: { SetMouseButton(eMouseButton::X2, eEventType, eState, bDoubleClicked, mouse); break; } default: // TODO: Unknown button, report? break; } } void CInputManager::SetMouseButton(eMouseButton button, eButtonEventType type, eButtonState state, bool bDoubleClick, SMouseController* mouse) { if(type == eButtonEventType::DOWN) { if(!mouse->buttons[button]) { mouse->buttons[button] = true; m_eMouseButtonPressed = button; } } else if(type == eButtonEventType::UP) { if(mouse->buttons[button]) { mouse->buttons[button] = false; m_eMouseButtonReleased = button; } } else { // TODO: Handle this somehow? } if(mouse->states[button] != state) { mouse->states[button] = state; } if(mouse->doubleClicks[button] != bDoubleClick) { mouse->doubleClicks[button] = bDoubleClick; } } void CInputManager::ClearMouseButtonPressed() { m_bMouseButtonPressed = false; } void CInputManager::ClearMouseButtonReleased() { m_bMouseButtonReleased = false; } SVector2<float> CInputManager::GetMousePosition() const { return static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)])->position; } SVector2<float> CInputManager::GetMouseClickPosition() const { return static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)])->clickPosition; } eMouseButton CInputManager::GetMouseButtonPressed() const { return m_eMouseButtonPressed; } eMouseButton CInputManager::GetMouseButtonReleased() const { return m_eMouseButtonReleased; } bool CInputManager::GetMouseButtonDown(eMouseButton button) const { return static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)])->buttons[button]; } bool CInputManager::GetMouseButtonUp(eMouseButton button) const { return !static_cast<SMouseController*>(m_pControllers[static_cast<int>(eControllerIndex::MOUSE)])->buttons[button]; } bool CInputManager::WasMouseButtonPressed() const { return m_bMouseButtonPressed; } bool CInputManager::WasMouseButtonReleased() const { return m_bMouseButtonReleased; } //========================================================================= // Keyboard Events //========================================================================= void CInputManager::HandleKeyboardEvent(const SDL_Event* event) { if(event->type != SDL_KEYDOWN && event->type != SDL_KEYUP) { ERROR("Recived an event that was not a keyboard key event: " + std::to_string(event->type)); return; } SKeyboardController* keyboard = static_cast<SKeyboardController*>(m_pControllers[static_cast<int>(eControllerIndex::KEYBOARD)]); eButtonEventType eEventType = eButtonEventType::UP; if(event->type == SDL_KEYDOWN) { eEventType = eButtonEventType::DOWN; } eButtonState eState = eButtonState::RELEASED; if(event->key.state == SDL_PRESSED) { eState = eButtonState::PRESSED; m_bKeyboardKeyPressed = true; m_bKeyboardKeyReleased = false; } else { m_bKeyboardKeyPressed = false; m_bKeyboardKeyReleased = true; } switch(event->key.keysym.sym) { case SDLK_ESCAPE: { SetKeyboardKey(EKeyboardKey::Escape, eEventType, eState, keyboard); break; } case SDLK_w: { SetKeyboardKey(EKeyboardKey::W, eEventType, eState, keyboard); break; } case SDLK_s: { SetKeyboardKey(EKeyboardKey::S, eEventType, eState, keyboard); break; } case SDLK_UP: { SetKeyboardKey(EKeyboardKey::Up, eEventType, eState, keyboard); break; } case SDLK_DOWN: { SetKeyboardKey(EKeyboardKey::Down, eEventType, eState, keyboard); break; } default: break; } } void CInputManager::SetKeyboardKey(EKeyboardKey key, eButtonEventType type, eButtonState state, SKeyboardController* keyboard) { if(type == eButtonEventType::DOWN) { if(!keyboard->keys[key]) { keyboard->keys[key] = true; m_eKeyboardKeyPressed = key; } } else if(type == eButtonEventType::UP) { if(keyboard->keys[key]) { keyboard->keys[key] = false; m_eKeyboardKeyReleased = key; } } if(keyboard->keyStates[key] != state) { keyboard->keyStates[key] = state; } } void CInputManager::ClearKeyboardKeyPressed() { m_bKeyboardKeyPressed = false; } void CInputManager::ClearKeyboardKeyReleased() { m_bKeyboardKeyReleased = false; } EKeyboardKey CInputManager::GetKeyboardKeyPressed() const { return m_eKeyboardKeyPressed; } EKeyboardKey CInputManager::GetKeyboardKeyReleased() const { return m_eKeyboardKeyReleased; } bool CInputManager::GetKeyboardKeyDown(EKeyboardKey key) const { return static_cast<SKeyboardController*>(m_pControllers[static_cast<int>(eControllerIndex::KEYBOARD)])->keys[key]; } bool CInputManager::GetKeyboardKeyUp(EKeyboardKey key) const { return !static_cast<SKeyboardController*>(m_pControllers[static_cast<int>(eControllerIndex::KEYBOARD)])->keys[key]; } bool CInputManager::WasKeyboardKeyPressed() const { return m_bKeyboardKeyPressed; } bool CInputManager::WasKeyboardKeyReleased() const { return m_bKeyboardKeyReleased; } } <file_sep>/Source/Graphics/UI/DropdownItem.cpp //============================================================================= // Date: 05 Jan 2018 // Creator: <NAME> //============================================================================= #include "DropdownItem.hpp" #include "../Renderer.hpp" #include "../../Managers/EventManager.hpp" #include "../../Input/InputManager.hpp" #include "../../Utils/Hash.hpp" #include "../../Engine.hpp" namespace Pong { CDropdownItem::CDropdownItem() : CDropdownItem("DefaultDropdownItem", "DefaultDropdownItemText") {} CDropdownItem::CDropdownItem(const std::string& name, const std::string& itemText) : CUIObject(-1, name), m_itemText(-1, name + "_Text", itemText, "DroidSans20"), m_pOnClickAction(nullptr), m_pOnApplyAction(nullptr), m_bEnabled(false), m_bHovered(false) { CUIObject::SetVisibility(false); m_colour(62, 67, 87, 255); m_itemText.SetColour(SVector4<uchar>(0, 0, 0, 0)); } void CDropdownItem::SetEnabled(bool bEnabled) { m_bEnabled = bEnabled; } std::string CDropdownItem::GetText() const { return m_itemText.GetText(); } void CDropdownItem::OnClick(Engine& engine) { if(m_pOnClickAction) { engine.GetEventManager()->AddAction(m_pOnClickAction); } } void CDropdownItem::OnHover(Engine& engine, bool bIsWithinBounds) { if(bIsWithinBounds) { m_bHovered = true; m_colour(88, 95, 123, 255); } else { if(m_bHovered) { m_bHovered = false; m_colour(62, 67, 87, 255); } } } void CDropdownItem::OnMouseButtonPressed(Engine& engine, bool bIsWithinBounds) { if(!bIsWithinBounds) { return; } eMouseButton button = engine.GetInputManager()->GetMouseButtonPressed(); switch(button) { case eMouseButton::LEFT: { m_bWasLeftClicked = true; engine.GetInputManager()->ClearMouseButtonPressed(); } break; default: break; } } void CDropdownItem::OnMouseButtonReleased(Engine& engine, bool bIsWithinBounds) { eMouseButton button = engine.GetInputManager()->GetMouseButtonReleased(); switch(button) { case eMouseButton::LEFT: { if(m_bWasLeftClicked) { m_bWasLeftClicked = false; } if(bIsWithinBounds) { OnClick(engine); //game->GetInputManager()->ClearMouseButtonReleased(); } } break; default: break; } } bool CDropdownItem::IsWithinBounds(const SVector2<float>& position) const { return (position.x >= (m_position.x + m_offset.x) && position.x <= (m_position.x + m_offset.x) + m_size.x && position.y >= (m_position.y + m_offset.y) && position.y <= (m_position.y + m_offset.y) + m_size.y); } IAction* CDropdownItem::GetAction(short hashName) { switch(hashName) { case StringToInt16("onclick"): { return m_pOnClickAction; } break; case StringToInt16("onapply"): { return m_pOnApplyAction; } break; default: { return nullptr; } break; } } void CDropdownItem::SetAction(short hashName, IAction* pAction) { if(!pAction) { return; } switch(hashName) { case StringToInt16("onclick"): { m_pOnClickAction = pAction; break; } case StringToInt16("onapply"): { m_pOnApplyAction = pAction; break; } default: break; } } void CDropdownItem::SetOffset(const SVector2<float>& offset) { m_offset = offset; // Calculate offset for centering text SVector2<float> textSize = m_itemText.GetSize(); float x = m_position.x + m_offset.x + (m_size.x / 2) - (textSize.x / 2); float y = m_position.y + m_offset.y + (m_size.y / 2) - (textSize.y / 2); SVector2<float> textOffset = {x, y}; m_itemText.SetOffset(textOffset); } void CDropdownItem::Update(Engine& engine) { if(!m_bVisible) { return; } SVector2<float> position = engine.GetInputManager()->GetMousePosition(); bool bIsWithinBounds = IsWithinBounds(position); OnHover(engine, bIsWithinBounds); if(engine.GetInputManager()->WasMouseButtonPressed()) { OnMouseButtonPressed(engine, bIsWithinBounds); } else if(engine.GetInputManager()->WasMouseButtonReleased()) { OnMouseButtonReleased(engine, bIsWithinBounds); } m_itemText.Update(engine); } void CDropdownItem::Render(Engine& engine) const { if(!m_bVisible) { return; } engine.GetRenderer()->Submit(this); m_itemText.Render(engine); } } <file_sep>/Source/GameObject.cpp //============================================================================= // Date: 10 Dec 2017 // Creator: <NAME> //============================================================================= #include "GameObject.hpp" #include "Graphics/Renderer.hpp" #include "Engine.hpp" namespace Pong { CGameObject::CGameObject(int id, const std::string& name, const SVector2<float>& position, const SVector2<float>& size) : CObject(id, name), m_position(position), m_size(size), m_offset(0.0f, 0.0f), m_colour(255, 255, 255, 0), m_eTextureID(TEXTUREID_NULL), m_bVisible(true) {} CGameObject::~CGameObject() { } void CGameObject::Update(Engine& engine) { } void CGameObject::Render(Engine& engine) const { if(m_bVisible) { engine.GetRenderer()->Submit(this); } } SVector2<float> CGameObject::GetPosition() const { return m_position; } SVector2<float> CGameObject::GetSize() const { return m_size; } SVector2<float> CGameObject::GetOffset() const { return m_offset; } SVector4<uchar> CGameObject::GetColour() const { return m_colour; } eTextureID CGameObject::GetTextureID() const { return m_eTextureID; } void CGameObject::SetPosition(const SVector2<float>& position) { m_position = position; } void CGameObject::SetSize(const SVector2<float>& size) { m_size = size; } void CGameObject::SetOffset(const SVector2<float>& offset) { m_offset = offset; } void CGameObject::SetColour(const SVector4<uchar>& colour) { m_colour = colour; } } <file_sep>/Source/Game/PauseMenu.hpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #pragma once #include "../Actions/MultiAction.hpp" #include "../Graphics/UI/Button.hpp" #include "../Graphics/UI/Canvas.hpp" #include "../Graphics/UI/Panel.hpp" #include "../Managers/Scene.hpp" namespace Pong { class PauseMenu : public CScene { CCanvas m_canvas; CPanel m_panel; CButton m_continueButton; CButton m_quitButton; CMultiAction m_quitButtonActions; public: PauseMenu(); }; } <file_sep>/Source/Actions/EnableAction.cpp //============================================================================= // Date: 10 Jan 2018 // Creator: <NAME> //============================================================================= #include "EnableAction.hpp" #include "../Managers/SceneManager.hpp" #include "../Engine.hpp" namespace Pong { CSetEnabledAction::CSetEnabledAction(const std::string& name, bool bEnabled) : m_name(name), m_bEnabled(bEnabled) {} bool CSetEnabledAction::Execute(Engine& engine) { CUIObject* object = engine.GetSceneManager()->GetUIObjectByName(m_name); if(!object) { return false; } object->SetEnabled(m_bEnabled); } } <file_sep>/Source/Utils/DebugOverlay.cpp //============================================================================= // Date: 13 Jan 2018 // Creator: <NAME> //============================================================================= #include "DebugOverlay.hpp" #include "../Graphics/UI/Canvas.hpp" #include "../Graphics/UI/Text.hpp" #include "../Input/InputManager.hpp" #include "../Managers/EventManager.hpp" #include "../Managers/Scene.hpp" #include "../Engine.hpp" namespace Pong { DebugOverlay::DebugOverlay() : CScene("DebugOverlay"), m_time(0.0f), m_frames(0.0f) { m_canvas = CCanvas(-1, "DebugCanvas"); Add(&m_canvas); m_fps = CText(-1, "Debug_FPS", "", "DroidSans12"); m_fps.SetPosition(SVector2<float>(10, 10)); m_canvas.Add(&m_fps); m_cursor = CText(2, "Debug_Cursor", "", "DroidSans12"); m_cursor.SetPosition(SVector2<float>(10, 25)); m_canvas.Add(&m_cursor); m_events = CText(3, "Debug_Events", "", "DroidSans12"); m_events.SetPosition(SVector2<float>(10, 40)); m_canvas.Add(&m_events); } void DebugOverlay::Update(Engine& engine) { SVector2<float> cursorPos = engine.GetInputManager()->GetMousePosition(); m_cursor.SetText("Mouse X: " + std::to_string((short)cursorPos.x) + ", Y: " + std::to_string((short)cursorPos.y)); m_events.SetText("Events Queued: " + std::to_string(engine.GetEventManager()->GetGameEventsInQueue())); m_time += engine.GetDeltaTime(); if(m_time > 1.0f) { m_fps.SetText("FPS: " + std::to_string(m_frames)); m_time = 0.0f; m_frames = 0; } m_frames++; CScene::Update(engine); } void DebugOverlay::Render(Engine& engine) const { CScene::Render(engine); } } <file_sep>/Source/Game/Player.cpp //============================================================================= // Date: 16 Jan 2018 // Creator: <NAME> //============================================================================= #include "Player.hpp" namespace Pong { Player::Player(int id, const std::string& name) : CGameObject(id, name, SVector2<float>(0.0f, 0.0f), SVector2<float>(0.0f, 0.0f)) { } } <file_sep>/Source/Input/Controller.hpp //============================================================================= // Date: 28 Dec 2017 // Creator: <NAME> //============================================================================= #pragma once namespace Pong { enum class eButtonState { PRESSED, RELEASED }; enum class eControllerType { KEYBOARD, MOUSE, GAMEPAD, JOYSTICK }; struct SController { eControllerType type; bool bIsInitialised; }; }
a3b9999c105a4cf51e25e23ddf2c5fd1cf5b0d18
[ "C", "CMake", "C++" ]
98
C++
fureloka/Pong
b1da90739139e7722576b6c72662db9b30c703c4
3b9d91d2ae092a73b8a7550d37c7f67197f5985a
refs/heads/master
<file_sep># Time Estimate for Capstone Project ## As of 2/17/2020 1. There are 9 weeks remaining 2. I have 4 hours per day or 28 hours per week available 3. Conservatively there are 250 hours available **List of items and estimated hours** 1. Homepage - 40 hrs 2. Search page - 12 hrs 3. Search result - 12 hrs 4. Pledge form - 12 hrs 5. Friends integ = 40 hrs 6. Database work - 24 hrs 7. Basket / cart - 30 hrs 8. History form - 12 hrs 9. Login form - 12 hrs 10.Trello etc. - 32 hrs 10. Contingency - 24 hrs *Subtotal = -250 hrs* **NO TIME TO WASTE**<file_sep># Peer Pledge, a Capstone project ## The target audience will be mentors, peers, instructors, recruiters, investors, and ultimately, people interested in growing global generosity (G-3). ### Peer Pledge is a single page web application that creates a "space" for people to find a charity that they would like to contribute to, invite friends to join them, and foster a community of everyday sharing and giving. Integration with social media tools allows everyone to share their generosity and grow giving by sharing. Imagine going to a space where you can see the generosity your peers have shown and join them in everyday giving. **With a successful launch and community adoption this application could transform "Giving Tuesday" from an annual event to a worldwide mindset!**<file_sep>import { Nav, Banner, Main, Footer } from "./components"; import * as state from "./store"; import Navigo from "navigo"; import { capitalize } from "lodash"; import axios from "axios"; import { auth, db } from "./firebase"; // ROUTER const router = new Navigo(window.location.origin); router .on({ ":page": (params) => render(state[capitalize(params.page)]), "/": () => render(state.Home), }) .resolve(); router.updatePageLinks(); // API to get weather axios .get( "https://api.openweathermap.org/data/2.5/weather?q=affton&APPID=<KEY>" ) .then((response) => { const farenheit = Math.round((response.data.main.temp - 273.15) * 1.8 + 32); state.Home.city = response.data.name; state.Home.temp = farenheit; state.Home.description = response.data.main; //Add temperature display let para = document.createElement("p"); let node = document.createTextNode(`Temp: ${farenheit}F`); para.appendChild(node); let element = document.getElementById("div2"); element.appendChild(para); }); //Function to render State export function render(st = state.Home) { document.querySelector(".root").innerHTML = ` ${Nav()} ${Banner()} ${Main(st)} ${Footer()} `; addNavEventListeners(); addLoginListener(st); addRegisterListener(st); router.updatePageLinks; addPledgeNowListener(st); addCancelButtonListener(st); addPledgeSubmitListener(st); addListenForSignOut(st); } //Render the Navigation links function addNavEventListeners() { document.querySelectorAll("nav a").forEach((navLink) => navLink.addEventListener("click", (event) => { event.preventDefault(); render(state[event.target.text]); router.updatePageLinks(); }) ); } // Add listener for Cancel buttons to return home function addCancelButtonListener(st) { if (st.view === "Home") { return; } else { document.getElementById("cancel").addEventListener("click", (event) => { event.preventDefault(); render(state.Home); }); } } //Listen for and process Registrations function addRegisterListener(st) { if (st.view === "Register") { document .getElementById("Register-form") .addEventListener("submit", (event) => { event.preventDefault(); addCancelButtonListener(st); let userData = Array.from(event.target.elements); // const inputs = userData.map((input) => input.value); let firstName = inputs[0]; let lastName = inputs[1]; let email = inputs[2]; let password = inputs[3]; // //create user in Firebase db auth.createUserWithEmailAndPassword(email, password).then(() => { addUserToStateAndDb(firstName, lastName, email, password); render(state.Home); //Add message to user on login let para = document.createElement("p"); let node = document.createTextNode( `Welcome ${firstName} ${lastName}!` ); para.appendChild(node); let element = document.getElementById("div1"); element.appendChild(para); }); }); } } //Add user to state only after login function addUserToState(first, last, email, status) { state.User.firstName = first; state.User.lastName = last; state.User.email = email; state.User.signedIn = status; } // Add user to State and Firebase function addUserToStateAndDb(first, last, email, password) { state.User.firstName = first; state.User.lastName = last; state.User.email = email; state.User.signedIn = status; db.collection("users").add({ firstname: first, lastname: last, email: email, password: <PASSWORD>, signedIn: true, }); } // Listen for and process Login events function addLoginListener(st) { if (st.view === "Login") { document .getElementById("Login-form") .addEventListener("submit", (event) => { event.preventDefault(); const userInfo = Array.from(event.target.elements); const inputs = userInfo.map((input) => input.value); let email = inputs[0]; let password = inputs[1]; auth.signInWithEmailAndPassword(email, password).then(() => { render(state.Home); addUserStatusToDb(email); }); }); } } //Function pull user info from db on Login function addUserStatusToDb(email) { db.collection("users") .get() .then((snapshot) => snapshot.docs.forEach((doc) => { if (email === doc.data().email) { let id = doc.id; db.collection("users").doc(id).update({ signedIn: true }); let email = doc.data().email; let first = doc.data().firstname; let last = doc.data().lastname; let status = true; //Add message to user on login let para = document.createElement("p"); let node = document.createTextNode(`Welcome ${first} ${last}!`); para.appendChild(node); let element = document.getElementById("div1"); element.appendChild(para); addUserToState(first, last, email, status); } }) ); } // Add listener for Pledge Now button function addPledgeNowListener(st) { if (st.view === "Home") { document.getElementById("pledge").addEventListener("click", (event) => { event.preventDefault(); render(state.Pledge); addPledgeSubmitListener(st); }); } } //Add a listener for Submit pledge function addPledgeSubmitListener(st) { if (st.view === "Pledge") { document .getElementById("Pledge-form") .addEventListener("submit", (event) => { event.preventDefault(); createPledge(); }); } } // Save Pledge form data on submit and call db to add function createPledge() { let pledgeData = Array.from(event.target.elements); const inputs = pledgeData.map((input) => input.value); let peer = inputs[0]; let charity = inputs[1]; let email = inputs[2]; let amount = inputs[3]; let date = Date(); addPledgeToDb(date, amount, charity, email, peer); } // Add pledge to db with a generated id. function addPledgeToDb(date, amount, charity, email, peer) { db.collection("pledges").add({ addedOn: date, amount: amount, charityName: charity, email: email, peerEmail: peer, }); addPledgeToState(date, peer, charity, email, amount); } //Add pledge to state and then db function addPledgeToState(date, peer, charity, email, amount) { state.Pledges.push({ addedOn: date, amount: amount, charityName: charity, email: email, peerEmail: peer, }); render(state.Home); //Display pledge message let para = document.createElement("p"); let node = document.createTextNode( `Thank you for the $ ${amount} pledge to ${charity}` ); para.appendChild(node); let element = document.getElementById("div1"); element.appendChild(para); } //Listen for logout function addListenForSignOut() { document.getElementById("Logout").addEventListener("click", (event) => { event.preventDefault(); let email = state.User.email; logoutUserInStateAndDb(email); }); } // if user is logged in, log out when clicked function logoutUserInStateAndDb(email) { event.preventDefault(); // log out functionality logOutUserInDb(email); render(state.Home); //Add message to user on logout let para = document.createElement("p"); let node = document.createTextNode(`Goodbye `); para.appendChild(node); let element = document.getElementById("div1"); element.appendChild(para); } //update user in database function logOutUserInDb(email) { db.collection("users") .get() .then((snapshot) => snapshot.docs.forEach((doc) => { if (email === doc.data().email) { let id = doc.id; db.collection("users").doc(id).update({ signedIn: false }); } }) ); } <file_sep>export default ["Register", "Login", "Logout", "Top 100"]; <file_sep>export default (links) => ` <nav> <ul id="hidden--mobile nav-links"> <a href="Register" class="nav" id="Register">Register</a> <a href="Login" class="nav" id="Login">Login</a> <a href="Logout" class="nav" id="Logout">Logout</a> </ul> </nav><!--nav--> `; <file_sep>export default { header: "Home", view: "Home", temp: "", description: "", }; <file_sep># This log describes the content envisioned for the Peer Pledge web page / application. ## User will see a main page featuring inspirational images, appeals to give, and recent pledges. Easily visible will be a charity lookup which doubles as a friend finder so that user can "peg" to a friends pledge. ### The app will pull named, legally formed charity content from an API to determine the payee. Using social networking app integration features, user will be able to connect to peers to encourage giving or to see what peer activity exists. **TBD a shopping cart / checkout and pay feature will be used to capture the pledge/donation.** --TBD a database will be used to commit transaction history and present to user upon demand.-- <file_sep># This file documents my Capstone project ## This project is a single page web application that creates a "space" for users to contribute to a charity, invite friends to join them, and foster a community of everyday sharing and giving. Future integration with social media tools envisioned. With a successful launch and community adoption this application could transform "Giving Tuesday" from an annual event to a worldwide mindset! ### The target audience will be mentors, peers, instructors, recruiters, investors, and ultimately, people interested in growing global generosity (G-3). #### In this repository you can find everything from the conceptual drawings to the finished product. ##### It's a work in process. **Github: https://github.com/davkem43/Capstone** **Firebase: https://console.firebase.google.com/u/0/project/david-s-project-f6d5c/overview** **Trello: https://trello.com/b/5vdBVpQd/capstone-david-kemp** **Netlify: https://focused-kare-e95b13.netlify.com/** <file_sep>export default () => ` <div class="banner" id="slogan"> <h1>Peer Pledge</h1> <h3>Pledge to a charity and challenge a friend!</h3> </div><!--banner--> `; <file_sep>export default { header: "Pledge", view: "Pledge", }; <file_sep>export default () => { return ` <div class="footer"> <ul class="social"> <i class="fab fa-facebook" title="Facebook/peerpledge"></i> <i class="fab fa-instagram" title="instagram/davekemp43"></i> <i class="fab fa-linkedin" title = "http://linkedin.com/in/kempdave"></i> <i class="fab fa-pinterest"></i> </ul> <footer>&copy Kemp2020</footer> <div id="div2"> <p id="p1"></p> </div> </div><!--#footer--> <div class="footer-image"> <img src = "https://github.com/davkem43/Capstone/blob/master/lib/volunteer.png?raw=true"> </div><!--footer-image--> `; };
dddd094d35cf665a0551da6af24c95d30f6aa8a1
[ "Markdown", "JavaScript" ]
11
Markdown
davkem43/Capstone
1d4c4e87c428d20d07d12933e401181ca3dadf57
006188399ea7612d51322c61d6ee3937068b7858
refs/heads/master
<file_sep>using System; using PlanShopEat.ViewModels; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace PlanShopEat.Views { public sealed partial class RecipesPage : Page { public RecipesViewModel ViewModel { get; } = new RecipesViewModel(); public RecipesPage() { InitializeComponent(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); await ViewModel.LoadDataAsync(); } } } <file_sep>using System; using PlanShopEat.Helpers; namespace PlanShopEat.ViewModels { public class MainViewModel : Observable { public MainViewModel() { } } } <file_sep>using System; using PlanShopEat.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace PlanShopEat.Views { public sealed partial class ShoppingListsPage : Page { public ShoppingListsViewModel ViewModel { get; } = new ShoppingListsViewModel(); public ShoppingListsPage() { InitializeComponent(); Loaded += ShoppingListsPage_Loaded; } private async void ShoppingListsPage_Loaded(object sender, RoutedEventArgs e) { await ViewModel.LoadDataAsync(MasterDetailsViewControl.ViewState); } } } <file_sep>using System; using PlanShopEat.ViewModels; using Windows.UI.Xaml.Controls; namespace PlanShopEat.Views { public sealed partial class MainPage : Page { public MainViewModel ViewModel { get; } = new MainViewModel(); public MainPage() { InitializeComponent(); } } }
c0824ef35e39925fd54c9450c9eb0dde651bc1a5
[ "C#" ]
4
C#
magnusnorvik/PlanShopEat
c8857c892c669f5681b098852ff25623e746564e
aa205725299ae2d25ffd05aca847ff46ba4344f3
refs/heads/master
<repo_name>Shulabh-968026/30DaysOfCodeHackerRank<file_sep>/Day 10: Binary Numbers #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input()) l=list() ones=0 m=0 while n!=0: if(n%2==0): l.insert(0,0) else: l.insert(0,1) n=n//2 for i in range(len(l)): if(l[i]==1): ones=ones+1 if(ones>=m): m=ones else: ones=0 print(m) <file_sep>/README.md # 30DaysOfCodeHackerRank This all 30 days code from HackerRank chanllange solve by me in Python except days 21 which in c++
19e731229b1c158cc1c5ae81306a407ba36efcc0
[ "Markdown", "Python" ]
2
Python
Shulabh-968026/30DaysOfCodeHackerRank
452b942f73164984ff741efb70670563d5344c83
7a259641f14b760e77dd8520fc8af5c71c56b894
refs/heads/master
<file_sep>import React from "react" import TodoItem from "./components/TodoItem"; import todosData from "./components/todosData" function App() { const todosComponents = todosData.map(item => <TodoItem key={item.id} todoItem={item}/>) return( <div className="list"> {todosComponents} </div> ) } export default App<file_sep>import React from "react" import Joke from "./components/Joke" import jokesData from "./components/jokesData" function App() { const jokesComponents = jokesData.map( joke => <Joke key={joke.id} data={joke} /> ) return ( <div> {jokesComponents} </div> ) } export default App<file_sep>import React from "react" function MyInfo() { return ( <div> <h1><NAME></h1> <p>I am developer and I would like to visit the following spots:</p> <ol> <li>Europe</li> <li>Australia</li> <li>Chile</li> </ol> </div> ) } export default MyInfo<file_sep>import React from "react" import ReactDom from "react-dom" ReactDom.render( <ul> <li>USA</li> <li>Canada</li> <li>Brazil</li> </ul>, document.getElementById("root") )<file_sep>import React from "react" import Joke from "./components/Joke" import jokesData from "./components/jokesData" function App() { return ( <div> <Joke data={ { punchLine: "It´s hard to explain puns to kleptomaniacs because they always take things literally" } } /> <Joke data={ { question: "Are we funny?", punchLine: "Well, we are the punch line" } } /> <Joke data={ { question: null, punchLine: "It´s hard to explain puns to kleptomaniacs because they always take things literally" } } /> <Joke data={ { question: "Are we funny?", punchLine: "Well, we are the punch line" } } /> <Joke data={ { question: "Are we funny?", punchLine: "Well, we are the punch line" } } /> </div> ) } export default App<file_sep>import React from "react" function App() { return ( <div> <input type="checkbox" name="task1" value="reactjs" /> <p> study rectjs </p> <input type="checkbox" name="task2" value="angularjs" /> <p> study angular </p> <input type="checkbox" name="task3" value="html5" /> <p> study html5 </p> </div> ) } export default App<file_sep>import React from "react" import ReactDOM from "react-dom" function App() { const date = new Date() return( <h1>It is currently about {date.getHours()%12}pm</h1> ) } ReactDOM.render(<App/>, document.getElementById("root"))
69a890e1b376f4d35e784dab65029306f51c0ca3
[ "JavaScript" ]
7
JavaScript
clebercmb/learn-react-app
617e090cc5c8bdc93e5d19274cac6c3c895237f5
98272d5bc5911f7ca771be21553d11b6aa824059
refs/heads/master
<file_sep>import React from 'react'; import './MenuBox.css'; import MenuItem from './MenuItem/MenuItem'; class MenuBox extends React.Component { constructor(props) { super(props); this.state = { name: this.props.name ? this.props.name : new String("Menu"), menuItems: this.props.menuItems ? this.props.menuItems : new Array({ menuItemName: 'example' }), }; } render() { return ( <div className="MenuBox"> <h1 className="MenuTitle">{this.state.name}</h1> {this.state.menuItems.map((menuItem, index) => ( <MenuItem key={index} name={menuItem.menuItemName} /> ))} </div> ); } } export default MenuBox;<file_sep>import React, { Component } from 'react'; import 'normalize.css'; import './App.css'; import MenuBox from './MenuBox/MenuBox'; class App extends Component { render() { let menuItems = new Array(); menuItems.push({ menuItemName: 'Attack' }); menuItems.push({ menuItemName: 'Magic' }); menuItems.push({ menuItemName: 'Items' }); menuItems.push({ menuItemName: '?' }); return ( <div className="App"> <MenuBox name="COMMAND" menuItems={menuItems} /> </div> ); } } export default App;
ee663316b5c8e877f32a1456ecd31b1a08fc339a
[ "JavaScript" ]
2
JavaScript
NoviceDream/Kingdom-Hearts-Command-Menu
8bebf51e0b90e747495eafacfd4849333fbb9d76
6bedd860944f23aae8e602f51d1182de57a6d31f
refs/heads/master
<file_sep>// Code your solution in this file. function lowerCaseDrivers(array) { return array.map(function(driver) { return driver.toLowerCase() }); } function nameToAttributes(array) { return array.map(function(driver) { let names = driver.split(' ') let oneName = names[0] let twoName = names[1] let obj = {firstName:oneName, lastName:twoName} return obj }); } function attributesToPhrase(array) { return array.map(function(driver) { return `${driver['name']} is from ${driver.hometown}` }) }
17c5ddc54d7e0ac5a75854de70c46eea7d7cc087
[ "JavaScript" ]
1
JavaScript
itisjustdiego/js-looping-and-iteration-map-lab-web-091817
4eb603dd79b99777f8160bccbc2c8c997aa092ad
3924594bafec8f04fb77fbb1d1e691144f1bf387
refs/heads/master
<repo_name>arizamoisesco/Medir-peso-en-marte-python<file_sep>/main.py print("*"*20) print("Bienvenido, ¿deseas calcular tu peso en Marte?") print("*"*20) respuesta = input("(1)Si / (2)No \n") if respuesta == "1": print("¿En que planeta desea estar?") print("a. Marte") print("b. L<NAME> la Tierra") planeta = input("cual escoge: ") def calcular_peso(gravedad_planeta): peso_user = int(input("Ingrese el peso en kilogramos: ")) gravedad_tierra = 9.85 peso_final = int((peso_user*gravedad_marte)/gravedad_tierra) print("Su peso es: ",peso_final," kg") if (planeta == "a"): gravedad_marte = 3.71 calcular_peso(gravedad_marte) if (planeta == "b"): peso_user = int(input("Ingrese el peso en kilogramos: ")) gravedad_tierra = 9.85 gravedad_luna = 1.62 peso_final = int((peso_user*gravedad_luna)/gravedad_tierra) print("Su peso es: ",peso_final," kg") else: print("¿Entonces para que me usas ?")
c549ad8e378d630e5b30909090c0cf86c2334fc8
[ "Python" ]
1
Python
arizamoisesco/Medir-peso-en-marte-python
cb65a4997ef7d707aa66c2dd42b9a26ab2f37248
8a73d5c8e6316aa25c5b8f4e9505e6daedb37db7
refs/heads/master
<repo_name>sundar156/Machine_Learning_using_R<file_sep>/ML_Session.R #Day1 var <- 10 var class(var) var1 <- T var1 class(var1) # Vector - homogeneous collection of scalar object v1 = 1:9 v1 v2 <- c(1,2,8,5,7,9) v2 class(v2) v2[2] v2[2:5] v2>=7 v2[v2>=7] # List – heterogeneous collection of data l1 <- list(a = 1,b = 6,c = 'r',d = T) class(l1) l1$d l1$a # Data Frame - Table in R v1 <- c('jack', 'tom', 'james', 'jill') v2 <- c(98,95,89,79) v3 <- c(90,85,69,98) v4 <- c(79,85,90,97) df <- data.frame(v1,v2,v3,v4) df View(df) colnames(df) <-c('Names', 'sci', 'eng', 'maths') View(df) df[3,3] df[4,2] df[2,] df[,3] df['eng'] df[3] df[-4,] install.packages("Flury") library(Flury) data() data("computers") View(computers) help("computers") ?vector example("vector") getwd() setwd('D:/Data Science/EML_R') getwd() dir() ad <- read.csv(file = "adult.csv", header = F ) View(ad) ?read.csv data() # Plotting View() # plot(x,y, col, xlab, ylab, pch) plot(computers$Units, computers$Minutes, col = 'red', xlab = 'Units', ylab = 'Minutes', main = 'Ploting with R', pch = 16) ?pch dir() salary <- read.csv("Salary_Data.csv") View(salary) plot(salary$YearsExperience, salary$Salary, col = 'red', xlab = 'YearsExperience', ylab = 'Salary', main = 'Ploting with R', pch = 16) SLR - one feature variable - pridictor linear Relation O/p variable - cont. numeric value # Simple linear Model #lm(dependent var ~ Independent var, data = dataset) model <- lm(Salary ~ YearsExperience, data= salary ) summary(model) abline(intercept, slope, col) abline(25792.2, 9450.0, col = 'blue') # predict # pred = b0 +b1X1 pred = 25792.2 + 9450.0*20 pred dir() br <- read.csv( "breakfast_data.csv",sep ='\t') View(br) plot(br) # mULTIPLE linear Model #lm(dependent var ~ Independent var+IV+IV, data = dataset) model <- lm(rating ~., data = br ) summary(model) # predict # pred = b0 +b1X1 +b2X2 +b3X3 +b4X4+ b5X5 # ML process # Historical Data br <- read.csv( "breakfast_data.csv",sep ='\t') View(br) plot(br) # Splitting of data - 80-20 sp <- sample(1:nrow(br), 0.8*nrow(br)) sp train_df <- br[sp,] test_df <- br[-sp,] # model # model <- lm(rating ~protein+fat+fiber+carbo+sugars, data = train_df ) model <- lm(rating ~., data = train_df ) summary(model) # Model validation # predict(model, test data) pred_values <- predict(model, test_df) pred_values test_df$rating # Error error <- test_df$rating - pred_values error <- (error*100)/test_df$rating error_mean <- mean(abs(error)) error_mean # Accuracy acc <-100- error_mean acc # Day 2 # Logistic Regression getwd() dir() chd <- read.csv("chd.csv") View(chd) # Historical data chd <- read.csv("chd.csv") View(chd) plot(chd) # Splitting the data into train and test data (80-20) #set.seed(12) sp <- sample(1:nrow(chd), 0.8*nrow(chd)) #1- 100, 80% = 80 sp train <- chd[sp,] test <- chd[-sp,] # model creation model <- glm(chd ~ age , data = train, family = 'binomial') summary(model) # Predict pred <- predict(model, test, type = 'response') # type = 'response'- as we want probability instead of y value pred # setting threshold 0.5 def <- rep(0,nrow(test)) def def[pred>0.5] <-1 def # validation cf <- table(test$chd, def) cf # accuracy acc <- ((cf[1]+cf[4])/nrow(test))*100 acc # Decision Tree install.packages('C50') # for model library(C50) install.packages('partykit') # for visualization of tree library(partykit) # Historical data data(iris) View(iris) # Splitting the data into train and test data (80-20) #set.seed(12) sp <- sample(1:nrow(iris), 0.8*nrow(iris)) #1- 150, 80% = 120 sp train <- iris[sp,] test <- iris[-sp,] # model # c5.0(Features, Target) model <- C5.0(train[,-5], train$Species) summary(model) plot(model, type = "simple") # Predict pred <- predict(model, test) pred # validation cf <- addmargins(table(test$Species, pred)) cf # accuracy acc <- ((cf[1]+cf[6]+cf[11])/cf[16])*100 acc # clustering new <- iris # Actual data plot(new[c("Petal.Length", "Petal.Width")], col = new$Species) # clustering the data kc <- kmeans(new[-5], 3) kc # Groups created by clustering plot(new[c("Petal.Length", "Petal.Width")], col = kc$cluster) # Visualizing the confusion matrix table(new$Species, kc$cluster)<file_sep>/ggplot_example.R install.packages("ggplot2") library(ggplot2) ?seq index <- seq(1,length(computers$Minutes)) print(index) ?ggplot ?aes ggplot() + geom_point(data=computers,aes(x = index, y = Minutes),size=2) + geom_hline(yintercept=mean(computers$Minutes)) + geom_segment(data=computers,aes(x=index,y=Minutes,xend=index,yend=mean(Minutes)),linetype="dotted",size=0.5) + ggtitle("Plot of computers$Minutes") + theme(plot.title = element_text(hjust = 0.5)) # ----------------- #Code to create the following scatter plot library(ggplot2) ggplot() + geom_point(data=computers,aes(x = Units, y = Minutes),size=2) + ggtitle("Plot of time taken to repair a computer Vs. No. of units being replaced") <file_sep>/Simple_Linear_Regression2.R #Model 0 library(Flury) data(computers) minutesmean <- mean(computers$Minutes) model0 <- data.frame(matrix(data=c(computers$Units,computers$Minutes, minutesmean*(0*computers$Minutes+1), (minutesmean-computers$Minutes)), ncol=4)) colnames(model0) <- c("Units replaced", "Observed time taken", "Expected value", "Expected - Observed value") print(model0) print("#Sum of errors for Model 0") SSE0= sum(minutesmean-computers$Minutes) print(SSE0) ## -End of Model 0 # - Model 1 Begining minutesmeanmodel1 <-(10+ (12*(computers$Units))) print(minutesmeanmodel1) model1 <- data.frame(matrix(data=c(computers$Units,computers$Minutes, minutesmeanmodel1*(0*computers$Minutes+1), (minutesmeanmodel1-computers$Minutes)),ncol=4)) colnames(model1) <- c("Units replaced", "Observed time taken", "Expected value", "Expected - Observed value") print(model1) SSE1 = sum((computers$Minutes-minutesmeanmodel1)^2) print(SSE1) ## -End of Model 1 # - Model 2 Begining minutesmeanmodel2 <-(6+ (18*(computers$Units))) print(minutesmeanmodel1) model2 <- data.frame(matrix(data=c(computers$Units,computers$Minutes, minutesmeanmodel2*(0*computers$Minutes+1), (minutesmeanmodel2-computers$Minutes)), ncol=4)) colnames(model2) <- c("Units replaced", "Observed time taken", "Expected value", "Expected - Observed value") print(model2) SSE2 = sum((computers$Minutes-minutesmeanmodel2)^2) print(SSE2) print(sqrt(SSE2)) #----- End Model 2 #-Best Fit Liner Regression Model library("Flury") data(computers) # Build the simple linear regression model using lm function ?lm simpleLRmodel <- lm(formula = Minutes ~ Units , data = computers) print(simpleLRmodel) #Calculating Sum of Squared of Errors #Regression coefficients b0 <- simpleLRmodel$coefficients[1] b1 <- simpleLRmodel$coefficients[2] print(simpleLRmodel$coefficients[2] ) SSE <- sum(((b0 + b1 * computers$Units) - computers$Minutes) ^ 2) print(SSE) # predict time for replacing 2 units using the lm model predicted_time <- predict(simpleLRmodel, newdata = data.frame(Units = 2)) print(predicted_time) #Plotting the best fit model library(ggplot2) ggplot() + geom_point(data = computers,aes(x = Units, y = Minutes),size = 2) + geom_abline(intercept = b0,slope = b1) + ggtitle("Best fit model") + theme(plot.title = element_text(hjust = 0.5)) #Summary of the model summary(simpleLRmodel) #Accessing R squared directly #r square is called coefficient of determination summary(simpleLRmodel)$r.squared <file_sep>/Linear_Regression_Example.R library(Flury) data() data("computers") View(computers) print("computers Dataset") ?sum mean_ = sum(computers$Minutes) / sum(computers$Units) print(sum(computers$Units)) print(computers,row.names = F) print(sum(computers$Minutes)/14) #--- # Create a vector as input. data <- c("East","West","East","North","North","East","West","West","West","East","North") print(data) print(is.factor(data)) # Apply the factor function. factor_data <- factor(data) print(factor_data) print(is.factor(factor_data)) #------------ ?c ?factor tst= c(1,2,4,6,8) mrk=c(45,60,78,90,80) subj = c ('Eng','Mat','Sci','Phy','che') ?factor mons= cut(mrk,breaks=c(0,50,80,100),labels=c('cat1','cat2','cat3'),right=FALSE) print(mons) table(mons) #Plot of Model 0, 1 and 2 models <- factor(c("Model 0", "Model 1", "Model 2","Model 1"),ordered = FALSE) print(models) levels(models)[1]="Model 0" ?`levels<-.factor` levels(models) slopes <- c(0,12,18) intercepts <- c(mean(computers$Minutes),10,6) Models <- data.frame(models, slopes, intercepts) library(ggplot2) ggplot() + geom_point(data = computers,aes(x = Units, y = Minutes),size = 2) + geom_abline(data = Models, aes(slope = slopes, intercept = intercepts, col = models),lwd = 1.2) + ggtitle("Speculated models") + theme(plot.title = element_text(hjust = 0.5)) #------------- plot(computers$Units,computers$Minutes,col='red',xlab=units,ylab='minutes', main='plotting in R',pch=16) abline(6,18,col='blue') abline(10,12,col='red') m1 <- lm(computers$Minutes~computers$Units,data=computers) print(m1) summary(m1) # optimised model is created abline(4.162,15.09,col='purple') b1 <- 4.162 b0 <- 15.09 SSE=sum(((b0+b1 * computers$Units)-computers$Minutes)^2) b0 <- 6 b1 <- 18 SSE=sum(((b0+b1 * computers$Units)-computers$Minutes)^2) SSE pred = b0 + b1*2 pred pred = b0 + b1*2 #pred = b0 + b1*2 + help(glm) chd = read.csv('chd.csv') ?family install.packages('C50') install.packages('partykit') data('iris') model <- C50.0(train_df[-5],train_df$Species) <file_sep>/Multiple_Linear_Regression_Exercise.R data(faithful) head(faithful) library(ggplot2) ggplot(data=faithful,aes()) ggplot() + geom_point(data = faithful,aes(x = eruptions, y = waiting),size = 2) + ggtitle("Plot of faithful") + theme(plot.title = element_text(hjust = 0.5)) ?geom_point() #-------- set.seed(123) training_data_size <- floor(0.75*nrow(faithful)) ?sample() faithful_training_index <- sample(1:nrow(faithful),training_data_size) #Training data faithful_train <- faithful[faithful_training_index,] #Testing data faithful_test <- faithful[-faithful_training_index,] faithful_model <- lm(waiting ~ eruptions,data=faithful) pred <- predict(faithful_model,faithful_test) percentage_error <- ((pred - faithful_test$waiting)*100 )/faithful_test$waiting print("Error") print(mean(abs(percentage_error))) print("Prediction Accuracy") print(100-mean(abs(percentage_error))) b0 <- faithful_model$coefficients[1] b1 <- faithful_model$coefficients[2] ggplot() + geom_point(data=faithful_test,aes(x=eruptions,y=waiting),size=2) + geom_abline(intercept = b0,slope=b1,col='red',lwd=2)+ggtitle("Plot of faithful") + theme(plot.title = element_text(hjust=0.5)) summary(faithful_model)$r.squared #data(mtcars) # Use mtcars dataset in R to calculate and compare the sum of square errors of linear regression # models plotted for "mpg" vs. "hp" and "mpg" vs. "qsec". library(ggplot2) ggplot(mtcars, aes(hp,mpg)) + geom_point() + geom_smooth(method = "lm", se = FALSE) + ylab("Miles per Gallon") + xlab("No. of Horsepower") + ggtitle("Impact of Number of Horsepower on MPG") m1 <- lm(mtcars$mpg~mtcars$hp,data=mtcars) summary(m1) abline(30.09,-0.06,col='purple') b1 <- 30.09 b0 <- 1.63 SSE=sum(((b0+b1 * computers$Units)-computers$Minutes)^2) print(SSE) #---- Age<- c(19,35,26,27,19,27) salary <- c(19000,20000,43000,57000,76000,58000) Purchase <- c(0,0,0,0,0,0) data_set=data.frame(Age,salary,Purchase) print(1:(nrow(data_set))) #print(data.frame(Age,salary,Purchase)) ?c() library(ggplot2) ggplot(data=data_set,aes(x=Age,y=Purchase))+ geom_point() + ggtitle("Scatterplot - Age vs Purchase") + theme(plot.title = element_text(hadjust=0.5)) <file_sep>/Simple_Linear_Regression3.R print(dir()) DeathRate <- read.csv("/Users/home/Desktop/UpX/git/Machine_Learning_using_R/DataSet_prob2.csv",header=TRUE,strip.white = TRUE,skipNul = TRUE,skip=1) print(DeathRate) #read.table("/Users/home/Desktop/UpX/git/Machine_Learning_using_R/DataSet_prob2.csv",header=TRUE,strip.white = TRUE,skipNul = TRUE) model1 <- data.frame(DeathRate) ?lm print(model1[4]) SimpleLRmodel2 = lm(formula = model1$Per.capita.income..in.Euros. ~ model1$Death.Rate.per.1000.residents,data = model1) print(SimpleLRmodel2) summary(SimpleLRmodel2) # version install.packages("FRB") library("FRB") data(delivery) head(delivery) <file_sep>/Decision_Tree_Example.R #Decision Tree install.packages("C50") data("iris") # Step 1: Split the dataset into training and testing part set.seed(1436) training_index <- sample(1:150, 120) training_data <- iris[training_index,] testing_data <- iris[-training_index,] # Sample of training dataset head(training_data) # Step 2: Building the decision tree model library(C50) model <- C5.0(training_data[,-5], training_data$Species) print(model) # Step 3: Calculate the Accuracy of the model prediction <- predict(object = model, newdata = testing_data) actual_class <- testing_data$Species #confusion matrix addmargins(table(actual_class,prediction)) plot(model,type="simple") version
62fe0472acb001604a3f415d54d8462b270b07ea
[ "R" ]
7
R
sundar156/Machine_Learning_using_R
f5e62c7eeaa6ae502ce80b8fab5898b545223f21
06089895a9a13dbbe6f5cab28f682c8ffe0d528b
refs/heads/master
<file_sep>package request import "errors" type Method int const ( GET Method = 1 + iota POST UPDATE DELETE OPTIONS ) type RequestReader interface { GetMethod() Method GetResource() string GetBody() interface{} } type RequestParams struct { Method Method `json:"method"` Resource string `json:"resourse"` Body interface{} `json:"body"` } type Request struct { method Method resource string body interface{} isInitialized bool } func (request *Request) Init(params RequestParams) error { if request.isInitialized { return errors.New("Request is initialized") } request.body = params.Body request.method = params.Method request.resource = params.Resource return nil } func (request Request) GetMethod() Method { return request.method } func (request Request) GetResource() string { return request.resource } func (request Request) GetBody() interface {} { return request.body }<file_sep>package service import ( "go-serv/core/request" "go-serv/core/response" ) type Endpoint func(request request.RequestReader, response response.ResponseWriter, context request.RequestContextReader)<file_sep>package main import ( "go-serv/core/request" "go-serv/core/response" "log" ) func SumEndpoint(req request.RequestReader, resp response.ResponseWriter, context request.RequestContextReader) { body := req.GetBody().(map[string]int) resp.Write(&response.Response{ Body: map[string] int { "sum": Sum(body["a"], body["b"]), }, Status: 200, }) } func Sum(a int, b int) int { return a + b } type EchoWriter struct {} func (w EchoWriter) Write(resp *response.Response) { log.Println(resp.Body) } func main () { req := request.Request{} req.Init(request.RequestParams{ Body: map[string] int { "a": 2, "b": 4, }, Resource: "/test", Method: request.GET, }) context := request.RequestContext{} context.Init(request.RequestContextParams{ ContentType: "application/json", AuthorizationString: "", RequesterId: "asd", RequestId: "asdd", Params: map[string] interface {} { "some": "other", }, }) writer := EchoWriter{} SumEndpoint(&req, &writer, &context) } <file_sep>package request import ( "errors" ) type RequestContextReader interface { GetContentType() string GetAuthorizationString() string GetRequesterId() string GetRequestId() string GetParams() map [string] interface{} } type RequestContextParams struct { ContentType string `json:"contentType"` AuthorizationString string `json:"authorization"` RequesterId string `json:"requsterId"` RequestId string `json:"requestId"` Params map [string] interface{} } type RequestContext struct { contentType string authorizationString string requesterId string requestId string isInitialized bool params map [string] interface{} } func (context *RequestContext) Init(params RequestContextParams) error { if !context.isInitialized { return errors.New("Request context is initialized") } context.contentType = params.ContentType context.authorizationString = params.AuthorizationString context.requesterId = params.RequesterId context.requestId = params.RequestId context.params = params.Params context.isInitialized = true return nil } func (context RequestContext) GetContentType() string { return context.contentType } func (context RequestContext) GetAuthorizationString() string { return context.authorizationString } func (context RequestContext) GetRequesterId() string { return context.requesterId } func (context RequestContext) GetRequestId() string { return context.requestId } func (context RequestContext) GetParams() map [string] interface{} { return context.params }<file_sep>package response type Response struct { Body interface{} `json:"body"` Status int `json:"status"` } type ResponseContext map[string] interface{} type ResponseWriter interface { Write(response *Response) } type ResponseContextWriter interface { Write(response *Response, context *ResponseContext) }
4cfbbecb0ae41ee48e64e150e683b010b02eb657
[ "Go" ]
5
Go
oleksandr-klimenko/go-serv
f443432ef3fca5131e2fdbf7822337e0f8d4d71c
ec93b67a7ed13d580f997de75d17d820ff506e1f
refs/heads/master
<repo_name>SubhanshuMG/GeolocationSMG.github.io<file_sep>/README.md # Geolocation Helps in finding your current location using device GPS. <file_sep>/js/background-timer.js var INTERVAL = 1000; //ms var timer = setInterval(function(){ var date = new Date(); postMessage(date.getTime()); },INTERVAL); onmessage = function(e) { if(e.data === "stop"){ clearInterval(timer); close(); } };
cbdde89cde8dc868dee8cfe82f7d2f8d3f315e5a
[ "Markdown", "JavaScript" ]
2
Markdown
SubhanshuMG/GeolocationSMG.github.io
ca5a1460d33b01f9e05756985f2d4612f93aaf0a
614edf2ed3f51273af8227caad2e277c27e8a31a
refs/heads/master
<file_sep>function TokenHeader(headerData) { var headerjson = ' + headerData + ', headerobj = JSON.parse(headerjson); encodedHeader = btoa(unescape(encodeURIComponent(headerjson))); encodedHeaderString = decodeURIComponent(escape(window.atob(encodedHeader))); return encodedHeaderString; } function TokenPayload(payloadData) { var payloadjson = ' + payloadAData + ', payloadobj = JSON.parse(payloadjson); encodedPayload = btoa(unescape(encodeURIComponent(payloadjson))); encodedPayloadString = decodeURIComponent(escape(window.atob(encodedPayload))); return encodedPayloadString; } function SignToken(headerData, payloadData, secretKey) { var headerjson = ' + headerData + ', headerobj = JSON.parse(headerjson); encodedHeader = btoa(unescape(encodeURIComponent(headerjson))); var payloadjson = ' + payloadAData + ', payloadobj = JSON.parse(payloadjson); encodedPayload = btoa(unescape(encodeURIComponent(payloadjson))); var unsignedToken = encodedHeader + "." + encodedPayload; // Use HMAC SHA256 to sign the unsigned token using the secret key var tokenSignature = CryptoJS.HmacSHA256(unsignedToken, secretKey); var encodedTokenSignature = CryptoJS.enc.Base64.stringify(tokenSignature); return encodedTokenSignature; } function GenerateToken(headerData, payloadData, secretKey) { var tokenHeader = TokenHeader(headerData); var tokenPayload = TokenPayload(payloadData); var tokenSignature = SignToken(tokenHeader, tokenPayload, secretKey); fullToken = tokenHeader + "." + tokenPayload + "." + tokenSignature; return fullToken; } <file_sep># JSON Web Token Generator ### Dependencies * jquery-3.3.1.min.js * jquery.base64.min.js * crypto-js.min.js * hmac-sha256.min.js * enc-base64.min.js ### TokenHeader(headerData) Encodes a token header. ### TokenPayload(payloadData) Encodes a token payload. ### SignToken(headerData, payloadData, secretKey) Returns a HMAC SHA256 signature for associated header and payload. ### GenerateToken(headerData, payloadData, secretKey) This function returns a full JSON Web Token after using the HMAC SHA256 algorithm to generate a signature for an accepted token header and payload. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JWT_Generator { public class TokenHeader { public string alg { get; set; } public string typ { get; set; } } public class TokenPayload { public string sub { get; set; } public string name { get; set; } public string admin { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; namespace JWT_Generator { class GenerateTokenSignature { private static string GetEncodedSignature(string myKey, string encodedHeaderString, string encodedPayloadString) { string message = encodedHeaderString + "." + encodedPayloadString; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(myKey); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); string hashAsString = BitConverter.ToString(hashmessage); // Convert the hash signature to Base64 string byte[] signatureStringAsBytes = Encoding.ASCII.GetBytes(hashAsString); string encodedSignature = Convert.ToBase64String(signatureStringAsBytes); return encodedSignature; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Security.Cryptography; namespace JWT_Generator { class jwt_generator { public string GenerateToken(string header, string payload, string secretKey) { string encodedHeaderString = ConvertHeaderToJson(header); string encodedPayloadString = ConvertPayloadToJson(payload); string encodedSignature = GetEncodedSignature(secretKey, encodedHeaderString, encodedPayloadString); string generatedToken = encodedHeaderString + "." + encodedPayloadString + "." + encodedSignature; return generatedToken; } private static string ConvertHeaderToJson(string headerString) { byte[] headerStringAsBytes = Encoding.ASCII.GetBytes(headerString); string encodedHeaderString = Convert.ToBase64String(headerStringAsBytes); return encodedHeaderString; } private static string ConvertPayloadToJson(string payloadString) { // Convert the token payload to the actual token byte[] payloadStringAsBytes = Encoding.ASCII.GetBytes(payloadString); string encodedPayloadString = Convert.ToBase64String(payloadStringAsBytes); return encodedPayloadString; } private static string GetEncodedSignature(string myKey, string encodedHeaderString, string encodedPayloadString) { string message = encodedHeaderString + "." + encodedPayloadString; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(myKey); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); string hashAsString = BitConverter.ToString(hashmessage); // Convert the hash signature to Base64 string byte[] signatureStringAsBytes = Encoding.ASCII.GetBytes(hashAsString); string encodedSignature = Convert.ToBase64String(signatureStringAsBytes); return encodedSignature; } } } <file_sep># JSON-Web-Token-Generator A .NET application and resources for JSON Web Token authentication. ## Dependencies <code> using Newtonsoft.Json; using System.Security.Cryptography; </code> ## Token Header TokenHeader tokenHeader = new TokenHeader(); tokenHeader.alg = "HS256"; tokenHeader.typ = "JWT"; Converting header to JSON: string headerString = JsonConvert.SerializeObject(tokenHeader); byte[] headerStringAsBytes = Encoding.ASCII.GetBytes(headerString); string encodedHeaderString = Convert.ToBase64String(headerStringAsBytes); return encodedHeaderString; ## Token Payload TokenPayload tokenPayload = new TokenPayload(); tokenPayload.sub = txtTokenSubject.Text; tokenPayload.name = txtName.Text; tokenPayload.admin = cmbIsAdmin.Text; Converting payload to Base64: string payloadString = JsonConvert.SerializeObject(tokenPayload); // Convert the token payload to the actual token byte[] payloadStringAsBytes = Encoding.ASCII.GetBytes(payloadString); string encodedPayloadString = Convert.ToBase64String(payloadStringAsBytes); return encodedPayloadString; ## Converting to JSON string headerString = JsonConvert.SerializeObject(tokenHeader); string payloadString = JsonConvert.SerializeObject(tokenPayload); ## Token Signature string message = encodedHeaderString + "." + encodedPayloadString; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(myKey); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); string hashAsString = BitConverter.ToString(hashmessage); // Convert the hash signature to Base64 string byte[] signatureStringAsBytes = Encoding.ASCII.GetBytes(hashAsString); string encodedSignature = Convert.ToBase64String(signatureStringAsBytes); return encodedSignature; <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Security.Cryptography; namespace JWT_Generator { class jwt_generator { public string GenerateTokenHeader(string headerData) { TokenHeader tokenHeader = new TokenHeader(); tokenHeader.alg = "HS256"; tokenHeader.typ = "JWT"; string headerString = JsonConvert.SerializeObject(tokenHeader); string encodedHeaderString = ConvertHeaderToJson(headerString); return encodedHeaderString; } private static string ConvertHeaderToJson(string headerString) { byte[] headerStringAsBytes = Encoding.ASCII.GetBytes(headerString); string encodedHeaderString = Convert.ToBase64String(headerStringAsBytes); return encodedHeaderString; } public string GenerateTokenPayload(string subject, string name, string admin) { TokenPayload tokenPayload = new TokenPayload(); tokenPayload.sub = subject; tokenPayload.name = name; tokenPayload.admin = admin; string payloadString = JsonConvert.SerializeObject(tokenPayload); string encodedPayloadString = ConvertPayloadToJson(payloadString); return encodedPayloadString; } private static string ConvertPayloadToJson(string payloadString) { // Convert the token payload to the actual token byte[] payloadStringAsBytes = Encoding.ASCII.GetBytes(payloadString); string encodedPayloadString = Convert.ToBase64String(payloadStringAsBytes); return encodedPayloadString; } public string SignToken(string headerData, string subject, string name, string admin, string secretKey) { string encodedHeaderString = GenerateTokenHeader(headerData); string encodedPayloadString = GenerateTokenPayload(subject, name, admin); string message = encodedHeaderString + "." + encodedPayloadString; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(secretKey); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); string hashAsString = BitConverter.ToString(hashmessage); // Convert the hash signature to Base64 string byte[] signatureStringAsBytes = Encoding.ASCII.GetBytes(hashAsString); string encodedSignature = Convert.ToBase64String(signatureStringAsBytes); return encodedSignature; } public string GenerateToken(string headerData, string subject, string name, string admin, string secretKey) { string encodedHeaderString = GenerateTokenHeader(headerData); string encodedPayloadString = GenerateTokenPayload(subject, name, admin); string encodedSignature = SignToken(headerData, subject, name, admin, secretKey); string fullToken = encodedHeaderString + "." + encodedPayloadString + "." + encodedSignature; return fullToken; } } } <file_sep>using System; using System.Text; using System.Windows.Forms; using Newtonsoft.Json; using System.Security.Cryptography; namespace JWT_Generator { public partial class frmTokenGenerator : Form { public frmTokenGenerator() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string myKey = txtKey.Text; string tokenHeader = txtInputHeader.Text; string tokenPayload = txtInputPayload.Text; // Convert the token header to the actual token string encodedHeaderString = ConvertHeaderToJson(tokenHeader); string encodedPayloadString = ConvertPayloadToJson(tokenPayload); string encodedSignature = GetEncodedSignature(myKey, encodedHeaderString, encodedPayloadString); DisplayGeneratedToken(tokenHeader, tokenPayload, encodedHeaderString, encodedPayloadString, encodedSignature); } private static string ConvertHeaderToJson(string headerString) { byte[] headerStringAsBytes = Encoding.ASCII.GetBytes(headerString); string encodedHeaderString = Convert.ToBase64String(headerStringAsBytes); return encodedHeaderString; } private static string ConvertPayloadToJson(string payloadString) { // Convert the token payload to the actual token byte[] payloadStringAsBytes = Encoding.ASCII.GetBytes(payloadString); string encodedPayloadString = Convert.ToBase64String(payloadStringAsBytes); return encodedPayloadString; } private void DisplayGeneratedToken(string headerString, string payloadString, string encodedHeaderString, string encodedPayloadString, string encodedSignature) { txtJsonData.Text = headerString + payloadString; txtEncodedToken.Text = encodedHeaderString + "." + encodedPayloadString + "." + encodedSignature; } private static string GetEncodedSignature(string myKey, string encodedHeaderString, string encodedPayloadString) { string message = encodedHeaderString + "." + encodedPayloadString; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(myKey); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); string hashAsString = BitConverter.ToString(hashmessage); // Convert the hash signature to Base64 string byte[] signatureStringAsBytes = Encoding.ASCII.GetBytes(hashAsString); string encodedSignature = Convert.ToBase64String(signatureStringAsBytes); return encodedSignature; } private void textBox4_TextChanged(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void frmTokenGenerator_Load(object sender, EventArgs e) { } } }
9ec48154f858151ac21968f93caeddf02f38399f
[ "JavaScript", "C#", "Markdown" ]
8
JavaScript
xerocrypt/JSON-Web-Token-Generator
e45b096a9ca78ba9032a0ca6f2de83a03a71f8db
06dd0d88adb6b4e2d845f84cdbfc4e86e126c522
refs/heads/master
<repo_name>ZTylerDurden/Canals-backend<file_sep>/routes/product-reviews.js const express = require('express'); const mongoose= require('mongoose'); const Canal = require('../models/canal-model'); const Review = require('../models/review'); const User = require('../models/user-model'); const reviewRoutes = express.Router(); // Route to Handle Review Form Submission reviewRoutes.post('/api/canals/:id/reviews', (req, res, next) =>{ // Load the Workout from the Database // let id = req.params.id; // console.log(id) if (!req.user) { res.status(401).json({ message: "Log in to update the canal." }); return; } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { res.status(400).json({ message: "Specified id is not valid" }); return; } console.log("req.params.id: ", req.params.id) Canal.findById(req.params.id, (err, canal) => { if(err){ res.status(500).json({message: "Some weird error from DB."}); return; } // console.log("req.user._id", req.user._id) // console.log("canal is:", canal.owner) // if(req.user._id === canal.owner){ // res.status(400).json({ message: "You can't post review on your own canal sir!" }); // return; // } // Create the Schema Object to Save the Review const newReview = new Review ({ content: req.body.content, stars: req.body.stars, author: req.user.username }); // Add Review to Workout Reviews Array canal.reviews.push(newReview); // Save the workout to the Database canal.save((err) =>{ if (err) {return next(err)} res.status(200).json(canal); }); }); }); // get the reviews // reviewRoutes.get('/api/canals/:id/allreviews', (req, res, next) => { // if (!req.user) { // res.status(401).json({ message: "Log in to update the canal." }); // return; // } // if (!mongoose.Types.ObjectId.isValid(req.params.id)) { // res.status(400).json({ message: "Specified id is not valid" }); // return; // } // Canal.findById(req.params.id, (err, foundCanal) => { // if(err){ // res.status(500).json({message: "Some weird error from DB."}); // return; // } // }) // }) module.exports = reviewRoutes;<file_sep>/routes/canal-routes.js const mongoose = require("mongoose"); const express = require("express"); const multer = require('multer'); const canalRoutes = express.Router(); const Canal = require('../models/canal-model'); // multer for photo, this is some module to use up to 5 photos, extra feature const myUploader = multer({ dest: __dirname + "/../public/uploads/" }); // create new phone, can also use POSTMAN to create a new phone object canalRoutes.post('/api/canals', myUploader.single('canalImage'), (req, res, next) => { if(!req.user){ res.status(401).json({message: "Log in to create canal."}); return; } const newCanal = new Canal({ canalName: req.body.canalName, lat: req.body.lat, lng: req.body.lng, description: req.body.description, fishTypes: req.body.fishTypes, image: req.body.image, observations: req.body.observations, owner: req.user.username }); if(req.file){ newCanal.image = '/uploads/' + req.file.filename; } newCanal.save((err) => { if(err){ res.status(500).json({message: "Some weird error from DB."}); return; } // validation errors if (err && newCanal.errors){ res.status(400).json({ canalNameError: newCanal.errors.canalName, }); return; } // Same as the previous example where POSTMAN won't show the user PW with this activated req.user.encryptedPassword = <PASSWORD>; newCanal.user = req.user; res.status(200).json(newCanal); }); }); // list the phones canalRoutes.get('/api/canals', (req, res, next) => { if (!req.user) { res.status(401).json({ message: "Log in to see canals." }); return; } Canal.find() // retrieve all the info of the owners (needs "ref" in model) // don't retrieve "encryptedPassword" though .populate('user', { encryptedPassword: 0 }) .exec((err, allTheCanals) => { if (err) { res.status(500).json({ message: "Canals find went bad." }); return; } res.status(200).json(allTheCanals); }); }); // list single phone canalRoutes.get("/api/canals/:id", (req, res, next) => { if (!req.user) { res.status(401).json({ message: "Log in to see THE canal." }); return; } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { res.status(400).json({ message: "Specified id is not valid" }); return; } Canal.findById(req.params.id, (err, theCanal) => { if (err) { // res.json(err); res.status(500).json({ message: "Canals find went bad." }); return; } res.status(200).json(theCanal); }); }); // update the phone, USING PUT IN THIS CASE canalRoutes.put('/api/canals/:id', (req, res, next) => { if (!req.user) { res.status(401).json({ message: "Log in to update the canal." }); return; } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { res.status(400).json({ message: "Specified id is not valid" }); return; } console.log("===================") const updates = { canalName: req.body.canalName, lat: req.body.lat, lng: req.body.lng, description: req.body.description, fishTypes: req.body.fishTypes, observations: req.body.observations }; console.log("image is:", req.body.image) if (req.body.image){ updates.image = req.body.image; } Canal.findByIdAndUpdate(req.params.id, updates, err => { if (err) { res.json(err); return; } res.json({ message: "Canal updated successfully." }); }); }); // delete phone canalRoutes.delete("/api/canals/:id", (req, res, next) => { if (!req.user) { res.status(401).json({ message: "Log in to delete the canal." }); return; } if (!mongoose.Types.ObjectId.isValid(req.params.id)) { res.status(400).json({ message: "Specified id is not valid." }); return; } Canal.remove({ _id: req.params.id }, err => { if (err) { res.json(err); return; } res.json({ message: "Canal has been removed." }); }); }); module.exports = canalRoutes; <file_sep>/models/canal-model.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; var integerValidator = require('mongoose-integer'); const Review = require('../models/review'); // create geolocation Schema const GeoSchema = new Schema({ type: { type: String, default: "Point" }, coordinates: { type: [Number], index: "2dsphere" } }); const CanalSchema = new Schema({ canalName: { type: String }, lat: { type: Number, integer: true }, lng: { type: Number, integer: true }, description: { type: String, }, fishTypes: { type: Number, integer: true }, image: { type: String }, owner: { type: String // type: Schema.Types.ObjectId, // required: true, // ref: 'User' }, reviews: [Review.schema], observations: [String], // add in maps location geometry: GeoSchema // add in images to Schema }, { timestamps: true } ); const Canal =mongoose.model('Canal', CanalSchema); module.exports = Canal;
b39534406e0b26f2b2a7022cbed42b2ee782a9e7
[ "JavaScript" ]
3
JavaScript
ZTylerDurden/Canals-backend
89c06195af83769192a28a52182ed02421e6ca56
1e07ef6654eb8c7eae573d3c982dd49c5617f434
refs/heads/master
<repo_name>chingyuany/Caesar-Cipher-algorithm<file_sep>/TestCaesarCipherTwo.java /** * Write a description of TestCaesarCipherTwo here. * * @author (your name) * @version (a version number or a date) */ import edu.duke.*; public class TestCaesarCipherTwo { public int[] countLetters(String message) { String alph = "abcdefghijklmnopqrstuvwxyz"; int [] counts = new int[26]; for(int k=0; k< message.length();k++) { char ch = Character.toLowerCase(message.charAt(k)); int dex = alph.indexOf(ch); if (dex !=-1) { counts[dex]+=1; } } return counts; } public int maxIndex(int [] vals) { int maxDex =0; for(int k=0; k<vals.length;k++) { if (vals[k] >vals[maxDex]) {maxDex = k;} } return maxDex; } public String halfOfString(String message, int start) { String halfstring = ""; for (int i = 0; i < message.length(); i++) { if (start == 0 && i % 2 == 0) { halfstring += message.charAt(i); } else if (start == 1 && i%2 !=0) { halfstring += message.charAt(i); } } return halfstring; } public int getKey(String s) { int[] freqs = countLetters(s); int maxDex = maxIndex(freqs); return maxDex; } public String breakCaesarCipher(String input) { String evenstring = halfOfString(input,0); String oddstring = halfOfString(input,1); int evenkey = getKey(evenstring); int oddkey = getKey(oddstring); int devenkey = evenkey - 4; if (evenkey <4) { devenkey = 26 - (4-evenkey); } int doddkey = oddkey - 4; if (oddkey <4) { doddkey = 26 - (4-oddkey); } System.out.println(devenkey+"\t"+doddkey); CaesarCipherTwo cc = new CaesarCipherTwo(devenkey,doddkey); String decrypted = cc.decrypt(input); return decrypted; } public void simpleTests() { FileResource fr = new FileResource(); String s = fr.asString(); //String s = "Aal uttx hm aal Qtct Fhljha pl Wbdl. Pvxvxlx!"; CaesarCipherTwo cc = new CaesarCipherTwo(14,24); String encrypted = cc.encrypt(s); //System.out.println("encrypted \n" +encrypted); String decrypted = cc.decrypt(s); //System.out.println("decrypted \n" +decrypted); String breaking = breakCaesarCipher(s); System.out.println("breaking \n" +breaking); } } <file_sep>/wordPlay.java /** * Write a description of wordPlay here. * * @author (your name) * @version (a version number or a date) */ import edu.duke.*; import java.io.*; import org.apache.commons.csv.*; public class wordPlay { public boolean isVowel(char ch) { String vowel = "AEIOU"; char uch = Character.toUpperCase(ch); for(int i = 0; i < 5 ; i++) { if (uch == vowel.charAt(i)) { return true; } } return false; } public String replaceVowels(String phrase,char ch) { StringBuilder newhprase = new StringBuilder(phrase); for(int i = 0; i < phrase.length(); i++) { if (isVowel(phrase.charAt(i))) { newhprase.setCharAt(i, ch); } } return newhprase.toString(); } public String emphasize(String phrase,char ch) { char uch = Character.toUpperCase(ch); StringBuilder newhprase = new StringBuilder(phrase); for(int i = 0; i < phrase.length(); i++) { char newch = Character.toUpperCase(phrase.charAt(i)); if ( newch == uch && i % 2 == 0) { newhprase.setCharAt(i, '*'); } else if (newch == uch && i % 2 != 0) { newhprase.setCharAt(i, '+'); } } return newhprase.toString(); } public void testemphasize() { char ch = 'a'; String phrase ="<NAME>"; String result = emphasize(phrase, ch); System.out.println(result); } public void testvowel() { char character = 'O'; if (isVowel(character)) {System.out.println(character+" is vowel");} else { System.out.println(character+" is NOT vowel");} } public void testreplaceVowels() { char ch = '*'; String phrase = "Hello World"; String result = replaceVowels(phrase,ch); System.out.println(result); } } <file_sep>/VigenereBreaker.java import java.util.*; import edu.duke.*; import java.io.*; public class VigenereBreaker { public String sliceString(String message, int whichSlice, int totalSlices) { StringBuilder split= new StringBuilder(message); String result = ""; for(int startIndex = whichSlice; startIndex < split.length() ; startIndex += totalSlices) { char w = split.charAt(startIndex); result += w; } return result; } public int[] tryKeyLength(String encrypted, int klength, char mostCommon) { int[] key = new int[klength]; CaesarCracker cc = new CaesarCracker(mostCommon); for(int i = 0; i <klength; i++) { String split = sliceString(encrypted, i, klength); int currkey = cc.getKey(split); key[i] = currkey; } return key; } public void breakVigenere () { FileResource fr = new FileResource("secretmessage1.txt"); String encrypted = fr.asString(); int klength = 4; int[] key = new int[klength]; key = tryKeyLength(encrypted, klength, 'e'); VigenereCipher vc = new VigenereCipher(key); String answer = vc.decrypt(encrypted); System.out.print(answer); } public HashSet<String> readDictionary(FileResource fr) { HashSet<String> set = new HashSet<String>(); for (String line : fr.lines()) { set.add(line.toLowerCase()); } return set; } public int countWords(String message,HashSet<String> dictionary) { int count = 0; String [] split = message.split("\\W+"); for(String words : split) { words = words.toLowerCase(); if (dictionary.contains(words)) { count++; } } return count; } public String breakForLanguage(String encrypted,HashSet<String> dictionary) { int max = 0; int[] maxkey = new int [100] ; String message = ""; for(int index = 1; index <= 100; index++) { int [] keys = tryKeyLength(encrypted, index, 'e'); VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); int count = countWords(decrypted,dictionary); if(count > max) { max = count; message = decrypted; maxkey = keys; } } System.out.println("key length = "+ maxkey.length); for (int i=0 ; i <maxkey.length;i++) {System.out.print(maxkey[i]+", ");} System.out.println(); System.out.println(max +" valid words in total "+ message.length()); return message; } public void breakVigenerewithunknowkey () { FileResource fr = new FileResource("secretmessage2.txt"); String encrypted = fr.asString(); FileResource dictionary = new FileResource("dictionaries/English"); HashSet<String> dict = readDictionary(dictionary); String decrypted = breakForLanguage(encrypted,dict); String [] ans = decrypted.split("\\n"); System.out.println(ans[0]); } public void newbreakVigenerewithunknowkey () { FileResource fr = new FileResource("athens_keyflute.txt"); String encrypted = fr.asString(); DirectoryResource dr = new DirectoryResource(); HashMap<String, HashSet<String>> manydict = new HashMap<String, HashSet<String>>(); for (File f : dr.selectedFiles()) { FileResource dictionary = new FileResource(f); HashSet<String> dict = readDictionary(dictionary); manydict.put(f.getName(), dict); } String ansdict = breakForAllLangs(encrypted, manydict); } public void breakForLanguagewithkeylength(String encrypted,HashSet<String> dictionary, int index) { int [] keys = tryKeyLength(encrypted, index, 'e'); VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); int count = countWords(decrypted,dictionary); System.out.println("key length = "+ index); for (int i=0 ; i <keys.length;i++) {System.out.print(keys[i]+", ");} System.out.println(); System.out.println(count +" valid words in total "+ encrypted.length()); } public char mostCommonCharIn(HashSet<String> dictionary) { String result = ""; for (String w : dictionary) { result += w;} int [] counts = countLetters(result); int max = maxIndex(counts); StringBuilder alph = new StringBuilder("abcdefghijklmnopqrstuvwxyz"); char commonch = alph.charAt(max); return commonch; } public String breakForAllLangs(String encrypted, HashMap<String, HashSet<String>> languages) { int max = 0; String ansdict = ""; int num = 0; HashSet<String> ansdicts = new HashSet<String>(); for(String s : languages.keySet()) { HashSet<String> words = languages.get(s); num++; Calendar now = Calendar.getInstance(); long hour = now.get(Calendar.HOUR_OF_DAY); long minute = now.get(Calendar.MINUTE); System.out.println("目前時間為: "+ hour+" 時"+ minute+" 分 "); System.out.println("Trying dict "+s +"第"+num+"本字典"); int count = newbreakForLanguage(encrypted,words); System.out.println("Tried dict "+s+"第"+num+"本字典"+" contains "+count+" vaild words "); if (count > max) { max = count; ansdicts = words; ansdict =s ; } } System.out.println("Best possible dict is "+ ansdict+ " it has "+ max + " vaild words"); Calendar now = Calendar.getInstance(); long hour = now.get(Calendar.HOUR_OF_DAY); long minute = now.get(Calendar.MINUTE); System.out.println("目前時間為: "+ hour+" 時"+ minute+" 分 "); return ansdict; } public int newbreakForLanguage(String encrypted,HashSet<String> dictionary) { char common = mostCommonCharIn(dictionary); System.out.println("common char is "+ common); Calendar now = Calendar.getInstance(); long hour = now.get(Calendar.HOUR_OF_DAY); long minute = now.get(Calendar.MINUTE); System.out.println("目前時間為: "+ hour+" 時"+ minute+" 分 "); int max = 0; int[] maxkey = new int [100] ; String message = ""; for(int index = 1; index <= 100; index++) { System.out.println("trying key length "+ index); int [] keys = tryKeyLength(encrypted, index, common); VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); int count = countWords(decrypted,dictionary); System.out.println("The "+index+" times has "+count+" vaild words in this dict"); if(count > max) { max = count; message = decrypted; maxkey = keys; } } /* System.out.println("key length = "+ maxkey.length); for (int i=0 ; i <maxkey.length;i++) {System.out.print(maxkey[i]+", ");} System.out.println(); */ return max; } public int newbreakForLanguagesperate(String encrypted,HashSet<String> dictionary,char common) { System.out.println("common char is "+ common); Calendar now = Calendar.getInstance(); long hour = now.get(Calendar.HOUR_OF_DAY); long minute = now.get(Calendar.MINUTE); System.out.println("目前時間為: "+ hour+" 時"+ minute+" 分 "); int max = 0; int[] maxkey = new int [100] ; String message = ""; for(int index = 1; index <= 100; index++) { System.out.println("trying key length "+ index); int [] keys = tryKeyLength(encrypted, index, common); VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); int count = countWords(decrypted,dictionary); System.out.println("The "+index+" times has "+count+" vaild words in this dict"); if(count > max) { max = count; message = decrypted; maxkey = keys; } } /* System.out.println("key length = "+ maxkey.length); for (int i=0 ; i <maxkey.length;i++) {System.out.print(maxkey[i]+", ");} System.out.println(); */ return max; } public int maxIndex(int [] vals) { int maxDex =0; for(int k=0; k<vals.length;k++) { if (vals[k] >vals[maxDex]) {maxDex = k;} } return maxDex; } public int[] countLetters(String message) { String alph = "abcdefghijklmnopqrstuvwxyz"; int [] counts = new int[26]; for(int k=0; k< message.length();k++) { char ch = Character.toLowerCase(message.charAt(k)); int dex = alph.indexOf(ch); if (dex !=-1) { counts[dex]+=1; } } return counts; } } <file_sep>/README.md # Caesar-Cipher-algorithm This program implement Caesar Cipher algorithm and breaking it. This is the asssement from the Duke university online course: Java Programming: Arrays, Lists, and Structured Data. wordPlay.java replacing vowels with an asterix. CaesarCipher.java implement Caesar Cipher algorithm for strings. CaesarCipherTwo.java encrypts a message with two keys (key1 is used to encrypt every other letter, starting with the first, and key2 is used to encrypt every other letter, starting with the second), and also decrypts the same message. CaesarCracker.java: an implementation of the Caesar cipher cracking (or breaking) algorithm. VigenereCipher.java: implements a Vigenère cipher algorithm. VigenereBreaker.java: an implementation of the Vigenère cipher cracking (or breaking) algorithm.
32bdd08da90bd9ab45b131a2df2de5019d18e1fd
[ "Markdown", "Java" ]
4
Java
chingyuany/Caesar-Cipher-algorithm
701b8cc712f7f509818263f3a4df445fc19d2813
918d70370526a5748d9e58a6e3bdb06a5988fd67
refs/heads/master
<file_sep>class DashboardController < ApplicationController require 'httparty' include HTTParty def index @dashboard = Dashboard.all.order('value') @last_changed = Dashboard.all.order('updated_at').last @response = HTTParty.get("http://api.openweathermap.org/data/2.5/forecast/daily?zip=#{94536}&cnt=8&APPID=56816b6400cf26a5068b34d20251372f") @chicago_response = HTTParty.get("http://api.openweathermap.org/data/2.5/forecast/daily?zip=#{60007}&cnt=8&APPID=56816b6400cf26a5068b34d20251372f") @texas_response = HTTParty.get("http://api.openweathermap.org/data/2.5/forecast/daily?zip=#{73301}&cnt=8&APPID=56816b6400cf26a5068b34d20251372f") $i = 0 @day = {} @night = {} @icon = {} @des = {} @date = {} @c_day = {} @c_night = {} @c_icon = {} @c_des = {} @c_date = {} @t_day = {} @t_night = {} @t_icon = {} @t_des = {} @t_date = {} 7.times do $i +=1 @day_k = @response['list'][$i]['temp']['day'] @day[$i] = ((1.8*(@day_k-273))+32).floor @night_k = @response['list'][$i]['temp']['night'] @night[$i] = ((1.8*(@night_k-273))+32).floor @icon[$i] = @response['list'][$i]['weather'][0]['icon'] @des[$i] = @response['list'][$i]['weather'][0]['description'] @date[$i] = Time.at(@response['list'][$i]['dt']).to_date.strftime("%m/%d") @c_day_k = @chicago_response['list'][$i]['temp']['day'] @c_day[$i] = ((1.8*(@c_day_k-273))+32).floor @c_night_k = @chicago_response['list'][$i]['temp']['night'] @c_night[$i] = ((1.8*(@c_night_k-273))+32).floor @c_icon[$i] = @chicago_response['list'][$i]['weather'][0]['icon'] @c_des[$i] = @chicago_response['list'][$i]['weather'][0]['description'] @c_date[$i] = Time.at(@response['list'][$i]['dt']).to_date.strftime("%m/%d") @t_day_k = @texas_response['list'][$i]['temp']['day'] @t_day[$i] = ((1.8*(@t_day_k-273))+32).floor @t_night_k = @texas_response['list'][$i]['temp']['night'] @t_night[$i] = ((1.8*(@t_night_k-273))+32).floor @t_icon[$i] = @texas_response['list'][$i]['weather'][0]['icon'] @t_des[$i] = @texas_response['list'][$i]['weather'][0]['description'] @t_date[$i] = Time.at(@response['list'][$i]['dt']).to_date.strftime("%m/%d") end end def update @dashboard = Dashboard.find_by_id(params[:id]) @dashboard.value = params[:value] @dashboard.save end def create @dashboard = Dashboard.new() @dashboard.value = params[:value] @dashboard.color= params[:color] @dashboard.label = params[:label] @dashboard.save end def delete @dashboard = Dashboard.find_by_id(params[:id]) @dashboard.delete redirect_back(fallback_location: root_path) end def seed Rails.application.load_seed redirect_back(fallback_location: root_path) end end <file_sep>class AddLabelToDashboard < ActiveRecord::Migration[5.1] def change add_column :dashboards, :label, :string add_column :dashboards, :value, :integer end end <file_sep>Rails.application.routes.draw do resources :dashboards # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root :to => "dashboard#index" patch '/dashboard/:id', to: 'dashboard#update', via: :all post '/dashboard', to: 'dashboard#create', via: :all delete '/dashboard/:id', to: 'dashboard#delete', via: :all match '/dashboard/seed', to: 'dashboard#seed', via: :all end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Dashboard.delete_all Dashboard.create(label: 'Bought', value: 2, color: 'red') Dashboard.create(label: 'Waiting', value: 5, color: 'brown') Dashboard.create(label: 'Stand By', value: 4, color: 'purple') Dashboard.create(label: 'New', value: 3, color: 'green') Dashboard.create(label: 'Failed', value: 2, color: 'black')
87a13cf0a00e5dda05e6af0d6c9bb5144c9aab64
[ "Ruby" ]
4
Ruby
jesser360/nvxl
be5a527679ea70f4a7e2a3a2eb3fc59e099d6f0b
e37137d317e93f01b4e4ee013a1bd776e03f7711
refs/heads/master
<repo_name>ArtemOnischenko/angular2-fundamentals-study<file_sep>/app/common/toaster.service.ts import { OpaqueToken } from '@angular/core' export let TOASTER_TOKEN = new OpaqueToken('toaster'); export interface Toaster { success (msg: string, title?:string): void; info (msg: string, title?:string): void; warning (msg: string, title?:string): void; error (msg: string, title?:string): void; } <file_sep>/app/app.module.ts import { NgModule } from '@angular/core' import { BrowserModule } from '@angular/platform-browser' import {RouterModule} from '@angular/router' import { EventThumbnailComponent, EventDetailComponent, CreateEventComponent, EventListComponent, EventService, EventRouteActivator, EventListResolver } from './events/index' import { EventsAppComponent } from './events-app.component' import {Error404Component} from './errors/404.component' import {NavBarComponent} from './nav/navbar.component' import {TOASTER_TOKEN, Toaster} from './common/toaster.service' import {jQ_TOKEN} from './common/jQuery.service' import {appRoutes} from "./routes"; import { AuthService } from './user/auth.service' import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {CreateSessionComponent} from "./events/event-details/create-session.component"; import {SessionListComponent} from "./events/event-details/session-list.component"; import {CollapsibleWell} from "./common/collapsible-well.component"; import {DurationPipe} from "./events/shared/duration.pipe"; import {SimpleModalComponent} from "./common/simpleModal.component"; import {ModalTriggerDirective} from "./common/modalTrigger.directive"; declare let toastr: Toaster; declare let jQuery: Object; @NgModule({ imports:[ BrowserModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot(appRoutes) ], declarations: [ EventsAppComponent, EventListComponent, EventThumbnailComponent, NavBarComponent, EventDetailComponent, CreateEventComponent, Error404Component, CreateSessionComponent, SessionListComponent, CollapsibleWell, SimpleModalComponent, DurationPipe, ModalTriggerDirective ], providers: [ EventListResolver, EventService, {provide: TOASTER_TOKEN, useValue: toastr}, {provide: jQ_TOKEN, useValue: jQuery}, AuthService, EventRouteActivator, { provide: 'canDeactivateCreateEvent', useValue: checkDirtyState } ], bootstrap: [EventsAppComponent] }) export class AppModule {} function checkDirtyState(component: CreateEventComponent) { if(component.isDirty) return window.confirm('You have not save this event, do you really want to cancel?'); return true; }<file_sep>/app/events/event-details/create-session.component.ts import {Component, OnInit, Output, EventEmitter} from "@angular/core"; import {FormControl, Validators, FormGroup} from "@angular/forms"; import {restrictedWords} from "../shared/restricted-words.validator"; import {ISession} from "../shared/event.model"; @Component({ selector: 'create-session', templateUrl: 'app/events/event-details/create-session.component.html', styles: [` em {float: right; color: #bd362f; padding-left: 10px} .error input {background: #E3C3C5} `] }) export class CreateSessionComponent implements OnInit{ @Output() saveNewSession = new EventEmitter(); @Output() cancelNewSession = new EventEmitter(); newSessionForm: FormGroup; name:FormControl; presenter:FormControl; duration:FormControl; level:FormControl; abstract:FormControl; ngOnInit() { this.name = new FormControl('', Validators.required); this.presenter = new FormControl('', Validators.required); this.duration = new FormControl('', Validators.required); this.level = new FormControl('', Validators.required); this.abstract = new FormControl('', [Validators.required, Validators.maxLength(400), restrictedWords(['foo', 'bar'])]); this.newSessionForm = new FormGroup({ name: this.name, presenter: this.presenter, duration: this.duration, level: this.level, abstract: this.abstract }) } saveSession(formValues){ let session:ISession = { id: undefined, name: formValues.name, presenter: formValues.presenter, duration: +formValues.duration, level: formValues.level, abstract: formValues.abstract, voters:[] }; this.saveNewSession.emit(session); } cancel(){ this.cancelNewSession.emit(); } }<file_sep>/app/events/create-event.component.ts import { Component } from '@angular/core' import { Router } from '@angular/router' import {EventService} from "./shared/event.service"; @Component({ templateUrl: 'app/events/create-event.component.html', styles: [` em {float: right; color: #bd362f; padding-left: 10px} .error input {background: #E3C3C5} `] }) export class CreateEventComponent { isDirty:boolean = true; event:any; constructor(private router:Router, private eventService:EventService){ } saveEvent(formValues){ this.eventService.saveEvent(formValues); this.isDirty = false; this.router.navigate(['/events']); } cancel() { this.router.navigate(['/events']); } }<file_sep>/app/nav/navbar.component.ts import {Component} from '@angular/core' import {AuthService} from '../user/auth.service' import {ISession} from "../events/shared/event.model"; import {EventService} from "../events/shared/event.service"; @Component({ selector: 'nav-bar', templateUrl: './app/nav/navbar.component.html', styles: [` .nav.navbar-nav {font-size:15px} #searchForm {margin-right: 100px;} @media (max-width: 120px) { #searchForm {display: none;} } li > a.active {color: #F97924; } `] }) export class NavBarComponent { searchTerm:string = ''; foundSession:ISession[]; constructor(private auth:AuthService, private eventService:EventService) { } searchSession(searchTerm){ this.eventService.searchSession(searchTerm).subscribe( sessions => { this.foundSession = sessions; console.log(this.foundSession); }); } }
7ebdcbafdfa6fbe317dd2b0af7c1fe0d17cd260c
[ "TypeScript" ]
5
TypeScript
ArtemOnischenko/angular2-fundamentals-study
c851d03f9719ea7147436e5a3ac4d7e03c3e3c2d
35ffabd93f89f310ff8d6419943c6c62eebf7ab9
refs/heads/master
<repo_name>Homhomich/CryptTask_3<file_sep>/src/com/company/hashFunction/feistel/CBC.java package com.company.hashFunction.feistel; import java.util.BitSet; public class CBC { private BitSet[] text; private Feistel feistel; private BitSet IV; private BitSet[] encryptText; public CBC(BitSet[] text, Feistel feistel, BitSet IV) { this.text = text; this.feistel = feistel; this.IV = IV; } public BitSet[] encrypt() { BitSet[] text = new BitSet[this.text.length]; BitSet[] encryptText = new BitSet[text.length]; for (int i = 0; i < this.text.length; i++) { text[i] = this.text[i].get(0, 64); } text[0].xor(IV); encryptText[0] = feistel.encrypt(text[0]); for (int i = 1; i < text.length; i++) { text[i].xor(encryptText[i - 1]); encryptText[i] = feistel.encrypt(text[i]); } this.encryptText = encryptText; return encryptText; } public BitSet[] decrypt() { BitSet[] encryptText = new BitSet[this.encryptText.length]; BitSet[] decryptText = new BitSet[encryptText.length]; for (int i = 0; i < this.encryptText.length; i++) { encryptText[i] = this.encryptText[i].get(0, 64); } for (int i = encryptText.length - 1; i > 0; i--) { BitSet decryptMessage = feistel.decrypt(encryptText[i]); decryptMessage.xor(encryptText[i - 1]); decryptText[i] = decryptMessage; } BitSet decryptMessage = feistel.decrypt(encryptText[0]); decryptMessage.xor(IV); decryptText[0] = decryptMessage; return decryptText; } } <file_sep>/src/com/company/hashFunction/sensor/Sensor.java package com.company.hashFunction.sensor; public class Sensor { private double z; private double R; private final double n = 8; public Sensor(double z, double R) { this.z = z; this.R = R; } public double getNumber() { this.z = this.z + Math.pow(10, -n); this.R = (this.R / z + Math.PI) % 1; return R; } } <file_sep>/src/com/company/hashFunction/sensor/Tests.java package com.company.hashFunction.sensor; import java.util.Arrays; public class Tests { private static final int amountOfParts = 20; /*Мат ожидание в квадрате*/ private static double getExpectedValueInSquare(double[] arr) { var expectedValue = 0.0; for (double v : arr) { expectedValue += Math.pow(v, 2); } expectedValue /= arr.length; return expectedValue; } /*Мат ожидание*/ public static double getExpectedValue(double[] arr) { var expectedValue = 0.0; for (double v : arr) { expectedValue += v; } expectedValue = expectedValue / arr.length; return expectedValue; } /*Дисперсия*/ public static double getVariance(double[] arr) { return getExpectedValueInSquare(arr) - Math.pow(getExpectedValue(arr), 2); } /*Частотное распредление*/ public static int[] getFrequencyDistribution(double[] arr) { var freqDist = new int[amountOfParts]; Arrays.fill(freqDist, 0); for (double v : arr) { var index = (int) (v * freqDist.length); freqDist[index] += 1; } return freqDist; } /*Хи распредление*/ public static double khiDistribution(double[] arr) { var freqDist = getFrequencyDistribution(arr); var khiDistribution = 0.0; var theoreticalAmount = (double) arr.length / freqDist.length; for (int amount : freqDist) { khiDistribution += Math.pow((amount - theoreticalAmount), 2) / theoreticalAmount; } return khiDistribution; } }
69d3554aa9f18e78ab8a4bec49c2d2942ee14539
[ "Java" ]
3
Java
Homhomich/CryptTask_3
278f9ea4a5ecef06aeeead613357f54b94204899
75226503695b7282189f49367872257bc30d9907
refs/heads/master
<file_sep>/** * Javascript 数组去重实现的不同方式 * d:\Apps\node-v8.11.3-win-x64\node js_useful.js */ // use ES6 Set function unique(arr) { return Array.from(new Set(arr)); } var arr = [1, 1, "true", "true", true, true, 15, 17, 17]; console.log(unique(arr)); // 利用双for 循环 // .splice() 从数组中删除条目,并返回改条目 function unique_for(arr) { for (var i = 0; i < arr.length; i++) { for (var j = 0; j < arr.length; j++) { if (arr[i] == arr[j]) { arr.splice(j, 1); j--; } } } return arr; } var arr = [1, 1, "true", "true", true, true, 15, 17, 17]; console.log(unique(arr)); // 使用 indexOf //indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。 // arr.indexOf(searchElement[, fromIndex]) //The indexOf() method returns the first index at which a given element can be found in the array, // or - 1 if it is not present. function unique_indexOf(arr) { if (!Array.isArray(arr)) { console.log("type error"); return; } var array = []; for (let i = 0; i < arr.length; i++) { if (array.indexOf(arr[i]) === -1) { array.push(arr[i]); } } return array; } /** * 利用Sort * 利用sort()排序方法,然后根据排序后的结果进行遍历,对比相邻的元素. */ function unique_sort(arr) { if (!Array.isArray(arr)) { console.log("type error"); return; } arr = arr.sort(); var array = [arr[0]]; for (let i = 1; i < arr.length; i++) { if (arr[i] !== arr[i - 1]) { array.push(arr[i]); } } return array; } /** * 利用不同对象的属性不能相同的特点进行去重 */ function unique_property(arr) { if (!Array.isArray(arr)) { console.log("type error"); return; } var array = []; var obj = {}; for (let i = 0; i < arr.length; i++) { if (!obj[arr[i]]) { array.push(arr[i]); obj[arr[i]] = 1; } else { obj[arr[i]]++; } } return array; } /** * 第六: use 'includes' * The includes() method determines whether an array includes a certain element, * returning true or false as appropriate. */ function unique_includes(arr) { if (Array.isArray(arr)) { console.log("type error"); return; } var array = []; for (let i = 0; i < arr.length; i++) { if (!array.includes(arr[i])) { array.push(arr[i]); } } return array; } /** * 第七: hasOwnProperty * 判断对象是否存在属性 */ function unique_hasOwnProperty(arr) { var obj = {}; return arr.filter(function(item, index, arr) { return obj.hasOwnProperty(typeof item + item) ? false : obj[typeof item + item]; }); } /** * 第八: 利用filter */ function unique_filter(arr) { return arr.filter(function(item, index, arr) { return arr.indexOf(item, 0) === index; }); } /** * 第九 利用递归 */ function unique_fac(arr) { var array = arr; var len = array.length; array.sort(function(a, b) { return a - b; }); function loop(index) { if (index >= 1) { if (array[index] === array[index - 1]) { array.splice(index, 1); } loop(index - 1); } } loop(len - 1); return array; } /** * 第十: 利用map 数据结构去重 * Map 的使用 */ function unique_map(arr) { let map = new Map(); let array = new Array(); for (let i = 0; i < arr.length; i++) { if (map.has(arr[i])) { map.set(arr[i], true); } else { map.set(arr[i], false); array.push(arr[i]); } } return array; } /** * 第十: reduce * reduce 的使用 */ Array.prototype.unique = function() { var sortArr = this.sort(); var array = []; sortArr.reduce((s1, s2) => { if (s1 !== s2) { array.push(s1); } return s2; }); array.push(sortArr[sortArr.length - 1]); return array; }; <file_sep>// 原生JavaScript实现字符串长度截取 // 原生JavaScript获取域名主机 // 原生JavaScript清除空格 // 原生JavaScript替换全部 // 原生JavaScript转义html标签 // 原生JavaScript还原html标签 // 原生JavaScript时间日期格式转换 // 原生JavaScript判断是否为数字类型 // 原生JavaScript设置cookie值 // 原生JavaScript获取cookie值 // 原生JavaScript加入收藏夹 // 原生JavaScript设为首页 // 原生JavaScript判断IE6 // 原生JavaScript加载样式文件 // 原生JavaScript返回脚本内容 // 原生JavaScript清除脚本内容 // 原生JavaScript动态加载脚本文件 // 原生JavaScript返回按ID检索的元素对象 // 原生JavaScript返回浏览器版本内容 // 原生JavaScript元素显示的通用方法 // 原生JavaScript中有insertBefore方法, 可惜却没有insertAfter方法 ? 用如下函数实现 // 原生JavaScript中兼容浏览器绑定元素事件 // 原生JavaScript光标停在文字的后面,文本框获得焦点时调用 // 原生JavaScript检验URL链接是否有效 // 原生JavaScript格式化CSS样式代码 // 原生JavaScript压缩CSS样式代码 // 原生JavaScript获取当前路径 // 原生JavaScriptIP转成整型 // 原生JavaScript整型解析为IP地址 // 原生JavaScript实现checkbox全选与全不选 // 原生JavaScript判断是否移动设备 // 原生JavaScript判断是否移动设备访问 // 原生JavaScript判断是否苹果移动设备访问 // 原生JavaScript判断是否安卓移动设备访问 // 原生JavaScript判断是否Touch屏幕 // 原生JavaScript判断是否在安卓上的谷歌浏览器 // 原生JavaScript判断是否打开视窗 // 原生JavaScript获取移动设备初始化大小 // 原生JavaScript获取移动设备最大化大小 // 原生JavaScript获取移动设备屏幕宽度 // 原生JavaScript完美判断是否为网址 // 原生JavaScript根据样式名称检索元素对象 // 原生JavaScript判断是否以某个字符串开头 // 原生JavaScript判断是否以某个字符串结束 // 原生JavaScript返回IE浏览器的版本号 // 原生JavaScript获取页面高度 // 原生JavaScript获取页面scrollLeft // 原生JavaScript获取页面可视宽度 // 原生JavaScript获取页面宽度 // 原生JavaScript获取页面scrollTop // 原生JavaScript获取页面可视高度 // 原生JavaScript跨浏览器添加事件 // 原生JavaScript跨浏览器删除事件 // 原生JavaScript去掉url前缀 // 原生JavaScript随机数时间戳 // 原生JavaScript全角半角转换, iCase: 0全到半,1半到全,其他不转化 // 原生JavaScript确认是否键盘有效输入值 // 原生JavaScript获取网页被卷去的位置 // 原生JavaScript另一种正则日期格式化函数 + 调用方法 // 原生JavaScript时间个性化输出功能 // 原生JavaScript解决offsetX兼容性问题 // 原生JavaScript常用的正则表达式 // 原生JavaScript实现返回顶部的通用方法 // 原生JavaScript获得URL中GET参数值 // 原生JavaScript实现全选通用方法 // 原生JavaScript实现全部取消选择通用方法 // 原生JavaScript实现打开一个窗体通用方法 // 原生JavaScript判断是否为客户端设备 // 原生JavaScript获取单选按钮的值 // 原生JavaScript获取复选框的值 // 原生JavaScript判断是否为邮箱 // 原生JavaScript判断是否有列表中的危险字符 // 原生JavaScript判断字符串是否大于规定的长度 // 原生JavaScript判断字符串是为网址不区分大小写 // 原生JavaScript判断字符串是否为小数 // 原生JavaScript判断字符串是否为整数 // 原生JavaScript判断字符串是否为浮点数 // 原生JavaScript判断字符是否为A - Za - z英文字母 // 原生JavaScript判断字符串是否邮政编码 // 原生JavaScript判断字符是否空NULL // 原生JavaScript用正则表达式提取页面代码中所有网址 // 原生JavaScript用正则表达式清除相同的数组(低效率) // 原生JavaScript用正则表达式清除相同的数组(高效率) // 原生JavaScript用正则表达式按字母排序,对每行进行数组排序 // 原生JavaScript字符串反序 // 原生JavaScript用正则表达式清除html代码中的脚本 // 原生JavaScript动态执行JavaScript脚本 // 原生JavaScript动态执行VBScript脚本 // 原生JavaScript实现金额大写转换函数 // 原生JavaScript常用的正则表达式大收集 // 原生JavaScript实现窗体改变事件resize的操作(兼容所以的浏览器) // 原生JavaScript用正则清除空格分左右 // 原生JavaScript判断变量是否空值 // 原生JavaScript实现base64码 // 原生JavaScript实现utf8解码 // 原生JavaScript获取窗体可见范围的宽与高 // 原生JavaScript判断IE版本号(既简洁、又向后兼容!) // 原生JavaScript获取浏览器版本号 // 原生JavaScript半角转换为全角函数 // 原生JavaScript全角转换为半角函数 /** * 原生JavaScript实现字符串长度截取 */ function cutstr(str, len) { var temp; var icount = 0; var patrn = /[^\x00-\xff]/; var strre = ""; for (let i = 0; i < str.length; i++) { if (icount < len - 1) { temp = str.substr(i, 1); } else { } } } <file_sep># String. > 和其他语言不同,javascript 的字符串不区分单引号和双引号,所以不论是单引号还是双引号的字符串,上面的转义字符都能运行 。 ## 长字符串 其一,可以使用 + 运算符将多个字符串连接起来,如下所示: ```javascript let longString = "This is a very long string which needs " + "to wrap across multiple lines because " + "otherwise my code is unreadable."; ``` 其二,可以在每行末尾使用反斜杠字符(“\”),以指示字符串将在下一行继续。确保反斜杠后面没有空格或任何除换行符之外的字符或缩进; 否则反斜杠将不会工作。 如下所示: ```javascript let longString = "This is a very long string which needs \ to wrap across multiple lines because \ otherwise my code is unreadable."; ``` <file_sep>/** * The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value. * Syntax: * new Map([iterable]) * iterable An Array or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]). Each key-value pair is added to the new Map; null values are treated as undefined. * Description: * A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration. * * 键的相等(Key equality) * NaN 是与 NaN 相等的 * 根据 === 运算符的结果判断是否相等 * Objects 和 maps 的比较 * 一个Object的键只能是字符串或者 Symbols,但一个 Map 的键可以是任意值,包括函数、对象、基本类型。 * Map 中的键值是有序的,而添加到对象中的键则不是。因此,当对它进行遍历时,Map 对象是按插入的顺序返回键值。 * 你可以通过 size 属性直接获取一个 Map 的键值对个数,而 Object 的键值对个数只能手动计算。 * Map 可直接进行迭代,而 Object 的迭代需要先获取它的键数组,然后再进行迭代。 * Object 都有自己的原型,原型链上的键名有可能和你自己在对象上的设置的键名产生冲突。 * 虽然 ES5 开始可以用 map = Object.create(null) 来创建一个没有原型的对象,但是这种用法不太常见。 * Map 在涉及频繁增删键值对的场景下会有些性能优势。 * * 属性 * 方法 * - clear() * - delete() * - entries() * - forEach() * - get(key) * - has(key) * - keys() * - set(key, value) * - values() */ // 使用 Map 对象 var myMap = new Map(); var keyObj = {}, keyFunc = function() {}, keyString = "a string"; // 添加键 myMap.set(keyString, "和键'a string'关联的值"); myMap.set(keyObj, "和键keyObj关联的值"); myMap.set(keyFunc, "和键keyFunc关联的值"); myMap.size; // 3 // 读取值 myMap.get(keyString); // "和键'a string'关联的值" myMap.get(keyObj); // "和键keyObj关联的值" myMap.get(keyFunc); // "和键keyFunc关联的值" myMap.get("a string"); // "和键'a string'关联的值" // 因为keyString === 'a string' myMap.get({}); // undefined, 因为keyObj !== {} myMap.get(function() {}); // undefined, 因为keyFunc !== function () {} // 将 NaN 作为 Map 的键 var myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" var otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number" // 使用 for..of 方法迭代 Map var myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (var [key, value] of myMap) { console.log(key + " = " + value); } // 将会显示两个log。一个是"0 = zero"另一个是"1 = one" for (var key of myMap.keys()) { console.log(key); } // 将会显示两个log。 一个是 "0" 另一个是 "1" for (var value of myMap.values()) { console.log(value); } // 将会显示两个log。 一个是 "zero" 另一个是 "one" for (var [key, value] of myMap.entries()) { console.log(key + " = " + value); } // 将会显示两个log。 一个是 "0 = zero" 另一个是 "1 = one" //使用 forEach() 方法迭代 Map myMap.forEach(function(value, key) { console.log(key + " = " + value); }, myMap); // 将会显示两个logs。 一个是 "0 = zero" 另一个是 "1 = one" // Map 与数组的关系 var kvArray = [["key1", "value1"], ["key2", "value2"]]; // 使用常规的Map构造函数可以将一个二维键值对数组转换成一个Map对象 var myMap = new Map(kvArray); myMap.get("key1"); // 返回值为 "value1" // 使用Array.from函数可以将一个Map对象转换成一个二维键值对数组 console.log(Array.from(myMap)); // 输出和kvArray相同的数组 // 或者在键或者值的迭代器上使用Array.from,进而得到只含有键或者值的数组 console.log(Array.from(myMap.keys())); // 输出 ["key1", "key2"] // 复制或合并 Maps var original = new Map([[1, "one"]]); var clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false. Useful for shallow comparison // var first = new Map([[1, "one"], [2, "two"], [3, "three"]]); var second = new Map([[1, "uno"], [2, "dos"]]); // 合并两个Map对象时,如果有重复的键值,则后面的会覆盖前面的。 // 展开运算符本质上是将Map对象转换成数组。 var merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three <file_sep>"use strict"; /** * 引用类型 - Object */ // 对于存储和传输数据,很好 // 两种构造方式 // 第一种 通过 new 关键字 var person = new Object(); person.name = "Bss"; // 第二种方式 对象字面量表示法 var person_2 = { name: "BSS", age: 29 }; /** * 引用类型 - 数组 方法 描述 concat() 连接两个或更多的数组,并返回结果。 join() 把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。 pop() 删除并返回数组的最后一个元素 push() 向数组的末尾添加一个或更多元素,并返回新的长度。 reverse() 颠倒数组中元素的顺序。 shift() 删除并返回数组的第一个元素 slice() 从某个已有的数组返回选定的元素 sort() 对数组的元素进行排序 splice() 删除元素,并向数组添加新元素。 toSource() 返回该对象的源代码。 toString() 把数组转换为字符串,并返回结果。 toLocaleString() 把数组转换为本地数组,并返回结果。 unshift() 向数组的开头添加一个或更多元素,并返回新的长度。 valueOf() 返回数组对象的原始值 操作方法: splice() 位置方法: indexOf() lastIndexOf() 迭代方法: every() // 传入的函数必须每一项都返回true filter() forEach() map() some() // 传入的函数对数组中的某一项返回true, 就返回trye */ // 缩小方法 /** * reduce() * reduceRight() */ var list = new Array(); var list_01 = []; var list_02 = Array(3); // 3 items // Js 的数组的 length 不是只读的,可以通过修改数组长度,增加或者删除item var colors = ["red", "green"]; colors[colors.length] = "black"; //增加了一个项目 colors[colors.length] = "brown"; var cl; for (cl in colors) { console.log(colors[cl]); } // toString() 方法 // toLocalString() 方法 var names = new Array(); names.push("frank", "daliu"); // 迭代方法 var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; var everyResults = nums.every(function(item, index, array) { return item > 2; }); var someResults = nums.some(function(item, index, array) { return item > 2; }); var filterResults = nums.filter(function(item, idnex, array) { return item > 2; }); var mapResults = nums.map(function(item, index, array) { return item * 2; }); console.log( "Use every to check every items is greater then 2 :" + everyResults ); console.log( "Use some to check whether there is an item greater then 2 :" + someResults ); console.log( "Use filter to filter which there is an item greater then 2 :" + filterResults ); console.log("Use map to operate items :" + mapResults); nums.forEach(function(item, index, array) { return item * 5; }); console.log("use forEach to operate array" + nums); console.log(Array.isArray(colors)); /** * 引用类型 - Date * d:\Apps\node-v8.11.3-win-x64\node ref_type.js */ /** * 引用类型 - RegExp */ /** * 引用类型 - Function */ <file_sep># Fontends > leaning notes of Javascript, vuejs, webpack,npm,nodejs - Script - Javascript - Typescript - ES6 - CSS - CSS basic - Bootstrap - HTML - HTML5 - Tools and Frameworkon - Vuejs - NPM - Webpack - Jquery <file_sep>"use strict"; var date = new Date(); console.log(date); /******************************************************* * 正则表达式详解 */ // 匹配模式: g, i , m // var expressions = / pattern /flags; // 需要转义的操作符 ( { { \ ^ $ | ? * + . } } ) var patt = /at/g; var p2 = /[bc]at/i; var p3 = /.at/gi; var p4 = /\[bc\]at/i; // RegExp 实例属性 /** * global : bool, 是否设置了g * ignoreCast : bool, 是否设置了i * lastIndex : 整数,标识开始搜索下一个匹配项的字符位置 * multiline : bool, 是否这只了m * source : 正则的字符串标识, */ // RegExp 的实例方法: exec() /** * * exce() 接受一个参数,就是模式的字符串,然后返回包含第一个匹配项信息的数组;或者返回null * * 返回的虽然是array 的实例,但是包含了两个额外的属相 index, inputl index 标识匹配的字符串位置,input 标识应用正则的字符串 */ var text = "mom and dad and boby"; var p5 = /mom( and dad( and baby)?)?/gi; var matches = p5.exec(text); console.log(matches.index); console.log(matches.input); console.log(matches[0]); console.log(matches[1]); console.log(matches[2]); <file_sep># Javascript ``` 重要知识点: - 函数: 语法,参数,变量作用域,闭包 - 对象: 常用对象 - 常用库 - 严格模式的语法和行为改变 d:\Apps\node-v8.11.3-win-x64\node.exe ``` ``` 数据类型 面向对象 继承 闭包 插件 作用域 跨域 原型链 模块化 自定义事件 内存泄漏 事件机制 异步装载回调 模板引擎 Json AJAX ``` > 内置对象 ``` 基本: Array, ArrayBuffer Boolean Date Map, WeakMap Object Number RegExp String Set, WeakSet Function Math Nan JSON ---------------------------------- Atomics DataView Error, EvalError, InternalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError Float32Array, Float64Array, Int16Array, Int32Array, Int8Array, Generator, GeneratorFunction Infinity Intl, Intl.Collator, Intl.DateTimeFormat, Intl.NumberFormat, Intl.PluralRules Promise Proxy Reflect SharedArrayBuffer Symbol WebAssembly ---------------------------------- 函数 decodeURI(), decodeURIComponent(), encodeURI(), encodeURIComponenet() escape() eval() isFinite() isNaN() null parseFloat, parseInt, undefined(), uneval() ``` ## 严格模式的行为改变 > - 全局变量显示声明 - 禁止`this` 关键字只想全局对象 - 禁止删除变量 - 对象不能有重名的属性 - 函数不能有重名的参数 - ... ## 数据类型 --- ## 操作符 ```javascript // 操作符 - 重点理解 /** 一元, * * 递增,递减 * * */ ++a; --a; a--; a++; // 一元,+ - 操作, 如果不是非数值时,会被转型 // false, true 被转成0,1 // 字符串会被按照一组特殊的规则进行解析 // 对象是先条用 valueof()和 toString()方法,再转换得到值 a = +num; a = -num; ``` ```javascript /* 位操作符 */ ``` --- ## 语句 --- ``` async function ** block break class ** const ** continue debugger ** default ** do...while... empty ** export ** for for each...in for...in...* for...of...* function if...else... import ** import.meta ** lable ** let return switch throw try...catch... var while with **: 不推荐使用 ``` - if 语句 > ```javascript if (condition) statement1 else statement2 // condition 可以是任意表达式,而且结果可以不是布尔值, ECMAScript 会自动调用 Boolean() 转换函数转换为布尔值。 ``` - do-while ```javascript do { statement; } while (expression); // 在对条件表达式求值之前,循环体内的代码至少会被执行一次. ``` - while ```javascript var i = 0; while (i < 10) { i += 2; } // 先计算条件,然后判断是否进入循环; ``` - for ```javascript // 前测试循环语句, 它具有在执行循环之前,初始化变量,定义循环执行代码的能力 var count = 10; for (var i = 0; i < count; i++){ alert(i); } for(;;) // 无限循环 ``` - for-in ```javascript // 是一种精准的迭代语句,用来枚举对象的属性 for (property in expression) statement; for (var propName in window) { document.write(propName); } ``` - lable - break & continue ```javascript // break 语句会立刻退出循环, 强制继续执行循环后面的语句 // continue 语句 也是立刻推出循环,但是退出后会从循环的顶部继续执行. ``` - with - switch ## 函数 --- ### 函数基础 ```javascript 1. 如果有 `return` 语句, 在执行完 `return` 后,会立即停止并立刻退出, 位于return之后的语句的任何代码,都不会执行. 2. `return` 也可以不返回值, 函数也会直接推出,其实是返回了一个 `undedfined` 3. 关于函数参数 函数的类型,个数对函数来说,没有限制 其实再函数内部,所有的参数都会形成一个数组,传给函数, 再函数体内,可以通过 `arguments` 获得这个数组 4. 函数没有重载: 如果定义了同名函数,后一个会覆盖前一个的功能. ``` ### 函数表达式 - 递归 - 闭包 - 私有变量 ## 变量,作用域 & 内存问题 --- ### 基本类型和引用类型的值 值类型: Undefined, Null, Boolean, Number, String 都是值类型 引用类型: Object, Array, Data, RegExp, Function 需要注意的: 1 .可以添加属性,方法,也可以改变和删除其属性和方法. 2. 复制变量值 3. 作为参数, ECMAScript 中所有的参数都是按值传递的,就是说函数外部的值复制给函数内部的参数,就可以值从一个变量复制到另一个变量一样。 4. *访问变量有按照值和引用两种方式, 而参数只能按照值. 5. typeof(var), instanceof(ObjectType): ### 执行环境及作用域 ```javascript 1. 代码执行时,会创建变量对象的一个 `作用域链`(scrope chain),其用途保证对执行环境有权访问的所有变量和函数有序访问. ``` 当 js 代码执行的时候,会进度不同的执行环境,这些不同的执行环境构成了执行环境栈, Javascript 中主要存在三种执行环境 - 全局执行环境 ``` Javascript 默认的执行环境, 通常被默认位 windows 对象,所有的全局变量和函数都作为 windows 对象的属性和方法; ds ``` - 函数执行环境 每个执行环境都有一个与之关联的变量对象(variable object, VO),执行环境中定义的所有变量和函数都会保存在这个对象中,解析器在处理数据的时候就会访问这个内部对象。 - eval() 执行环境 Javascript 的 变量对象 #### 作用域 - 局部作用域:局部变量的优先级高于全局变量。 1. 函数体内用var声明的变量具有局部作用域,成为局部变量 2. 函数的参数也具有局部作用域 **JavaScript 是函数作用域(function scope),没有块级作用域。无论函数体内的变量在什么地方声明,对整个函数都是可见的,即 JavaScript 函数里声明的所有变量都被提前到函数体的顶部,只是提前变量声明,变量的赋值还是保留在原位置。** # 面向对象编程 ## 理解对象 ## 创建对象 ## 继承 ## 事件 ```Javascript // 键盘事件 onkeypress onkeyup onkeydown // 焦点事件 onfocusout onfocus onabort // 图片下载被打断时 onblur // 元素失去焦点时 onclick ondbclick onerror // 加载文件或图片发生错误 // 鼠标事件 onmousedown onmousemove onmouseout onmouseover onmouseup onunload ```
da4cdaf33502c8017cd38a9c421e6732c5c51b56
[ "JavaScript", "Markdown" ]
8
JavaScript
Zhaxichun/fontends
72fb20122d18fcb2af4613055bfb16d51bfac707
4dfdde45332d3ad189698c6a748c00f88c25d833
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kehuang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/24 21:32:25 by kehuang #+# #+# */ /* Updated: 2018/08/31 08:33:04 by kehuang ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "ioft.h" #include "wolf3d.h" void projection(t_env *e); static int usage(char *name) { ft_putstr_fd(name, 2); ft_putstr_fd(": <map.wolf3d>\n", 2); return (EXIT_FAILURE); } int main(int argc, char **argv) { t_env e; if (argc != 2) return (usage(argv[0])); e.core.w = 0; e.core.h = 1; if (parser(&e.core, argv[1]) < 0) { ft_putstr_fd("error\n", 2); return (EXIT_FAILURE); } for (unsigned long j = 0; j < e.core.h; j++) { for (unsigned long i = 0; i < e.core.w; i++) { ft_putnbr(e.core.map[j][i]); ft_putchar(' '); } ft_putchar('\n'); } projection(&e); for (unsigned long j = 0; j < e.core.h; j++) free(e.core.map[j]); free(e.core.map); return (EXIT_SUCCESS); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kehuang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/24 21:46:26 by kehuang #+# #+# */ /* Updated: 2018/09/01 12:23:03 by kehuang ### ########.fr */ /* */ /* ************************************************************************** */ #include "core.h" #include <fcntl.h> #include <unistd.h> #include "libft.h" //#define DEBUG_ON #ifdef DEBUG_ON # include <stdio.h> # define DEBUG_PARSE printf("enter: (%s)\n", __FUNCTION__); #else # define DEBUG_PARSE #endif // %s/DEBUG_PARSE\n\t//g char *ft_strjoin_free(char *s1, char const *s2) { char *dest; int i; int j; if (!s1 || !s2) return (NULL); i = 0; if ((dest = (char *)malloc(sizeof(*dest) * (ft_strlen(s1) + ft_strlen(s2) + 1))) == NULL) return (NULL); while (s1[i] != '\0') { dest[i] = s1[i]; i++; } j = 0; while (s2[j] != '\0') { dest[i + j] = s2[j]; j++; } free(s1); dest[i + j] = '\0'; return (dest); } int get_next_line1(int fd, char **line, char **noleaks) { int ret; char buf[2]; *noleaks = (void *)0; buf[1] = '\0'; ret = 1; if ((*line = ft_strnew(0)) == NULL) return (-1); while (ft_strchr(*line, '\n') == NULL && ret > 0) { if ((ret = read(fd, buf, 1)) == -1) return (-1); else if (ret > 0) if ((*line = ft_strjoin_free(*line, buf)) == NULL) return (-1); } if (ret == 0) return (0); if ((*line)[ft_strlen(*line) - 1] == '\n') (*line)[ft_strlen(*line) - 1] = '\0'; return (1); } static int check_syntax(unsigned long *width, char *line) { DEBUG_PARSE int i; i = 0; while (line[i] != '\0') { while (line[i] == ' ' || line[i] == '\t') i++; if (ft_isdigit(line[i]) || (line[i] == '-' && ft_isdigit(line[++i]))) { *width += 1; while (ft_isdigit(line[i])) i++; } else return (-1); } return ((*width == 0) ? -1 : 0); } static int get_height(unsigned long *width_f, unsigned long *height, int const fd) { DEBUG_PARSE unsigned long width; char *line; char *noleaks; if (get_next_line1(fd, &line, &noleaks) < 0) return (-2); if (check_syntax(width_f, line) == -1) { ft_strdel(&line); return (-3); } ft_strdel(&line); while (get_next_line1(fd, &line, &noleaks) > 0) { width = 0; if (check_syntax(&width, line) == -1) { ft_strdel(&line); return (-3); } *height += 1; ft_strdel(&line); if (width != *width_f) return (-3); } return (0); } static int treat_line(t_core *core, long const y, char *line) { DEBUG_PARSE long x; unsigned int i; unsigned char neg; x = 0; i = 0; while (line[i] != '\0') { while (line[i] == ' ' || line[i] == '\t') i++; core->map[y][x] = 0; if ((neg = (line[i] == '-')) || line[i] == '+') i++; while (ft_isdigit(line[i])) core->map[y][x] = (core->map[y][x] * 10) + (line[i++] - '0'); if (neg) core->map[y][x] = -core->map[y][x]; // insert condition if not [min;max] return -1; x++; } return (0); } static int get_map(t_core *core, char *arg) { DEBUG_PARSE long y; int fd; char *line; char *noleaks; if ((fd = open(arg, O_RDONLY)) < 0) return (-1); if ((core->map = (int **)malloc(sizeof(int *) * core->h)) == NULL) return (-5); y = 0; while (get_next_line1(fd, &line, &noleaks) > 0) { if ((core->map[y] = (int *)malloc(sizeof(int) * core->w)) == NULL) { while (--y >= 0) free(core->map[y]); free(core->map); ft_strdel(&line); return (-6); } if (treat_line(core, y, line) == -1) { ft_strdel(&line); return (-3); } y++; ft_strdel(&line); } return (0); } int border_only_wall(t_core *core) { unsigned long i; unsigned long border; border = core->w - 1; i = 0; while (i < core->h) { if (core->map[i][0] != ID_WALL || core->map[i][border] != ID_WALL) return (FALSE); i++; } border = core->h - 1; i = 0; while (i < core->w) { if (core->map[0][i] != ID_WALL || core->map[border][i] != ID_WALL) return (FALSE); i++; } return (TRUE); } int one_spawn(t_core *core) { unsigned long x; unsigned long y; char c; c = 0; y = 0; while (y < core->h) { x = 0; while (x < core->w) { if (core->map[y][x] == ID_SPAWN) { core->cam.pos.x = x; core->cam.pos.y = y; c++; } if (c > 1) return (FALSE); x++; } y++; } return (c == 1); } int parser(t_core *core, char *name) { DEBUG_PARSE int fd; int ret; if ((fd = open(name, O_RDONLY)) < 0) return (-1); if ((ret = get_height(&core->w, &core->h, fd)) != 0) return (ret); if (close(fd) != 0) return (-4); if (core->w < 3 || core->h < 3) return (-7); if ((ret = get_map(core, name)) != 0) return (ret); if (border_only_wall(core) == FALSE) return (-8); if (one_spawn(core) == FALSE) return (-9); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* projection.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kehuang <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/26 21:10:18 by kehuang #+# #+# */ /* Updated: 2018/09/02 21:29:51 by kehuang ### ########.fr */ /* */ /* ************************************************************************** */ #include <math.h> #include "wolf3d.h" static void sdl_free(t_env *e, int ret) { if (ret & 0x08) SDL_DestroyRenderer(e->render); if (ret & 0x04) SDL_DestroyWindow(e->win); if (ret & 0x02) SDL_Quit(); } int init(t_env *e) { if (SDL_Init(SDL_INIT_VIDEO) != 0) return (0x01); if ((e->win = SDL_CreateWindow(":D", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIN_W, WIN_H, SDL_WINDOW_SHOWN)) == NULL) return (0x02); if ((e->render = SDL_CreateRenderer(e->win, -1, SDL_RENDERER_ACCELERATED)) == NULL) return (0x06); e->core.cam.dir.x = 1.0; e->core.cam.dir.y = 0; e->on = TRUE; SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderClear(e->render); SDL_RenderPresent(e->render); return (0); } void aff_map(t_env *e); void handle_keyboard_event(t_env *e) { static const double a = 5.0 * M_PI / 180; static const double ratio = 0.10; t_vec2 p; t_vec2 d; p = e->core.cam.pos; d = e->core.cam.dir; if (e->evt.key.keysym.sym == SDLK_ESCAPE) e->on = FALSE; else if (e->evt.key.keysym.sym == SDLK_SPACE) { printf("(%f:%f)ID(%d)\n", e->core.cam.pos.x, e->core.cam.pos.y, e->core.map[(unsigned int)(e->core.cam.pos.y + 0.5)][(unsigned int)(e->core.cam.pos.x + 0.5)]); // e->core.cam.dir.x = 1.0; // e->core.cam.dir.y = 0; } else if (e->evt.key.keysym.sym == SDLK_a) { // d = e->core.cam.dir; e->core.cam.dir.x = cos(-a) * d.x - sin(-a) * d.y; e->core.cam.dir.y = sin(-a) * d.x + cos(-a) * d.y; SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderClear(e->render); aff_map(e); SDL_RenderPresent(e->render); } else if (e->evt.key.keysym.sym == SDLK_d) { // d = e->core.cam.dir; e->core.cam.dir.x = cos(a) * d.x - sin(a) * d.y; e->core.cam.dir.y = sin(a) * d.x + cos(a) * d.y; SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderClear(e->render); aff_map(e); SDL_RenderPresent(e->render); } else if (e->evt.key.keysym.sym == SDLK_w) { p.x += e->core.cam.dir.x * ratio; p.y += e->core.cam.dir.y * ratio; // printf("%d(%u:%u)\n", e->core.map[(int)p.y][(int)p.x], // (unsigned int)p.x, (unsigned int)p.y); if (e->core.map[(unsigned int)(p.y + 0.5)][(unsigned int)(e->core.cam.pos.x + 0.5)] == 1) p.y = e->core.cam.pos.y; if (e->core.map[(unsigned int)(e->core.cam.pos.y + 0.5)][(unsigned int)(p.x + 0.5)] == 1) p.x = e->core.cam.pos.x; if (e->core.map[(unsigned int)(p.y + 0.5)][(unsigned int)(p.x + 0.5)] != 1) { e->core.cam.pos.x = p.x; e->core.cam.pos.y = p.y; SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderClear(e->render); aff_map(e); SDL_RenderPresent(e->render); } } else if (e->evt.key.keysym.sym == SDLK_s) { p.x -= e->core.cam.dir.x * ratio * 0.5; p.y -= e->core.cam.dir.y * ratio * 0.5; // printf("%d(%u:%u)\n", e->core.map[(int)p.y][(int)p.x], // (unsigned int)p.x, (unsigned int)p.y); if (e->core.map[(unsigned int)(p.y + 0.5)][(unsigned int)(e->core.cam.pos.x + 0.5)] == 1) p.y = e->core.cam.pos.y; if (e->core.map[(unsigned int)(e->core.cam.pos.y + 0.5)][(unsigned int)(p.x + 0.5)] == 1) p.x = e->core.cam.pos.x; if (e->core.map[(unsigned int)(p.y + 0.5)][(unsigned int)(p.x + 0.5)] != 1) { e->core.cam.pos.x = p.x; e->core.cam.pos.y = p.y; SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderClear(e->render); aff_map(e); SDL_RenderPresent(e->render); } } } void treat_event(t_env *e) { if (e->evt.type == SDL_QUIT) e->on = FALSE; else if (e->evt.type == SDL_KEYDOWN) handle_keyboard_event(e); else if (e->evt.type == SDL_WINDOWEVENT) if (e->evt.window.event == SDL_WINDOWEVENT_EXPOSED) SDL_RenderPresent(e->render); } static void fill_loops(t_env *v, t_vec2 *pos, int x0, int y0) { int i; i = x0 - pos->x; while (i <= x0 + pos->x) { SDL_RenderDrawPoint(v->render, i, y0 + pos->y); SDL_RenderDrawPoint(v->render, i, y0 - pos->y); ++i; } i = x0 - pos->y; while (i <= x0 + pos->y) { SDL_RenderDrawPoint(v->render, i, y0 + pos->x); SDL_RenderDrawPoint(v->render, i, y0 - pos->x); ++i; } } void fill_circle(t_env *v, int x0, int y0, int r) { t_vec2 pos; t_vec2 change; int err; pos.x = r; pos.y = 0; change.x = 1 - (r << 1); change.y = 0; err = 0; while (pos.x >= pos.y) { fill_loops(v, &pos, x0, y0); ++pos.y; err += change.y; change.y += 2; if (((err << 1) + change.x) > 0) { --pos.x; err += change.x; change.x += 2; } } } char send_ray(t_core const *core, t_vec2 const *dir, t_vec2 *inter) { double x; double y; double step[2]; x = core->cam.pos.x; y = core->cam.pos.y; step[0] = dir->x * 0.01; step[1] = dir->y * 0.01; while (y >= 0.0 && x >= 0.0 && y < core->h && x < core->w) { if (core->map[(unsigned long)(y + 0.5)][(unsigned long)(x + 0.5)] == ID_WALL) { inter->x = (unsigned long)x; inter->y = (unsigned long)y; return (TRUE); } // x += dir->x; // y += dir->y; x += step[0]; y += step[1]; } printf("RETURN_ FALSE\n"); return (FALSE); } void aff_map(t_env *e) { unsigned long x; unsigned long y; const unsigned int clr[3] = {0xdcdcdc, 0x6e6e6e, 0xee00}; unsigned int idx; static const unsigned int size = 20; SDL_Rect rect; t_vec2 pos; t_vec2 dir; // aff wall {{{ t_vec2 d; t_vec2 inter; double astep_ray; double angle; double rad; double t; int i; double calc; i = 0; astep_ray = (double)(60.0 / WIN_W); angle = -30; while (i < WIN_W) { rad = angle * M_PI / 180; d.x = cos(rad) * e->core.cam.dir.x - sin(rad) * e->core.cam.dir.y; d.y = sin(rad) * e->core.cam.dir.x + cos(rad) * e->core.cam.dir.y; if (send_ray(&e->core, &d, &inter) == TRUE) { t = hypot(inter.x - e->core.cam.pos.x, inter.y - e->core.cam.pos.y); SDL_SetRenderDrawColor(e->render, 0xff, 0, 0xff, 0); calc = (WIN_H / -2) + (t * fmax(e->core.h, e->core.w) * 2); // this one line .................................... if (calc < (WIN_H / 2)) SDL_RenderDrawLine(e->render, i, calc, i, (WIN_H / 2)); } else ; angle += astep_ray; i++; } // aff wall }}} // aff minimap {{{ pos = e->core.cam.pos; rect.w = size; rect.h = size; y = 0; while (y < e->core.h) { x = 0; while (x < e->core.w) { idx = e->core.map[y][x]; SDL_SetRenderDrawColor(e->render, (clr[idx] >> 16) & 0xff, (clr[idx] >> 8) & 0xff, clr[idx] & 0xff, 0); rect.x = x * size; rect.y = 320 + y * size; // rect.x = (x + 1) * size; // rect.y = (y + 1) * size; SDL_RenderFillRect(e->render, &rect); SDL_SetRenderDrawColor(e->render, 0, 0, 0, 0); SDL_RenderDrawRect(e->render, &rect); x++; } y++; } SDL_SetRenderDrawColor(e->render, 0xff, 0, 0, 0); pos.x = pos.x * 20 + 10; pos.y = 320 + pos.y * 20 + 10; fill_circle(e, pos.x, pos.y, 2); // SDL_SetRenderDrawColor(e->render, 0xff, 0, 0xff, 0); // aff direction dir = e->core.cam.dir; dir.x = dir.x * 400; dir.y = dir.y * 400; SDL_RenderDrawLine(e->render, pos.x, pos.y, pos.x + dir.x, pos.y + dir.y); // aff left fov dir = e->core.cam.dir; dir.x = cos(-30 * M_PI / 180) * e->core.cam.dir.x - sin(-30 * M_PI / 180) * e->core.cam.dir.y; dir.y = sin(-30 * M_PI / 180) * e->core.cam.dir.x + cos(-30 * M_PI / 180) * e->core.cam.dir.y; dir.x = dir.x * 400; dir.y = dir.y * 400; SDL_RenderDrawLine(e->render, pos.x, pos.y, pos.x + dir.x, pos.y + dir.y); // aff right fov dir = e->core.cam.dir; dir.x = cos(30 * M_PI / 180) * e->core.cam.dir.x - sin(30 * M_PI / 180) * e->core.cam.dir.y; dir.y = sin(30 * M_PI / 180) * e->core.cam.dir.x + cos(30 * M_PI / 180) * e->core.cam.dir.y; dir.x = dir.x * 400; dir.y = dir.y * 400; SDL_RenderDrawLine(e->render, pos.x, pos.y, pos.x + dir.x, pos.y + dir.y); // aff minimap }}} } void projection(t_env *e) { int ret; if ((ret = init(e))) { sdl_free(e, ret); return ; } aff_map(e); while (e->on == TRUE) while (SDL_PollEvent(&e->evt)) treat_event(e); sdl_free(e, 0x0e); }
6654cf60db31e2194599a8b0963bc9737c89a04b
[ "C" ]
3
C
Ctsu27/wolf3d
4556bca3bcf7ab8849304c9b6a85e6c0280bbbce
29427662db1eebf936b29662c3954b6dc6af8619
refs/heads/master
<file_sep>package utils import ( "bufio" "fmt" "os" ) func handleMissingFile(filePath string) bool { fmt.Println(filePath, "does not exist. Should we create it for you? y/n") reader := bufio.NewReader(os.Stdin) char, _, err := reader.ReadRune() if err != nil { fmt.Println(err) } switch char { case 'y': os.Create(filePath) fmt.Println("File created") return true case 'n': fmt.Println("No file created") os.Exit(0) default: handleMissingFile(filePath) } return false } // ReadTasks Tries to open a file for reading, and returns each line // as a value in a slice, or asks the use to create the file func ReadTasks(filePath string) []string { file, err := os.Open(filePath) defer file.Close() if err != nil { handleMissingFile(filePath) } scanner := bufio.NewScanner(file) result := []string{} for scanner.Scan() { line := scanner.Text() result = append(result, line) } return result } // WriteTasks takes in a filePath and a slice of tasks, // tries to open the supplied filePath, calls handleMissingFile // if unsuccessful asks the user to crate the file, otherwise it // opens the supplied filePath, empties it's contents // and writes each task in the slice to the file before // returning true on success. func WriteTasks(filePath string, tasks []string) bool { file, err := os.OpenFile(filePath, os.O_RDWR, 0700) defer file.Close() file.Truncate(0) if err != nil { handleMissingFile(filePath) return false } for _, line := range tasks { file.WriteString(line + "\n") } file.Sync() return true } // Find taks a slice and a string, and iterates // over the slice, and returns true if it finds // a match and false if it doesn't func Find(slice []string, val string) bool { for _, item := range slice { if item == val { return true } } return false } // Filter taks a slice and a function that returns a boolean, // then iterates over the slice running the function on each // item, and pushes any that return true onto a new slice, // returning the new slice when finished func Filter(slice []string, fun func(int) bool) []string { filtered := make([]string, 0) for ind, item := range slice { if fun(ind) { filtered = append(filtered, item) } } return filtered } <file_sep>package commands import ( "fmt" "strconv" "t/colour" "t/config" "t/utils" ) // DeleteItem reads the tasks out of the configured file // then filters the resulting slice base on index and taskID // and finally writes the resulting slice to the file before // letting the user know it has been successful func DeleteItem(input []string) { if len(input) >= 2 { fmt.Println(colour.BoldRed("Too many values supplied")) return } // convert the taskID to int64, because I can't // work out how to convert to int taskID, _ := strconv.ParseInt(input[0], 10, 0) // Read file into array/slice tasks := utils.ReadTasks(config.DefaultConfig.FilePath) // Check that the task exists if len(tasks) < int(taskID) { fmt.Println(colour.BoldRed("Task does not exist")) return } // Filter the task out of the slice newTasks := utils.Filter(tasks, func(ind int) bool { return ind != int(taskID)-1 }) // Write the slice back to the file success := utils.WriteTasks(config.DefaultConfig.FilePath, newTasks) if success { fmt.Println(colour.BoldGreen("Task has been yeeted")) } } <file_sep># Contributing Guidelines The following is a set of guidelines for contributing to the project. These are mostly guidelines, not rules. Feel free to propose changes to this document in a pull request. ## General I welcome all contributions to this project, no matter how small. But please keep a few things in mind when you do contribute: * Please leave the place nicer than you found it. If something can be made simpler or more readable, please make the change. * While all contributions are welcome, not all will be accepted. This may be for any number of reasons, including work that is not aligned with the goal of the project, work that introduces unnecessary complexity, and a number of other reasons * If you are providing feedback on another's contribution, please remember that there is a human on the other side of your computer and strive to be: * Kind * Respectful * Constructive ## Branching Strategy I use a single branch branching strategy where all branches are made from `master` and and merge back into `master`. New feature should be developed on a branch with the prefix `feature`, and bugfixes should be developed on a branch prefixed with `bugfix`. If you've forked the repo and want to make a PR, it doesn't matter what you've called your branch, it'll be judged on its merits. ## Pull Requests Please confirm that: 1. There isn't already a PR to fix the issue 2. If you are fixing a bug, that there is a issue related to it (feel free to raise one if it doesn't exist) 3. You provide some context around your change, why it was made and how to test it ## Styleguides ### Coding Styleguides There isn't one. This is my first Go project, so I'm not sure what the consensus standards are. ### Git Commit Messages I like [Conventional Commits][conv-commits] to ensure consistency of commit messages, although I don't always abide by them. A compliant commit looks like this: ``` <type>(optional scope): <description> <optional body> ``` * The first line of the commit becomes the subject line * Don't capitalize the first letter of the description * Use the imperative mood ("add feature" not "adds feature") * Use present tense ("add feature" not "added feature") * No period (.) at the end of the subject line * Limit the subject line to 72 characters or less. [conv-commits]: https://www.conventionalcommits.org/en/v1.0.0-beta.3/<file_sep>package commands import ( "fmt" "strings" "t/colour" "t/config" "t/utils" ) // AddItem reads the list of tasks from the configured // file, then checks to see if the new task already exists // and pushes it to the slice if not. It then writes the // resulting slice to the configured file. func AddItem(input []string) { tasks := utils.ReadTasks(config.DefaultConfig.FilePath) task := strings.Join(input, " ") // Check that the task doesn't already exist found := utils.Find(tasks, task) if found { fmt.Println("Task already exists") return } // Add the task to the end of the slice tasks = append(tasks, task) if utils.WriteTasks(config.DefaultConfig.FilePath, tasks) { fmt.Println(colour.BoldGreen("Task added")) } } <file_sep>package colour const ( normalText = "\033[0m" // Turn off all attributes redText = "\033[31m" greenText = "\033[32m" yellowText = "\033[33m" blueText = "\033[34m" magentaText = "\033[35m" cyanText = "\033[36m" whiteText = "\033[37m" boldText = "\033[1m" boldRedText = "\033[1;31m" boldGreenText = "\033[1;32m" boldYellowText = "\033[1;33m" boldBlueText = "\033[1;34m" boldMagentaText = "\033[1;35m" boldCyanText = "\033[1;36m" faintText = "\033[2m" faintRedText = "\033[2;31m" faintGreenText = "\033[2;32m" faintYellowText = "\033[2;33m" faintBlueText = "\033[2;34m" faintMagentaText = "\033[2;35m" faintCyanText = "\033[2;36m" faintWhiteText = "\033[2;37m" ) // Red taks a string and returns that string escaped with the colour code // for red text func Red(str string) string { return string(redText + str + normalText) } // Green taks a string and returns that string escaped with the colour code // for green text func Green(str string) string { return string(greenText + str + normalText) } // Yellow taks a string and returns that string escaped with the colour code // for yellow text func Yellow(str string) string { return string(yellowText + str + normalText) } // Blue taks a string and returns that string escaped with the colour code // for blue text func Blue(str string) string { return string(blueText + str + normalText) } // Magenta taks a string and returns that string escaped with the colour code // for __ text func Magenta(str string) string { return string(magentaText + str + normalText) } // Cyan taks a string and returns that string escaped with the colour code // for __ text func Cyan(str string) string { return string(cyanText + str + normalText) } // White taks a string and returns that string escaped with the colour code // for __ text func White(str string) string { return string(whiteText + str + normalText) } // Bold takes a string and returns that string wrapped with the escape sequence // to set it bold func Bold(str string) string { return string(boldText + str + normalText) } // BoldRed takes a string and returns that string wrapped with the escape sequence // to set it bold and color it red func BoldRed(str string) string { return string(boldRedText + str + normalText) } // BoldGreen takes a string and returns that string wrapped with the escape sequence // to set it bold and color it green func BoldGreen(str string) string { return string(boldGreenText + str + normalText) } // BoldYellow takes a string and returns that string wrapped with the escape sequence // to set it bold and color it yellow func BoldYellow(str string) string { return string(boldYellowText + str + normalText) } // BoldBlue takes a string and returns that string wrapped with the escape sequence // to set it bold and color it blue func BoldBlue(str string) string { return string(boldBlueText + str + normalText) } // BoldMagenta takes a string and returns that string wrapped with the escape sequence // to set it bold and color it magenta func BoldMagenta(str string) string { return string(boldMagentaText + str + normalText) } // BoldCyan takes a string and returns that string wrapped with the escape sequence // to set it bold and color it cyan func BoldCyan(str string) string { return string(boldCyanText + str + normalText) } // Faint takes a string and returns that string wrapped with the escape sequence // to render it faintly func Faint(str string) string { return string(faintText + str + normalText) } // FaintRed takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it red func FaintRed(str string) string { return string(faintRedText + str + normalText) } // FaintGreen takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it green func FaintGreen(str string) string { return string(faintGreenText + str + normalText) } // FaintYellow takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it yellow func FaintYellow(str string) string { return string(faintYellowText + str + normalText) } // FaintBlue takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it blue func FaintBlue(str string) string { return string(faintBlueText + str + normalText) } // FaintMagenta takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it magenta func FaintMagenta(str string) string { return string(faintMagentaText + str + normalText) } // FaintCyan takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it cyan func FaintCyan(str string) string { return string(faintCyanText + str + normalText) } // FaintWhite takes a string and returns that string wrapped with the escape sequence // to render it faintly and color it white func FaintWhite(str string) string { return string(faintWhiteText + str + normalText) } <file_sep>package commands import ( "fmt" "strconv" "t/colour" "t/config" "t/utils" ) // ListItems reads the list of tasks from the configured // file, then prints them out to the terminal with a header // # TODO func ListItems() { tasks := utils.ReadTasks(config.DefaultConfig.FilePath) length := len(tasks) newLine := "\n" fmt.Println(newLine + colour.BoldBlue("# TODO") + newLine) if length > 0 { for i, task := range tasks { id := strconv.Itoa(i+1) + "." fmt.Println(colour.Faint(id), task) } } else { fmt.Println(colour.BoldGreen("Nothing to do")) } } <file_sep>package main import ( "fmt" "os" "strings" "t/colour" "t/commands" "t/config" ) var versionString string = colour.Blue("0.0.1") const helpString string = `t - The minimalist command line todo manager Usage: t [option] <Input> Options: -l, --list List the tasks in the todo list -a, --add <Task> Add a task to the todo list -d, --delete <TaskID> Delete a task from the todo list -v, --version Show the version -h, --help Show this help information` func main() { config.InitialiseConfig() if len(os.Args) <= 1 { os.Args = append(os.Args, "l") } var input = os.Args[2:] var flag string = strings.TrimPrefix(os.Args[1], "-") // Just to trim for long form flags flag = strings.TrimPrefix(flag, "-") switch flag { case "l", "list": commands.ListItems() case "a", "add": commands.AddItem(input) case "d", "delete": commands.DeleteItem(input) case "h", "help": showHelp() case "v", "version": showVersion() } } func showHelp() { fmt.Println(helpString) } func showVersion() { fmt.Println("Version:", versionString) } <file_sep>package config import ( "encoding/json" "os" "strings" ) var home, _ = os.UserHomeDir() // Config is the main config shape for our app type Config struct { Path string FileName string FilePath string } // DefaultConfig is our config instance used in the app var DefaultConfig = Config{ Path: home + "/.t/", FileName: "todo.txt", FilePath: home + "/.t/todo.txt", } // InitialiseConfig will check for the existance of a config // file in the users home directory and override the values // on the defaultConfig variable if one is found func InitialiseConfig() { file, err := os.Open(home + "/.t.json") defer file.Close() decoder := json.NewDecoder(file) if err == nil { err = decoder.Decode(&DefaultConfig) if DefaultConfig.Path[1] == 47 { DefaultConfig.Path = strings.Replace(DefaultConfig.Path, "~", home, -1) } DefaultConfig.FilePath = DefaultConfig.Path + DefaultConfig.FileName } } <file_sep># t t - the minimalist command line todo list This is still a work in progress Features: - [x] List todo items - [x] Add todo items - [x] Delete todo items - [x] Save todo items in a file - [x] Configure using a config file - [x] Have a default config - [x] Colourise output ## Prerequisites * [Go](https://golang.org) ## Installation There's a number of ways you can get t: #### Download the binary Download the binary from the latest [release][binary] #### Run from source ```go run t``` #### Compile ```go build t``` then move the binary to somewhere in your `$PATH` ## Usage ``` Usage: t [option] <Input> Options: -l, --list List the tasks in the todo list -a, --add <Task> Add a task to the todo list -d, --delete <TaskID> Delete a task from the todo list -v, --version Show the version -h, --help Show this help information ``` ## Contributing Please read [CONTRIBUTING.md][cont] for details on how to contribute to this project, including coding standards, commit message requirements and the process for submitting pull requests. ## Versioning SemVer all the things [cont]: https://github.com/deanacus/t/tree/master/CONTRIBUTING.md [binary]: https://github.com/deanacus/t/releases/latest
b709a2dca3685c920f4b90a30d5a0b45c5c828e4
[ "Markdown", "Go" ]
9
Go
deanacus/t
c422fdba04cf36e9520d38dd14594084f1e04121
50d67ba0268b2b764609864bb8487b753f25eaea
refs/heads/master
<file_sep>const cheerio = require("cheerio"); const cheerioTableparser = require("cheerio-tableparser"); const foodDataFetcher = require("./foodDataFetcher"); function removeT(str) { return str.replace(/\t/g, ""); } function removeNT(str) { return str.replace(/\t/g, "").replace(/\n/g, ""); } function parseTable(body, date) { const $ = cheerio.load(body); cheerioTableparser($); let parsedTable = []; $(".tbl_food_list").each(function(i) { if (i === date) parsedTable = $(this).parsetable(true, true, true); }); //서호관은 가격 등재가 파싱하기 매우 까다로우며, 가격 나열이 의미 없어보여 일단 제외함. return parsedTable[2]; } function tableRowToObject(table, row) { const mealTime = ["점심", "스낵", "저녁"]; return [ { kitchen: mealTime[row], meal: removeT(table[row]), price: null } ]; } async function getParsedTable() { const body = await foodDataFetcher.fetchSeohoData(); const todayDay = new Date().getDay() - 1; return parseTable(body, todayDay); } module.exports.getLunchFromTable = async () => { return tableRowToObject(await getParsedTable(), 0); }; module.exports.getSnackFromTable = async () => { return tableRowToObject(await getParsedTable(), 1); }; module.exports.getDinnerFromTable = async () => { return tableRowToObject(await getParsedTable(), 2); }; <file_sep># 인하대학교 카카오톡 학식 알리미 인하대학교 카카오톡 학식 알리미는 **AWS Lambda** 위에서 돌아가며, **node.js 의 serverless 프레임워크**로 개발된 카카오톡 플러스친구 챗봇입니다. 그렇기에 구동에는 AWS 계정이 필수적으로 존재해야합니다. ## Dependencies 아래의 모듈을 설치해야합니다. - serverless - cheerio - cheerio-tableparser - request npm ``` npm install ``` yarn ``` yarn ``` 위의 명령어를 입력해, 모듈을 자동으로 설치합니다. ## Get Started [이 링크](https://medium.com/@jwyeom63/%EB%B9%A0%EB%A5%B4%EA%B2%8C-%EB%B0%B0%EC%9B%8C%EB%B3%B4%EB%8A%94-node-js%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EC%84%9C%EB%B2%84%EB%A6%AC%EC%8A%A4-serverless-503ee61539d4) 를 참조하여 AWS Lambda 세팅부터 Serverless 프레임워크로 작성된 어플리케이션 실행방법 까지 알 수 있습니다. <file_sep>const cheerio = require("cheerio"); const cheerioTableparser = require("cheerio-tableparser"); const foodDataFetcher = require("./foodDataFetcher"); function removeT(str) { return str.replace(/\t/g, ""); } function removeNT(str) { return str.replace(/\t/g, "").replace(/\n/g, ""); } function replaceBackslashToWonsign(str) { str = str.replace(/\\/g, "₩"); return str; } function parseTable(body, date) { const $ = cheerio.load(body); cheerioTableparser($); let parsedTable = []; $(".tbl_food_list").each(function(i) { if (i === date) parsedTable = $(this).parsetable(true, true, true); }); parsedTable.splice(0, 2); return parsedTable; } function tableRowToObject(table, row) { return { kitchen: removeNT(table[0][row]), meal: removeT(table[1][row]), price: table[2][row] }; } function rowRangeToArray(table, from, to) { const rowRange = []; for (i = from; i <= to; i++) { rowRange.push(tableRowToObject(table, i)); } return rowRange; } async function getParsedTable() { const body = await foodDataFetcher.fetchPlazaData(); const todayDay = new Date().getDay() - 1; return parseTable(body, todayDay); } module.exports.getBreakfastFromTable = async () => { //조식은 가격 표시가 메뉴와 함께 되어있다. const range = rowRangeToArray(await getParsedTable(), 0, 1); range.forEach((obj, i) => { range[i].meal = replaceBackslashToWonsign(range[i].meal); }); return range; }; module.exports.getLunchFromTable = async () => { return rowRangeToArray(await getParsedTable(), 2, 6); }; module.exports.getSnackFromTable = async () => { return rowRangeToArray(await getParsedTable(), 8, 9); }; module.exports.getDinnerFromTable = async () => { return rowRangeToArray(await getParsedTable(), 10, 12); }; <file_sep>"use strict"; const plazaParser = require("./plazaParser"); const seohoParser = require("./seohoParser"); function getReplyMessage(message, buttonType) { let buttons = []; switch (buttonType) { case "main": buttons = ["학생회관 (비룡플라자)", "서호관", "문의하기", "개발자 정보"]; break; case "plaza": buttons = [ "아침 (학생회관)", "점심 (학생회관)", "스낵 (학생회관)", "저녁 (학생회관)", "처음으로" ]; break; case "seoho": buttons = ["점심 (서호관)", "스낵 (서호관)", "저녁 (서호관)", "처음으로"]; break; } const replyMessage = { message: { text: message }, keyboard: { type: "buttons", buttons: buttons } }; return replyMessage; } function getTodayDateText() { let today = new Date(); if (today.getDay() === 0 || today.getDay() === 6) { const first = today.getDate() - today.getDay(); today = new Date(today.setDate(first + 6)).toUTCString(); } return `${today.getFullYear()}년 ${today.getMonth() + 1}월 ${today.getDate()}일 학식`; } function mealObjectToText(mealObj) { let text = `${getTodayDateText()}\n\n`; mealObj.forEach((obj, i) => { text += `[${obj.kitchen}]\n`; text += `${obj.meal}\n\n`; if (obj.price !== "") text += `${obj.price} 원\n\n`; }); return text; } function getSendData(message, buttonType, statusCode = 200) { return { statusCode, body: JSON.stringify(getReplyMessage(message, buttonType)) }; } module.exports.message = async (event, context) => { const { content } = JSON.parse(event.body); let message = ""; let buttonType = ""; switch (content) { //메인메뉴 case "처음으로": message = "학생회관 (비룡플라자) / 서호관 을 선택해주세요."; buttonType = "main"; break; case "문의하기": message = "아래 링크로 접속하여, 인하대학교 학식 알리미 문의 오픈채팅에 접속해주세요.\n\nhttps://open.kakao.com/o/svLzGu6"; buttonType = "main"; break; case "개발자 정보": message = "인하대학교 17학번 사회인프라공학과 조동현 (Hudi)\n\n블로그) http://hudi.kr\n페이스북) http://www.facebook.com/profile.php?id=100007156273191"; buttonType = "main"; break; case "학생회관 (비룡플라자)": message = "아침/점심/스낵/저녁 중에서 선택해주세요."; buttonType = "plaza"; break; case "서호관": message = "점심/스낵/저녁 중에서 선택해주세요."; buttonType = "seoho"; break; //학생회관 메뉴 case "아침 (학생회관)": message = mealObjectToText(await plazaParser.getBreakfastFromTable()); buttonType = "plaza"; break; case "점심 (학생회관)": message = mealObjectToText(await plazaParser.getLunchFromTable()); buttonType = "plaza"; break; case "스낵 (학생회관)": message = mealObjectToText(await plazaParser.getSnackFromTable()); buttonType = "plaza"; break; case "저녁 (학생회관)": message = mealObjectToText(await plazaParser.getDinnerFromTable()); buttonType = "plaza"; break; //서호관 메뉴 case "점심 (서호관)": message = mealObjectToText(await seohoParser.getLunchFromTable()); buttonType = "seoho"; break; case "스낵 (서호관)": message = mealObjectToText(await seohoParser.getSnackFromTable()); buttonType = "seoho"; break; case "저녁 (서호관)": message = mealObjectToText(await seohoParser.getDinnerFromTable()); buttonType = "seoho"; break; } return getSendData(message, buttonType); }; module.exports.keyboard = async (event, context) => { return { statusCode: 200, body: JSON.stringify({ type: "buttons", buttons: ["학생회관 (비룡플라자)", "서호관"] }) }; }; <file_sep>const request = require("request"); const plazaURL = "https://m.inha.ac.kr/homepage/campus/FoodMenuList.aspx?gubun=0"; const seohoURL = "https://m.inha.ac.kr/homepage/campus/FoodMenuList.aspx?gubun=2"; const fetchData = async url => { return new Promise((resolve, reject) => { request(url, (error, response, body) => { resolve(body); }); }); }; module.exports.fetchPlazaData = async () => { return await fetchData(plazaURL); }; module.exports.fetchSeohoData = async () => { return await fetchData(seohoURL); };
b2146777d7e9b8226a9d85300d8f0834faad6da1
[ "JavaScript", "Markdown" ]
5
JavaScript
devHudi/inhafood-bot
d37b515fc05e89b77496d193eed243de283b97a0
da7d34aba7a6a67ad147806854dd4ea9118655eb
refs/heads/main
<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Net; using System.Net.Sockets; using Aws.GameLift.Server; using Aws.GameLift.Server.Model; namespace AGLW_CSharp_BetterChatServerSample { class ConnectedClient { public readonly System.Text.Encoding Encoder = System.Text.Encoding.UTF8; public TcpClient TargetClient { get; private set; } = null; public NetworkStream TargetStream { get; private set; } = null; public ConcurrentQueue<byte[]> SendingQueue { get; private set; } = null; public ConcurrentQueue<byte[]> ReceivingQueue { get; private set; } = null; public Thread SenderThread { get; private set; } = null; public Thread ReceiverThread { get; private set; } = null; public ConnectedClient(TcpClient client) { TargetClient = client; TargetStream = client.GetStream(); SendingQueue = new ConcurrentQueue<byte[]>(); ReceivingQueue = new ConcurrentQueue<byte[]>(); } public void StartClient() { SenderThread = new Thread(() => Send()); SenderThread.Start(); ReceiverThread = new Thread(() => Receive()); ReceiverThread.Start(); } // Should be called by server, add a message to queue, will be sent to client later public void SendMessage(byte[] bytes) { SendingQueue.Enqueue(bytes); } // Should be called by server, retrieve message public bool RetrieveMessage(out byte[] bytes) { bool retrieved = ReceivingQueue.TryDequeue(out bytes); return retrieved; } // Looping in a sender thread private void Send() { byte[] bytes; while (TargetStream != null) { if (SendingQueue.TryDequeue(out bytes)) { TargetStream.Write(bytes); } } } // Looping in a receiver thread private void Receive() { byte[] bytes = new byte[ChatServer.MessageLength]; if (TargetStream != null) { try { while (TargetStream.Read(bytes) > 0) { Console.WriteLine($"Message Received: {Encoder.GetString(bytes)}"); ReceivingQueue.Enqueue(bytes); bytes = new byte[ChatServer.MessageLength]; } } catch(SocketException e) { Console.WriteLine($"Excpetion catched : {e}"); } catch(IOException e) { Console.WriteLine($"Excpetion catched : {e}"); } } } } }<file_sep># AGLW-CSharp-BetterChatServerSample<file_sep>using System; namespace AGLW_CSharp_BetterChatServerSample { class Program { static private GameLiftServer gameLiftServer = new GameLiftServer(); static void Main(string[] args) { gameLiftServer.Start(); while(gameLiftServer.IsAlive) { } Console.WriteLine("Program ends."); } } } <file_sep>using System; using System.Collections.Generic; using System.Threading; using System.Net; using System.Net.Sockets; using System.Collections.Concurrent; using Aws.GameLift.Server; using Aws.GameLift.Server.Model; namespace AGLW_CSharp_BetterChatServerSample { class GameLiftServer { public ChatServer Server { get; private set; } = null; // A instance's status flag of this class public bool IsAlive { get; private set; } = false; public GameLiftServer() { } //This is an example of a simple integration with GameLift server SDK that will make game server processes go active on GameLift! public void Start() { //Identify port number (hard coded here for simplicity) the game server is listening on for player connections var listeningPort = 7777; //InitSDK will establish a local connection with GameLift's agent to enable further communication. Console.WriteLine(GameLiftServerAPI.GetSdkVersion().Result); var initSDKOutcome = GameLiftServerAPI.InitSDK(); if (initSDKOutcome.Success) { ProcessParameters processParameters = new ProcessParameters( this.OnStartGameSession, this.OnUpdateGameSession, this.OnProcessTerminate, this.OnHealthCheck, listeningPort, //This game server tells GameLift that it will listen on port 7777 for incoming player connections. new LogParameters(new List<string>() { //Here, the game server tells GameLift what set of files to upload when the game session ends. //GameLift will upload everything specified here for the developers to fetch later. "/local/game/logs/myserver.log" })); //Calling ProcessReady tells GameLift this game server is ready to receive incoming game sessions! var processReadyOutcome = GameLiftServerAPI.ProcessReady(processParameters); if (processReadyOutcome.Success) { // Set Server to alive when ProcessReady() returns success IsAlive = true; Console.WriteLine("ProcessReady success."); } else { IsAlive = false; Console.WriteLine("ProcessReady failure : " + processReadyOutcome.Error.ToString()); } } else { IsAlive = true; Console.WriteLine("InitSDK failure : " + initSDKOutcome.Error.ToString()); } } void OnStartGameSession(GameSession gameSession) { Server = new ChatServer(gameSession); //When a game session is created, GameLift sends an activation request to the game server and passes along the game session object containing game properties and other settings. //Here is where a game server should take action based on the game session object. //Once the game server is ready to receive incoming player connections, it should invoke GameLiftServerAPI.ActivateGameSession() Console.WriteLine($"Server : OnStartGameSession() called"); GameLiftServerAPI.ActivateGameSession(); } void OnUpdateGameSession(UpdateGameSession updateGameSession) { Server.UpdateGameSession(updateGameSession.GameSession); // Do sth more for server? //When a game session is updated (e.g. by FlexMatch backfill), GameLiftsends a request to the game //server containing the updated game session object. The game server can then examine the provided //matchmakerData and handle new incoming players appropriately. //updateReason is the reason this update is being supplied. Console.WriteLine($"Server : OnUpdateGameSession() called"); } void OnProcessTerminate() { //OnProcessTerminate callback. GameLift will invoke this callback before shutting down an instance hosting this game server. //It gives this game server a chance to save its state, communicate with services, etc., before being shut down. //In this case, we simply tell GameLift we are indeed going to shutdown. Console.WriteLine($"Server : OnProcessTerminate() called"); GameLiftServerAPI.ProcessEnding(); IsAlive = false; } bool OnHealthCheck() { //This is the HealthCheck callback. //GameLift will invoke this callback every 60 seconds or so. //Here, a game server might want to check the health of dependencies and such. //Simply return true if healthy, false otherwise. //The game server has 60 seconds to respond with its health status. GameLift will default to 'false' if the game server doesn't respond in time. //In this case, we're always healthy! Console.WriteLine($"Server : OnHealthCheck() called"); return true; } void OnApplicationQuit() { //Make sure to call GameLiftServerAPI.Destroy() when the application quits. This resets the local connection with GameLift's agent. GameLiftServerAPI.Destroy(); IsAlive = false; } } } <file_sep>using System; using System.Collections.Generic; using System.Threading; using System.Net; using System.Net.Sockets; using System.Collections.Concurrent; using Aws.GameLift.Server; using Aws.GameLift.Server.Model; namespace AGLW_CSharp_BetterChatServerSample { class ChatServer { public static int MessageLength = 256; public static int SleepDuration = 100; // 100ms // A UTF-8 encoder to process byte[] <-> string conversion public readonly System.Text.Encoding Encoder = System.Text.Encoding.UTF8; public GameSession ManagedGameSession { get; private set; } = null; // TCP lisenter has it's own thread private TcpListener listener = null; private Thread listenerThread = null; private Thread senderThread = null; private Thread retrieverThread = null; private ConcurrentQueue<byte[]> messagePool = null; private event Action<byte[]> sendMsgDelegate; // private Dictionary<int, string> playerSessions; List<ConnectedClient> clientPool = null; List<ConnectedClient> clientsInQueue = null; public ChatServer(GameSession session) { ManagedGameSession = session; messagePool = new ConcurrentQueue<byte[]>(); clientPool = new List<ConnectedClient>(); clientsInQueue = new List<ConnectedClient>(); StartServer(); } internal void UpdateGameSession(GameSession gameSession) { ManagedGameSession = gameSession; } public void StartServer() { // Create a TCP listener(in a listener thread) from port when when ProcessReady() returns success LaunchListenerThread(ManagedGameSession.Port); LaunchSenderThread(); LaunchRetrieverThread(); } // A method creates thread for listener void LaunchListenerThread(int port) { listenerThread = new Thread(() => { Listen(port); }); listenerThread.Start(); Console.WriteLine($"Server : Listener thread is created and started"); } void LaunchSenderThread() { senderThread = new Thread(() => SendToAllClients()); senderThread.Start(); } void LaunchRetrieverThread() { retrieverThread = new Thread(() => RetrieveFromAllClients()); retrieverThread.Start(); } // A method listens the port. // When client connects : // 1) Send msg to client -> 2) Wait msg from client -> 3) Close then connection and break void Listen(int port) { listener = TcpListener.Create(ManagedGameSession.Port); listener.Start(); Console.WriteLine($"Server : Start listening port {port}"); while (true) { // TcpClient.AccecptTcpClient() blocks TcpClient client = listener.AcceptTcpClient(); ConnectedClient c = new ConnectedClient(client); sendMsgDelegate += c.SendMessage; c.StartClient(); clientsInQueue.Add(c); } } private void SendToAllClients() { while (true) { SleepForAWhile(); if (messagePool.Count > 0) { byte[] bytes = new byte[MessageLength]; if (messagePool.TryDequeue(out bytes)) { Console.WriteLine($"Message sent: {Encoder.GetString(bytes)}"); sendMsgDelegate(bytes); } } } } private void RetrieveFromAllClients() { while (true) { if (clientsInQueue.Count > 0) { clientPool.AddRange(clientsInQueue); clientsInQueue.Clear(); } SleepForAWhile(); List<ConnectedClient> disconnectedClients = new List<ConnectedClient>(); byte[] bytes = new byte[MessageLength]; foreach (var c in clientPool) { if (c != null && c.TargetClient.Connected) { if (c.RetrieveMessage(out bytes)) { messagePool.Enqueue(bytes); } } else { disconnectedClients.Add(c); } } // Release disconnected client object foreach (var dc in disconnectedClients) { sendMsgDelegate -= dc.SendMessage; clientPool.Remove(dc); } } } private void SleepForAWhile() { Thread.Sleep(SleepDuration); } } }
0d3e88219bb49c61825a3235596abf7e1756d218
[ "Markdown", "C#" ]
5
C#
cm-obuchi-hugo/AGLW-CSharp-BetterChatServerSample
ab4a3a86eb01e1f79981b0218cc2eb7857c300d8
0e1ca022650f5885e68609ed9f1c4498f28a65a7
refs/heads/master
<repo_name>igtss/server<file_sep>/server_v3.py from socket import * import threading class Config: host, port, sizeMessage = ("localhost", 5003, 1024) sPa, sPb = (AF_INET, SOCK_STREAM) class ControllConnection(Config): sServer = socket(Config.sPa, Config.sPb) listenFlag = 1 def __init__(self): self.sServer.bind((Config.host, Config.port)) self.sServer.listen(5) def logConnect(self, address): print "Connect recive from %s" % (address,) class DataCloset: clientList = {} def __init__(self): pass class Listen(threading.Thread): controllConnection = ControllConnection() dataManager = DataCloset() connectManager = ControllConnection() def __init__(self): threading.Thread.__init__(self) def run(self): self.standByConnect() def standByConnect(self): while self.connectManager.listenFlag: client, address = self.connectManager.sServer.accept() self.dataManager.clientList[address[1]] = client self.connectManager.logConnect(address[0]) class ControllMessage(threading.Thread): dataManager = DataCloset() connectManager = ControllConnection() def __init__(self): threading.Thread.__init__(self) def run(self): self.trafficMessage() def trafficMessage(self): while len(self.dataManager.clientList) == 0: pass client = self.dataManager.clientList.values()[0] while self.connectManager.listenFlag: message = client.recv(1024) print message client.send("OK") if(message == "exit"): connectManager.listenFlag = 0 client.send("Bye !") break Listen.start() ControllMessage.start()<file_sep>/client.py # -*- coding: utf-8 *-* """client modules""" from socket import * import threading import time import datetime class Client: host, port = ("localhost", 5053) connection = "" def __init__(self): self.connection = socket(AF_INET, SOCK_STREAM) self.connection.connect((self.host, self.port)) while True: text = input("Write: ") self.connection.send(text) data = self.connection.recv(1024) print(data) if(text == "exit"): self.connection.send("exit") break self.connection.close() client = Client() <file_sep>/server2.py # -*- coding: utf-8 *-* """server modules""" from socket import * from time import * import threading class BuildData: """build class server""" host, port, sizeMessage = ("localhost", 5053, 1024) socketServer = socket(AF_INET, SOCK_STREAM) clientList = {} keepAlive = 1 def __init__(self): self.socketServer.bind((self.host, self.port)) self.socketServer.listen(5) class ControlConnection(threading.Thread, BuildData): def __init__(self): threading.Thread.__init__(self) def run(self): self.acceptConnection() def acceptConnection(self): print("To shutdown server type \"exit\"") while BuildData.keepAlive: #print(dir(BuildData.socketServer)) client, address = BuildData.socketServer.accept() BuildData.clientList[address[1]] = client print(BuildData.clientList) def showActiveConnection(self): print(BuildData.clientList) def closeAllConnection(self): BuildData.socketServer.close() class ControlMessage(threading.Thread, BuildData): client = "" def __init__(self): threading.Thread.__init__(self) def run(self): self.trafficMessage() def trafficMessage(self): while len(BuildData.clientList) == 0: pass client = BuildData.clientList.values()[0] while True: message = client.recv(1024) print(message) if message == "exit": client.send("Bye !") BuildData.socketServer.close() break elif message == "status": print BuildData.clientList actualDate = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) textR = actualDate + "message recived: " + message client.send(textR) if __name__ == '__main__': buildData = BuildData() ControlConnection().start() ControlMessage().start() <file_sep>/test.py import time import datetime import threading import Queue import socket print dir(socket) def oblicz(x): time.sleep(x) return x*x def log(message): now = datetime.datetime.now().strftime("%H:%M:%S") print "%s %s" % (now, message) class WatekOblicz(threading.Thread): def __init__(self, id, kolejka_zadan): threading.Thread.__init__(self, name="WatekOblicz-%d" % (id,)) self.kolejka_zadan = kolejka_zadan def run(self): while True: req = self.kolejka_zadan.get() print req if req is None: break result = oblicz(req) log("%s %s -> %s" % (self.getName(), req, result)) def main(): log("Uruchamiam watek glowny") kolejka_zadan = Queue.Queue() N_liczba_watkow = 2 for i in range(N_liczba_watkow): WatekOblicz(i, kolejka_zadan).start() kolejka_zadan.put(2) kolejka_zadan.put(2) kolejka_zadan.put(2) kolejka_zadan.put(2) kolejka_zadan.put(2) for i in range(N_liczba_watkow): kolejka_zadan.put(None) log("koniec watku glownego") if __name__ == "__main__": main()<file_sep>/server.py import socket import threading import time import datetime def counterDown (value): time.sleep(value) now = datetime.datetime.now().strftime("%H:%M:%S") print "%s %s" % (now, value) class Server(threading.Thread): host = "localhost" port = 5001 def __init__ (self, value): threading.Thread.__init__(self) self.counter = value #self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.serversocket.bind((self.host, self.port)) #self.serversocket.listen(5) def run (self): print "Thread is starting" counterDown (self.counter) Server(3).start() Server(2).start() '''while True: client, addres = server.serversocket.accept() data = client.recv(1024) if data != "exit": print "Message + %s + recived" % (data,) client.send("You send message + " + data + " +") else: print "Server is down..." break server.serversocket.close()'''
21b824737297e7fe1be60207db21675c65cd331f
[ "Python" ]
5
Python
igtss/server
fc10a82409b3a350b40e0f7e265c97d6c8f4f814
39b56f1714d31c11cf742bf022f3155674358320
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class UIController : Singleton<UIController> { public Advices Advices; public Image PlayerHealth; public Image RoseHealth; public TextMeshProUGUI txt_bobabAmount; public TextMeshProUGUI txt_stateAdvice; public TextMeshProUGUI txt_timeInGame; public GameOverScreen gameoverScreen; public Image CurrentItem; public static void ChangePlayerHealth(float value) { Instance.PlayerHealth.fillAmount = value; } public static void ChangeRoseHealth(float value) { Instance.RoseHealth.fillAmount = value; } public static void ChangeStateAdvice(string advice) { Instance.txt_stateAdvice.text = "ADVICE: " + advice; } private void Update() { txt_bobabAmount.text = GameController.Instance.BaobabsCount.ToString(); txt_timeInGame.text = (Mathf.Round(Time.time * 100f) / 100f).ToString(); } public void GameOver(string reason) { if (!GameController.Instance.isGameover) { GameController.Instance.isGameover = true; gameoverScreen.gameObject.SetActive(true); string currentTime = (Mathf.Round(Time.time * 100f) / 100f).ToString(); gameoverScreen.Init(reason ,currentTime); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GravityField : Singleton<GravityField> { private float gravityForce = 0.25f; private float nextUpdateTime = 0; private float delay = 0.02f; // Update is called once per frame void Update() { if (Time.time > nextUpdateTime) { ApplyPlanetGravity(); nextUpdateTime = nextUpdateTime + delay; } } private void ApplyPlanetGravity() { Vector3 center = transform.position; float radius = 20; Collider[] hitColliders = Physics.OverlapSphere(center, radius); foreach (var collider in hitColliders) { Rigidbody rb = collider.GetComponent<Rigidbody>(); if(rb == null) continue; Vector3 direction = transform.position - collider.transform.position; rb.AddForce(gravityForce * direction); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chair : Item { public override void Grabed() { base.Grabed(); transform.localPosition = new Vector3(0.86f,-0.78f,0.24f); transform.localEulerAngles = new Vector3(-156.416f,-94.41f,-182.47f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class DomeItem : Item { // Start is called before the first frame update public override void Use(ItemHolder holder) { Vector3 center = holder.transform.parent.position; //Debug.DrawLine(center,center + transform.forward * grabRadius,Color.green,0.5f); Collider[] hitColliders = Physics.OverlapSphere(center, holder.grabRadius); foreach (var collider in hitColliders) { RoseHealth rose = collider.GetComponent<RoseHealth>(); if (rose != null) { rose.GetComponent<Rigidbody>().isKinematic = true; rb.isKinematic = true; rose.DomeRose(true); transform.forward = transform.position - GravityField.Instance.transform.position; transform.position = rose.transform.position; transform.parent = rose.transform; holder.RemoveCurrentItem(); break; } } } public virtual void Grabed() { base.Grabed(); transform.localPosition = new Vector3(0.55f,-0.46f,0.23f); transform.localEulerAngles = new Vector3(-170.45f,175.275f,177.45f); ItemHolder holder = transform.parent.GetComponent<ItemHolder>(); Vector3 center = holder.transform.parent.position; //Debug.DrawLine(center,center + transform.forward * grabRadius,Color.green,0.5f); Collider[] hitColliders = Physics.OverlapSphere(center, holder.grabRadius); foreach (var collider in hitColliders) { RoseHealth rose = collider.GetComponent<RoseHealth>(); if (rose != null) { rose.DomeRose(false); break; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AxeItem : Item { public override void Use(ItemHolder holder) { Vector3 center = holder.transform.parent.position; //Debug.DrawLine(center,center + transform.forward * grabRadius,Color.green,0.5f); Collider[] hitColliders = Physics.OverlapSphere(center, holder.grabRadius); foreach (var collider in hitColliders) { BaobabHealth baobab = collider.GetComponent<BaobabHealth>(); if (baobab != null) { AudioManager.PlaySound(AudioManager.Instance.audioData.chop); baobab.CurrentHealth -= GameController.Instance.GameDesigneData.axe_damage; break; } } } public override void Grabed() { base.Grabed(); transform.localEulerAngles = new Vector3(-90f,0,90f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class GameOverScreen : MonoBehaviour { public TextMeshProUGUI txt_loseReason; public TextMeshProUGUI txt_timeInGame; public void Init(string reason, string time) { txt_loseReason.text = reason; txt_timeInGame.text = "You held out " + time + " seconds"; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Menuplanet : MonoBehaviour { public float angles; // Update is called once per frame void Update() { transform.RotateAround(transform.position,Vector3.up,angles*Time.deltaTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShadowChacker : MonoBehaviour { public Transform lightPoint; public LayerMask layers; public bool CheckShadow() { RaycastHit raycastHit; Ray ray = new Ray(transform.position, lightPoint.position - transform.position); return Physics.Raycast(ray, out raycastHit, layers); // Debug.DrawRay(ray.origin,ray.direction,Color.yellow,Time.deltaTime); // Physics.Raycast(ray, out raycastHit,10, layers); // Debug.Log("Hited object name is " + raycastHit.collider.name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AsteroidState : StateBase { private float asteroidSpawnDelay = 1f; private float nextAsteroidSpawnTime; public override void EnterState(GameController _owner) { stateAdvice = "Avoid asteroids"; base.EnterState(_owner); } public override void UpdateState(GameController _owner) { base.UpdateState(_owner); if (Time.time > nextAsteroidSpawnTime) { _owner.SpawnAsteroid(); asteroidSpawnDelay = Random.Range(0f, 2f); nextAsteroidSpawnTime = Time.time + asteroidSpawnDelay; } } protected override void SetNewState(GameController _owner) { _owner.stateMachine.ChangeState(new NormalState()); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New sound data", menuName = "sound data", order = 51)] public class AudioData : ScriptableObject { public AudioClip explosion; public AudioClip chop; public AudioClip pickUp; public AudioClip wateringCam; public AudioClip treeDestroyed; public AudioClip throwItem; } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WateringCanItem : Item { public override void Use(ItemHolder holder) { AudioManager.PlaySound(AudioManager.Instance.audioData.wateringCam); Vector3 center = holder.transform.parent.position; //Debug.DrawLine(center,center + transform.forward * grabRadius,Color.green,0.5f); Collider[] hitColliders = Physics.OverlapSphere(center, holder.grabRadius); foreach (var collider in hitColliders) { RoseHealth rose = collider.GetComponent<RoseHealth>(); if (rose != null) { rose.HealRose(); break; } } } public override void Grabed() { base.Grabed(); transform.localPosition = new Vector3(0.12f,-0.32f,0.02f); transform.localEulerAngles = new Vector3(-184.73f,-4.4f,-197.25f); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController : MonoBehaviour { [Header("References")] public Health health; public Movement movement; public ShadowChacker shadowChacker; //TODO: Add grabers interaction here private float nextApplydamageTime = 0; private void Update() { if (shadowChacker.CheckShadow()) { DamageWarnings.Instance.playerShadow.gameObject.SetActive(true); if (nextApplydamageTime < Time.time) { health.CurrentHealth -= GameController.Instance.GameDesigneData.sh_Damage; nextApplydamageTime = Time.time + GameController.Instance.GameDesigneData.sh_delay; } } else { DamageWarnings.Instance.playerShadow.gameObject.SetActive(false); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Advice data", menuName = "Advice data", order = 51)] public class Advices : ScriptableObject { public List<string> advices = new List<string>(); public string GetRandomAdvice() { int rand = Random.Range(0, advices.Count); return advices[rand]; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoseHealth : Health { private bool canBeHealed = true; private float nextHealtTime; public bool isDomed; private void Update() { if (Time.time > nextHealtTime) { canBeHealed = true; } } public override void AditionalEffect() { float normalizedValue = currentHealth / maxHealth; UIController.ChangeRoseHealth(normalizedValue); } public void HealRose() { if (canBeHealed) { CurrentHealth += GameController.Instance.GameDesigneData.wc_heal; canBeHealed = false; nextHealtTime = Time.time + GameController.Instance.GameDesigneData.wc_heal; } else { CurrentHealth -= GameController.Instance.GameDesigneData.wc_heal; canBeHealed = false; nextHealtTime = Time.time + GameController.Instance.GameDesigneData.wc_heal; } } public void DomeRose(bool state) { isDomed = state; } public void CheckWindDamage() { if (!isDomed) { CurrentHealth -= GameController.Instance.GameDesigneData.wind_damage; DamageWarnings.Instance.roseWind.gameObject.SetActive(true); } else { DamageWarnings.Instance.roseWind.gameObject.SetActive(false); } } public void CheckDomeDamage() { if (isDomed) { CurrentHealth -= GameController.Instance.GameDesigneData.wind_damage; DamageWarnings.Instance.roseDomedNoWind.gameObject.SetActive(true); } else { DamageWarnings.Instance.roseDomedNoWind.gameObject.SetActive(false); } } public override void Die() { UIController.Instance.GameOver("Rose is out of health"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New gamedisgne data", menuName = "Game designe data", order = 51)] public class GameDesigneData : ScriptableObject { [Header("Shadow damage")] public float sh_Damage = 5f; public float sh_delay = 1f; public float wc_heal = 30f; public float axe_damage = 20; public float wind_damage = 1f; public float wind_delay = 1f; public float baobab_delay = 5f; } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using StateStuff; using UnityEngine.SceneManagement; using Random = System.Random; public class GameController : Singleton<GameController> { public int BaobabsCount = 4; public GameDesigneData GameDesigneData; [HideInInspector] public StateMachine<GameController> stateMachine; public Asteroid asteroidPrefab; public RoseHealth rose; public bool isGameover = false; public ParticleSystem wind; private void Start() { rose = FindObjectOfType<RoseHealth>(); stateMachine = new StateMachine<GameController>(this); stateMachine.ChangeState(new NormalState()); } private void Update() { stateMachine?.currentState?.UpdateState(this); if (BaobabsCount >= 15) { UIController.Instance.GameOver("Baobabs tree destroyed your planet"); } } public void SpawnAsteroid() { int rand = UnityEngine.Random.Range(1, 3); for (int i = 0; i < rand; i++) { Asteroid newAsteroid = Instantiate(asteroidPrefab); newAsteroid.Init(); } } public void Restart() { SceneManager.LoadScene(1); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class Asteroid : MonoBehaviour { public ParticleSystem destroyParticle; private float StartImpuls = 1f; private Rigidbody rb; public void Init() { rb = GetComponent<Rigidbody>(); transform.position = Random.onUnitSphere * 10f + GravityField.Instance.transform.position; Vector3 direction = (GravityField.Instance.transform.position - transform.position).normalized; rb.AddForce(direction * StartImpuls,ForceMode.Impulse); } private void OnCollisionEnter(Collision other) { if (other.collider.GetComponent<Health>()) { Debug.Log("Something with health was hited"); other.collider.GetComponent<BaobabHealth>()?.Die(); if (other.collider.GetComponent<CharacterController>() != null) { UIController.Instance.GameOver("Asteroid destroyed your hero."); } if (other.collider.GetComponent<RoseHealth>() != null) { UIController.Instance.GameOver("Asteroid destroyed rose."); } Die(); } else { Die(); } } private void Die() { AudioManager.PlaySound(AudioManager.Instance.audioData.explosion); Destroy(Instantiate(destroyParticle, transform.position, Quaternion.identity), destroyParticle.main.duration); Destroy(gameObject); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class LightOrbiting : MonoBehaviour { private float orbitingAngle = 2.25f; private Transform planet; private void Start() { planet = FindObjectOfType<GravityField>().transform; } void Update() { transform.RotateAround(planet.position,Vector3.up,orbitingAngle*Time.deltaTime); transform.LookAt(planet.position); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Movement : MonoBehaviour { public Animator animator; public float radius = 0.55f; public float translateSpeed = 180.0f; public float rotateSpeed = 360.0f; float angle = 0.0f; Vector3 direction = Vector3.one; Quaternion rotation = Quaternion.identity; public LayerMask mask; void Update() { if((Input.GetKey(KeyCode.LeftArrow)||Input.GetKey(KeyCode.RightArrow)||Input.GetKey(KeyCode.UpArrow)||Input.GetKey(KeyCode.DownArrow)) && !animator.GetBool("isRuning") ) animator.SetBool("isRuning", true); else { if(animator.GetBool("isRuning") &&(!Input.GetKey(KeyCode.LeftArrow)&&!Input.GetKey(KeyCode.RightArrow)&&!Input.GetKey(KeyCode.UpArrow)&&!Input.GetKey(KeyCode.DownArrow))) animator.SetBool("isRuning", false); } direction = new Vector3(Mathf.Sin(angle), Mathf.Cos(angle)); // Rotate with left/right arrows if (Input.GetKey(KeyCode.LeftArrow)) Rotate( rotateSpeed); if (Input.GetKey(KeyCode.RightArrow)) Rotate(-rotateSpeed); Vector3 originCenter = transform.position + transform.forward * transform.localScale.x/2; if (!Physics.Raycast(originCenter, transform.forward, 0.05f, mask)) { // Translate forward/backward with up/down arrows if (Input.GetKey(KeyCode.UpArrow)) Translate(0, translateSpeed); } Vector3 originCenterBack = transform.position - transform.forward * transform.localScale.x/2; if (!Physics.Raycast(originCenterBack, -transform.forward, 0.05f, mask)) { // Translate left/right with A/D. Bad keys but quick test. if (Input.GetKey(KeyCode.DownArrow)) Translate(0, -translateSpeed); } UpdatePositionRotation(); } void Rotate(float amount) { angle += amount * Mathf.Deg2Rad * Time.deltaTime; } void Translate(float x, float y) { var perpendicular = new Vector3(-direction.y, direction.x); var verticalRotation = Quaternion.AngleAxis(y * Time.deltaTime, perpendicular); var horizontalRotation = Quaternion.AngleAxis(x * Time.deltaTime, direction); rotation *= horizontalRotation * verticalRotation; } void UpdatePositionRotation() { transform.localPosition = rotation * Vector3.forward * radius; transform.rotation = rotation * Quaternion.LookRotation(direction, Vector3.forward); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class NormalState : StateBase { private float nextUpdateTime; public override void EnterState(GameController _owner) { stateAdvice = UIController.Instance.Advices.GetRandomAdvice(); base.EnterState(_owner); } protected override void SetNewState(GameController _owner) { int i = Random.Range(0, 2); if(i == 0) _owner.stateMachine.ChangeState(new AsteroidState() ); else { _owner.stateMachine.ChangeState(new WindState()); } } public override void UpdateState(GameController _owner) { base.UpdateState(_owner); if (Time.time > nextUpdateTime) { _owner.rose.CheckDomeDamage(); nextUpdateTime = Time.time + GameController.Instance.GameDesigneData.wind_delay; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; // Z - throw/grab item // X - use item public class ItemHolder : MonoBehaviour { public float grabRadius; public Sprite NoItem; private Item currentItem; // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Z)) { ChangeHolderHandState(); } else if (Input.GetKeyDown(KeyCode.X)) { UseItem(); } else { if (currentItem == null) { UIController.Instance.CurrentItem.sprite = NoItem; Debug.Log("Current item is null"); } else { UIController.Instance.CurrentItem.sprite = currentItem.SpriteItem; } } } private void UseItem() { if (currentItem != null) currentItem.Use(this); } private void ChangeHolderHandState() { if (currentItem == null) { Vector3 center = transform.parent.position; //Debug.DrawLine(center,center + transform.forward * grabRadius,Color.green,0.5f); Collider[] hitColliders = Physics.OverlapSphere(center, grabRadius); foreach (var collider in hitColliders) { DomeItem item = collider.GetComponent<DomeItem>(); if (item != null) { currentItem = item; UIController.Instance.CurrentItem.sprite = item.SpriteItem; currentItem.transform.parent = transform; currentItem.transform.localPosition = Vector3.zero; AudioManager.PlaySound(AudioManager.Instance.audioData.pickUp); item.Grabed(); return; } } foreach (var collider in hitColliders) { Item item = collider.GetComponent<Item>(); if (item != null) { currentItem = item; currentItem.transform.parent = transform; currentItem.transform.localPosition = Vector3.zero; AudioManager.PlaySound(AudioManager.Instance.audioData.pickUp); item.Grabed(); break; } } } else { //current item remove from hand currentItem.Throwed(transform.forward); RemoveCurrentItem(); } } public void RemoveCurrentItem() { currentItem = null; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { protected Rigidbody rb; public Sprite SpriteItem; // Start is called before the first frame update protected virtual void Start() { rb = GetComponent<Rigidbody>(); } public virtual void Use(ItemHolder holder) { } public virtual void Grabed() { rb.isKinematic = true; } public virtual void Throwed(Vector3 direction) { rb.isKinematic = false; transform.parent = null; AudioManager.PlaySound(AudioManager.Instance.audioData.throwItem); rb.AddForce(direction * 0.25f,ForceMode.Impulse); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class DamageWarnings : Singleton<DamageWarnings> { public TextMeshProUGUI playerShadow; public TextMeshProUGUI roseShadow; public TextMeshProUGUI roseWind; public TextMeshProUGUI roseDomedNoWind; public TextMeshProUGUI baobabWasSpawned; public void ShowBaobabSpawnedInfo() { StartCoroutine(BabobabShow()); } private IEnumerator BabobabShow() { baobabWasSpawned.gameObject.SetActive(true); yield return new WaitForSeconds(2f); baobabWasSpawned.gameObject.SetActive(false); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using Cinemachine; using UnityEngine; public class Health : MonoBehaviour { [SerializeField] protected float maxHealth = 100f; protected float currentHealth; public float CurrentHealth { get { return currentHealth; } set { if (value > maxHealth) currentHealth = maxHealth; else currentHealth = value; AditionalEffect(); if (currentHealth <= 0) { currentHealth = 0; Die(); } } } private void Start() { currentHealth = maxHealth; } public virtual void AditionalEffect() { float normalizedValue = currentHealth / maxHealth; UIController.ChangePlayerHealth(normalizedValue); } public virtual void Die() { UIController.Instance.GameOver("Your hero is out of health."); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using StateStuff; public abstract class StateBase : State<GameController> { protected float stateDuration; protected float changeStateTime; protected string stateAdvice; public override void EnterState(GameController _owner) { stateDuration = Random.Range(20f,30f); changeStateTime = Time.time + stateDuration; UIController.ChangeStateAdvice(stateAdvice); } public override void ExitState(GameController _owner) { } public override void UpdateState(GameController _owner) { if(Time.time > changeStateTime) SetNewState(_owner); } protected virtual void SetNewState(GameController _owner) { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BaobabHealth : Health { public ParticleSystem destroyParticle; public override void AditionalEffect() { Debug.Log("Baobab health:" + currentHealth); } public override void Die() { //TODO: Spawn player heal with 10% chance GameController.Instance.BaobabsCount--; AudioManager.PlaySound(AudioManager.Instance.audioData.treeDestroyed); Destroy(Instantiate(destroyParticle, transform.position, Quaternion.identity), destroyParticle.main.duration); Destroy(gameObject); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BaobabSpawner : MonoBehaviour { public BaobabHealth BaobabPrefab; private CharacterController player; private float nextSpawnTime; private void Start() { nextSpawnTime = Time.time + GameController.Instance.GameDesigneData.baobab_delay; player = FindObjectOfType<CharacterController>(); } private void Update() { //if(Input.GetKeyDown(KeyCode.Space)) if (Time.time > nextSpawnTime) { BaobabHealth newBaobab = Instantiate(BaobabPrefab); newBaobab.transform.parent = GravityField.Instance.transform; newBaobab.transform.localPosition = -player.transform.localPosition; newBaobab.transform.up = newBaobab.transform.position - GravityField.Instance.transform.position; newBaobab.transform.localPosition -= newBaobab.transform.up * 0.01f; newBaobab.transform.localScale = Vector3.one * 0.101f; DamageWarnings.Instance.ShowBaobabSpawnedInfo(); nextSpawnTime = Time.time + GameController.Instance.GameDesigneData.baobab_delay; GameController.Instance.BaobabsCount++; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Wind : MonoBehaviour { public bool isWindActive = true; private RoseHealth rose; private float nextUpdateTime; private void Start() { rose = FindObjectOfType<RoseHealth>(); } void Update() { if (isWindActive) { if (Time.time > nextUpdateTime) { rose.CheckWindDamage(); nextUpdateTime = Time.time + GameController.Instance.GameDesigneData.wind_delay; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioManager : Singleton<AudioManager> { public AudioSource soundSource; public AudioSource windAudioSource; public AudioData audioData; public static void PlaySound(AudioClip sound) { Instance.soundSource.PlayOneShot(sound); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class WindState : StateBase { private float nextUpdateTime; public override void EnterState(GameController _owner) { stateAdvice = UIController.Instance.Advices.GetRandomAdvice(); _owner.wind.gameObject.SetActive(true); AudioManager.Instance.windAudioSource.gameObject.SetActive(true); base.EnterState(_owner); } public override void UpdateState(GameController _owner) { base.UpdateState(_owner); if (Time.time > nextUpdateTime) { _owner.rose.CheckWindDamage(); nextUpdateTime = Time.time + GameController.Instance.GameDesigneData.wind_delay; } } public override void ExitState(GameController _owner) { base.ExitState(_owner); _owner.wind.gameObject.SetActive(false); AudioManager.Instance.windAudioSource.gameObject.SetActive(false); } protected override void SetNewState(GameController _owner) { _owner.stateMachine.ChangeState(new NormalState()); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class RoseItem : Item { [Header("References")] public Health health; public ShadowChacker shadowChacker; //TODO: Add grabers interaction here private float nextApplydamageTime = 0; private void Update() { if (shadowChacker.CheckShadow()) { DamageWarnings.Instance.roseShadow.gameObject.SetActive(true); if (nextApplydamageTime < Time.time) { health.CurrentHealth -= GameController.Instance.GameDesigneData.sh_Damage; nextApplydamageTime = Time.time + GameController.Instance.GameDesigneData.sh_delay; } } else { DamageWarnings.Instance.roseShadow.gameObject.SetActive(false); } } public override void Use(ItemHolder holder) { transform.parent = null; rb.isKinematic = false; holder.RemoveCurrentItem(); transform.up = transform.position - GravityField.Instance.transform.position; } public override void Grabed() { base.Grabed(); transform.localEulerAngles = new Vector3(90f,0,0f); } }
7633fa6691c2b070a28290a55f364fb78c207ea8
[ "C#" ]
31
C#
fomich486/LudumDare46
3b2ef4ca03f687a9b858a4b92e0297ee4997a1bd
0cd2f37ab8a0d407ced3ba16530ad85103e38a2b
refs/heads/master
<repo_name>gagner2/deepQ<file_sep>/translator/__init__.py """Makes helper libraries available in the translate package.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.models.rnn.translate import data_utils from tensorflow.models.rnn.translate import seq2seq_model<file_sep>/github_upload.py import gym gym.upload('/home/gagner2/gym/training', api_key='<KEY>')<file_sep>/deepQworking3.py # Deep Q network import gym import numpy as np import tensorflow as tf import math import random # HYPERPARMETERS H = 200 H2 = 200 batch_number = 500 gamma = 0.99 num_between_q_copies = 150 explore_decay = 0.9995 min_explore = 0.01 max_steps = 199 max_episodes = 1000 memory_size = 100000 learning_rate = 0.01 if __name__ == '__main__': env = gym.make('CartPole-v0') env.monitor.start('training', force=True) #Setup tensorflow tf.reset_default_graph() #First Q Network w1 = tf.Variable(tf.random_uniform([env.observation_space.shape[0],H], -1.0, 1.0)) b1 = tf.Variable(tf.random_uniform([H], -1.0, 1.0)) w2 = tf.Variable(tf.random_uniform([H, H2], -1.0, 1.0)) b2 = tf.Variable(tf.random_uniform([H2], -1.0, 1.0)) w3 = tf.Variable(tf.random_uniform([H2, env.action_space.n], -1.0, 1.0)) b3 = tf.Variable(tf.random_uniform([env.action_space.n], -1.0, 1.0)) #Second Q Network w1_ = tf.Variable(tf.random_uniform([env.observation_space.shape[0],H], -1.0, 1.0)) b1_ = tf.Variable(tf.random_uniform([H], -1.0, 1.0)) w2_ = tf.Variable(tf.random_uniform([H,H2], -1.0, 1.0)) b2_ = tf.Variable(tf.random_uniform([H2], -1.0, 1.0)) w3_ = tf.Variable(tf.random_uniform([H2, env.action_space.n], -1.0, 1.0)) b3_ = tf.Variable(tf.random_uniform([env.action_space.n], -1.0, 1.0)) #Make assign functions for updating Q prime's weights w1_update= w1_.assign(w1) b1_update= b1_.assign(b1) w2_update= w2_.assign(w2) b2_update= b2_.assign(b2) w3_update= w3_.assign(w3) b3_update= b3_.assign(b3) all_assigns = [ w1_update, w2_update, w3_update, b1_update, b2_update, b3_update] #build network states_ = tf.placeholder(tf.float32, [None, env.observation_space.shape[0]]) h_1 = tf.nn.relu(tf.matmul(states_, w1) + b1) h_2 = tf.nn.relu(tf.matmul(h_1, w2) + b2) h_2 = tf.nn.dropout(h_2, .5) Q = tf.matmul(h_2, w3) + b3 h_1_ = tf.nn.relu(tf.matmul(states_, w1_) + b1_) h_2_ = tf.nn.relu(tf.matmul(h_1_, w2_) + b2_) h_2_ = tf.nn.dropout(h_2_, .5) Q_ = tf.matmul(h_2_, w3_) + b3_ action_used = tf.placeholder(tf.int32, [None], name="action_masks") action_masks = tf.one_hot(action_used, env.action_space.n) filtered_Q = tf.reduce_sum(tf.mul(Q, action_masks), reduction_indices=1) #Train Q target_q = tf.placeholder(tf.float32, [None, ]) loss = tf.reduce_mean(tf.square(filtered_Q - target_q)) train = tf.train.AdamOptimizer(learning_rate).minimize(loss) #Set up the environment D = [] explore = 1.0 rewardList = [] past_actions = [] episode_number = 0 episode_reward = 0 reward_sum = 0 init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) sess.run(all_assigns) ticks = 0 for episode in xrange(max_episodes): state = env.reset() reward_sum = 0 for step in xrange(max_steps): ticks += 1 if episode % 10 == 0: q, qp = sess.run([Q,Q_], feed_dict={states_: np.array([state])}) #print "Q:{}, Q_ {}".format(q[0], qp[0]) env.render() if explore > random.random(): action = env.action_space.sample() else: q = sess.run(Q, feed_dict={states_: np.array([state])})[0] action = np.argmax(q) explore = max(explore * explore_decay, min_explore) new_state, reward, done, _ = env.step(action) reward_sum += reward D.append([state, action, reward, new_state, done]) if len(D) > memory_size: D.pop(0); state = new_state if done: break #Training a Batch samples = random.sample(D, min(batch_number, len(D))) #calculate all next Q's together new_states = [ x[3] for x in samples] all_q = sess.run(Q_, feed_dict={states_: new_states}) y_ = [] state_samples = [] actions = [] terminalcount = 0 for ind, i_sample in enumerate(samples): state_mem, curr_action, reward, new_state, done = i_sample if done: y_.append(reward) terminalcount += 1 else: this_q = all_q[ind] maxq = max(this_q) y_.append(reward + (gamma * maxq)) state_samples.append(state_mem) actions.append(curr_action); sess.run([train], feed_dict={states_: state_samples, target_q: y_, action_used: actions}) if ticks % num_between_q_copies == 0: sess.run(all_assigns) if reward_sum >= 190: print 'Reward for episode %d is %d. Explore is %.4f' %(episode,reward_sum, explore) else: print 'Episode %d' %(episode) env.monitor.close()<file_sep>/deepQworking.py import numpy as np import gym import tensorflow as tf # %% environment setting env = gym.make('MountainCar-v0') # Action Space A : discrete(3) # 0 : decelerate # 1 : coast # 2 : accelerate A = env.action_space O = env.observation_space # Hyper parameters num_tilings = 10 num_tiling_width = 9 num_actions = A.n lambda_ = 0.9 alpha = 0.005 # 0.05 / num_tilings epsilon_b = 0 # behaviour policy epsilon greedy epsilon_t = 0 # target policy epsilon greedy gamma_ = 0.999 # 0.999 # %% tile_coding def tiling_init(): ''' initialize tiling condition return tile_shape, tilings_offset ''' tile_shape = (O.high - O.low) / (num_tiling_width - 1) tilings_offset = np.zeros([num_tilings, 2]) for i in range(num_tilings): tile_offset_x = np.random.uniform(0, tile_shape[0]) tile_offset_y = np.random.uniform(0, tile_shape[1]) tilings_offset[i] = [tile_offset_x, tile_offset_y] return tile_shape, tilings_offset def s2f(state_, tile_shape_, tilings_offset_, action_=0): ''' state to features consider it as feature function phi(s) return rank 1 tensor(vector) ''' pos = state_ - O.low f = np.zeros([num_tilings, num_tiling_width * num_tiling_width]) f_pair = np.zeros([num_tilings, num_tiling_width * num_tiling_width, num_actions]) for i_tiling in range(num_tilings): temp = np.zeros([num_tiling_width, num_tiling_width]) pos_ = pos - tilings_offset_[i_tiling] x_i = 1 + pos_[0] // tile_shape_[0] y_i = 1 + pos_[1] // tile_shape_[1] temp[int(x_i)][int(y_i)] = 1 f[i_tiling, :] = np.reshape( temp, num_tiling_width * num_tiling_width) f_pair[i_tiling, :, action_] = np.reshape( temp, num_tiling_width * num_tiling_width) f = np.reshape(f, [num_tilings * num_tiling_width * num_tiling_width]) f_pair = np.reshape( f_pair, [num_tilings * num_tiling_width * num_tiling_width, num_actions]) return f, f_pair def sa2f(state_, tile_shape_, tilings_offset_, action_): ''' (state, action) pair to features consider it as feature function phi(s,a) but return rank 2 tensor(matrix) : (features, action), not rank 1 tensor(vector) ''' pos = state_ - O.low f = np.zeros([num_tilings, num_tiling_width * num_tiling_width, num_actions]) for i_tiling in range(num_tilings): temp = np.zeros([num_tiling_width, num_tiling_width]) pos_ = pos - tilings_offset_[i_tiling] x_i = 1 + pos_[0] // tile_shape_[0] y_i = 1 + pos_[1] // tile_shape_[1] temp[int(x_i)][int(y_i)] = 1 f[i_tiling, :, action_] = np.reshape( temp, num_tiling_width * num_tiling_width) return np.reshape(f, [num_tilings * num_tiling_width * num_tiling_width, num_actions]) def f2sa(f_, tile_shape_, tilings_offset_): ''' features to original (state, action) pair ''' f = np.reshape(f_, [num_tilings, num_tiling_width, num_tiling_width, num_actions]) temp = f[:, :, :, :] where_one = np.argwhere(temp == 1) print(where_one) s = [0, 0] n = 0 for i_tiling, x, y, a in where_one: x_ = (x - 1 / 2) * tile_shape_[0] y_ = (y - 1 / 2) * tile_shape_[1] s += [x_, y_] + tilings_offset_[i_tiling] + O.low n += 1 return s / n # %% functions def epsilon_greedy(a, b, rand_): if rand_ < epsilon_b: return a else: return b # In[]: tensorflow graph # observation : (1d-position, velocity) observation = env.reset() graph = tf.Graph() num_component = num_tilings * num_tiling_width * num_tiling_width with graph.as_default(): # S(t) input_feature_t = tf.placeholder( tf.float32, shape=[num_component], name='feature_t') feature_pair = tf.placeholder( tf.float32, shape=[num_component, num_actions], name='feature_pair') # S(t+1) input_feature_t_next = tf.placeholder( tf.float32, shape=[num_component], name='feature_t_next') # a(t) input_action = tf.placeholder(tf.int64, shape=[], name='random_action') # r(t+1) input_reward = tf.placeholder(tf.float32, shape=[], name='reward') # theta weights = tf.Variable(tf.random_uniform( shape=[num_component, num_actions], minval=-0.01, maxval=0.0), name='theta') tf.histogram_summary('weights', weights) # eligibility trace vector e(t) eligibility = tf.Variable( tf.zeros(shape=[num_component, num_actions]), name='eligibility') tf.histogram_summary('eligibility', eligibility) # estimated Q-value with tf.name_scope(name='Greedy_Policy'): f_t = tf.reshape(input_feature_t, shape=[1, num_component]) q_t = tf.reshape(tf.matmul(f_t, weights), shape=[num_actions]) # action A(t) a = tf.argmax(q_t, 0, name='ArgMax_Q') with tf.name_scope(name='Compute_Q'): f_next = tf.reshape(input_feature_t_next, shape=[ 1, num_component], name='f_t') q_next = tf.reshape(tf.matmul(f_next, weights), shape=[num_actions], name='q_t') with tf.name_scope(name='delta'): delta = input_reward + gamma_ * \ tf.gather(q_next, tf.argmax(q_next, 0), name='Q_next') - \ tf.gather(q_t, input_action, name='Q_t') with tf.name_scope(name='delta_done'): delta_done = input_reward - tf.gather(q_t, input_action, name='Q_t') with tf.name_scope(name='update_eligibility'): eligibility = tf.assign(eligibility, tf.maximum( lambda_ * gamma_ * eligibility, feature_pair), name='eligibility') with tf.name_scope(name='theta_update'): optimizer = tf.assign_add( weights, alpha * delta * eligibility, name='update_theta') with tf.name_scope(name='theta_done'): optimizer_done = tf.assign_add( weights, alpha * delta_done * eligibility, name='done_theta') saver = tf.train.Saver() merged = tf.merge_all_summaries() # In[]: Session for episodes summaries_dir = './summaries/train' num_episodes = 2000 ts, to = tiling_init() outdir = '/tmp/MountainCar-v0-expr-1' with tf.Session(graph=graph) as session: if tf.gfile.Exists(summaries_dir): print("delete summary") tf.gfile.DeleteRecursively(summaries_dir) tf.gfile.MakeDirs(summaries_dir) train_writer = tf.train.SummaryWriter(summaries_dir, session.graph) tf.initialize_all_variables().run() env.monitor.start(outdir, force=True) for i_episode in range(num_episodes): done = False t = 0 observation = env.reset() tf.initialize_variables([tf.all_variables()[1]]).run() print("start Episodes : ", i_episode) for t in range(400): action = A.sample() f, _ = s2f(observation, ts, to) feed_dict = {input_feature_t: f, input_action: action} action = session.run(a, feed_dict=feed_dict) _, f_pair = s2f(observation, ts, to, action) observation, reward, done, _ = env.step(action) f_, _ = s2f(observation, ts, to, action) feed_dict = {input_feature_t: f, input_feature_t_next: f_, feature_pair: f_pair, input_reward: reward, input_action: action} if done: _ = session.run(optimizer_done, feed_dict=feed_dict) print("Episode finished after {} timesteps".format(t + 1)) break _ = session.run(optimizer, feed_dict=feed_dict) summary = session.run(merged, feed_dict={}) train_writer.add_summary(summary, i_episode) save_path = saver.save(session, "./checkpoint/model.ckpt") print("Model saved in file: %s" % save_path) env.monitor.close()
ebda948181e4e3e6256226d81802e1e68eee2ffb
[ "Python" ]
4
Python
gagner2/deepQ
f7d0026c59da0d80b33650a23040452089aa49b0
613175963df22d87e279450f45c75a78f3a229db
refs/heads/master
<file_sep>#include <stdio.h> #include <vector> #include <random> #include <assert.h> #include <time.h> #include <GLFW\glfw3.h> #include "linmath.h" #include <stdlib.h> #define SCREEN_STRIDE 2 #define SCREEN_MIN -1 #define SCREEN_MAX 1 #define GAME_BOARD_STRIDE 1 #define PADDLE_WIDTH 0.03 #define PADDLE_HEIGHT_IN_WINDOW 0.4 #define BOARD_HEIGHT 1 #define BOARD_WIDTH 1 #define PADDLE_HEIGHT 0.2 #define AI_PADDLE_SPEED 0.02 #define RL_AI_PADDLE_SPEED 0.04 #define HI_RANDOM_VELOCITY_X 0.015 #define LO_RANDOM_VELOCITY_X -0.015 #define HI_RANDOM_VELOCITY_Y 0.03 #define LO_RANDOM_VELOCITY_Y -0.03 #define BALL_SPEED_LIMIT 0.04 #define BOARD_DISCRETIZATION_X 12 #define BOARD_DISCRETIZATION_Y 12 #define NUM_PADDLE_POS 12 #define EPSILON 0.2 #define GAMMA 0.9 #define LEARNING_RATE_CONST 200 #define TRAIN_TRIALS 1000 enum ACTION { STAY, UP, DOWN, NUM_ACTION }; enum BOUNCE_TYPE { NO_BOUNCE, OFF_WALL, OFF_LPADDLE, OFF_RPADDLE, AI_WIN, RL_AI_WIN, NUM_BOUNCE_TYPE }; //RL_AI on the right side of board enum PLAYER_TYPE { RL_AI, AI, TRAINER_AI, NUM_AI }; enum rlBallVelocityX { BALL_HEADING_RIGHT, BALL_HEADING_LEFT, NUM_BALL_VELOCITY_X }; enum rlBallVelocityY { BALL_HEADING_UP, BALL_HEADING_DOWN, BALL_HEADING_HORIZONTAL, NUM_BALL_VELOCITY_Y }; enum RlMode { TRAINING, PLAYING, NUM_RL_MODE }; //struct BallState //{ // float posX; // float posY; // float velocityX; // float velocityY; //}; struct WorldState { int ballPosX; int ballPosY; int ballVelocityX; int ballVelocityY; int paddlePosY; }; struct WorldStatus { float ballPosX; float ballPosY; float ballVelocityX; float ballVelocityY; float paddlePosY; void initialize() { ballPosX = 0; ballPosY = 0; ballVelocityX = 0; ballVelocityY = 0; paddlePosY = 0; } bool empty() { return (ballPosX == 0 && ballPosY == 0 && ballVelocityX == 0 && ballVelocityY == 0 && paddlePosY == 0); } void operator= (const WorldStatus& worldStatus) { ballPosX = worldStatus.ballPosX; ballPosY = worldStatus.ballPosY; ballVelocityX = worldStatus.ballVelocityX; ballVelocityY = worldStatus.ballVelocityY; paddlePosY = worldStatus.paddlePosY; } }; class Paddle { private: float epsion; // epsilon percent of chance to choose random action in training float gamma; // discount factor for each new utility at state S' WorldStatus oldWorldStatus; // used for training. Stores world status of previous time frame ACTION oldAction; //// used for training. Stores the action taken in previous time frame public: PLAYER_TYPE playerType; bool isTraining; //set this flag to train float posX; float posY; float****** Q; // utility table int ****** N; // num of action taken under certain state (a table) void reset() { posY = 0.5 - (PADDLE_HEIGHT / 2) ; } Paddle(float XPos, PLAYER_TYPE newPlayerType) : playerType(newPlayerType), posX(XPos), posY(0.5 - (PADDLE_HEIGHT / 2)), gamma(GAMMA), isTraining(false) { srand(time(NULL)); epsion = EPSILON; oldWorldStatus.initialize(); //allocate memory for Q and N Q = (float******)malloc(BOARD_DISCRETIZATION_X*sizeof(float*****)); N = (int******)malloc(BOARD_DISCRETIZATION_X * sizeof(int*****)); if (!Q) { printf("out of memory Q\n"); exit(EXIT_FAILURE); } if (!N) { printf("out of memory N\n"); exit(EXIT_FAILURE); } for (int ballX = 0; ballX < BOARD_DISCRETIZATION_X; ballX++) { Q[ballX] = (float*****)malloc(BOARD_DISCRETIZATION_Y * sizeof(float****)); N[ballX] = (int *****)malloc(BOARD_DISCRETIZATION_Y * sizeof(int ****)); if (!Q[ballX]) { printf("out of memory Q[%d]\n", ballX); exit(EXIT_FAILURE); } if (!N[ballX]) { printf("out of memory N[%d]\n", ballX); exit(EXIT_FAILURE); } for (int ballY = 0; ballY < BOARD_DISCRETIZATION_Y; ballY++) { Q[ballX][ballY] = (float****)malloc(NUM_BALL_VELOCITY_X * sizeof(float***)); N[ballX][ballY] = (int ****)malloc(NUM_BALL_VELOCITY_X * sizeof(int ***)); if (!Q[ballX][ballY]) { printf("out of memory Q[%d][%d]\n", ballX, ballY); exit(EXIT_FAILURE); } if (!N[ballX][ballY]) { printf("out of memory N[%d][%d]\n", ballX, ballY); exit(EXIT_FAILURE); } for (int ballVelocityX = 0; ballVelocityX < NUM_BALL_VELOCITY_X; ballVelocityX++) { Q[ballX][ballY][ballVelocityX] = (float***)malloc(NUM_BALL_VELOCITY_Y * sizeof(float**)); N[ballX][ballY][ballVelocityX] = (int ***)malloc(NUM_BALL_VELOCITY_Y * sizeof(int **)); if (!Q[ballX][ballY][ballVelocityX]) { printf("out of memory Q[%d][%d][%d]\n", ballX, ballY, ballVelocityX); exit(EXIT_FAILURE); } if (!N[ballX][ballY][ballVelocityX]) { printf("out of memory N[%d][%d][%d]\n", ballX, ballY, ballVelocityX); exit(EXIT_FAILURE); } for (int ballVelocityY = 0; ballVelocityY < NUM_BALL_VELOCITY_Y; ballVelocityY++) { Q[ballX][ballY][ballVelocityX][ballVelocityY] = (float**)malloc(NUM_PADDLE_POS * sizeof(float*)); N[ballX][ballY][ballVelocityX][ballVelocityY] = (int **)malloc(NUM_PADDLE_POS * sizeof(int *)); if (!Q[ballX][ballY][ballVelocityX][ballVelocityY]) { printf("out of memory Q[%d][%d][%d][%d]\n", ballX, ballY, ballVelocityX, ballVelocityY); exit(EXIT_FAILURE); } if (!N[ballX][ballY][ballVelocityX][ballVelocityY]) { printf("out of memory N[%d][%d][%d][%d]\n", ballX, ballY, ballVelocityX, ballVelocityY); exit(EXIT_FAILURE); } for (int paddlePos = 0; paddlePos < NUM_PADDLE_POS; paddlePos++) { Q[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos] = (float*)malloc(NUM_ACTION * sizeof(float)); N[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos] = (int *)malloc(NUM_ACTION * sizeof(int)); if (!Q[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos]) { printf("out of memory Q[%d][%d][%d][%d][%d]\n", ballX, ballY, ballVelocityX, ballVelocityY, paddlePos); exit(EXIT_FAILURE); } if (!N[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos]) { printf("out of memory N[%d][%d][%d][%d][%d]\n", ballX, ballY, ballVelocityX, ballVelocityY, paddlePos); exit(EXIT_FAILURE); } } } } } } //zero memory for Q and N for (int ballX = 0; ballX < BOARD_DISCRETIZATION_X; ballX++) { for (int ballY = 0; ballY < BOARD_DISCRETIZATION_Y; ballY++) { for (int ballVelocityX = 0; ballVelocityX < int(NUM_BALL_VELOCITY_X); ballVelocityX++) { for (int ballVelocityY = 0; ballVelocityY < int(NUM_BALL_VELOCITY_Y); ballVelocityY++) { for (int paddlePos = 0; paddlePos < NUM_PADDLE_POS; paddlePos++) { for (int action = 0; action < (NUM_ACTION); action++) { Q[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos][action] = 0; N[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos][action] = 0; } } } } } } ////zero memory for Q and N //for (int ballX = 0; ballX < 12; ballX++) //{ // for (int ballY = 0; ballY < 12; ballY++) // { // for (int ballVelocityX = 0; ballVelocityX < 2; ballVelocityX++) // { // for (int ballVelocityY = 0; ballVelocityY < 3; ballVelocityY++) // { // for (int paddlePos = 0; paddlePos < 12; paddlePos++) // { // for (int action = 0; action < 3; action++) // { // Q[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos][action] = 0; // N[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos][action] = 0; // } // } // } // } // } //} } ~Paddle() { for (int ballX = 0; ballX < BOARD_DISCRETIZATION_X; ballX++) { for (int ballY = 0; ballY < BOARD_DISCRETIZATION_Y; ballY++) { for (int ballVelocityX = 0; ballVelocityX < NUM_BALL_VELOCITY_X; ballVelocityX++) { for (int ballVelocityY = 0; ballVelocityY < NUM_BALL_VELOCITY_Y; ballVelocityY++) { for (int paddlePos = 0; paddlePos < NUM_PADDLE_POS; paddlePos++) { free(Q[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos]); free(N[ballX][ballY][ballVelocityX][ballVelocityY][paddlePos]); } free(Q[ballX][ballY][ballVelocityX][ballVelocityY]); free(N[ballX][ballY][ballVelocityX][ballVelocityY]); } free(Q[ballX][ballY][ballVelocityX]); free(N[ballX][ballY][ballVelocityX]); } free(Q[ballX][ballY]); free(N[ballX][ballY]); } free(Q[ballX]); free(N[ballX]); } free(Q); free(N); } inline int ballPosXState(float x) { int state = int(x / (float(BOARD_WIDTH) / float(BOARD_DISCRETIZATION_X))); if (state >= BOARD_DISCRETIZATION_X) { state = BOARD_DISCRETIZATION_X - 1; } return state; } inline int ballPosYState(float y) { int state = int(y / (float(BOARD_WIDTH) / float(BOARD_DISCRETIZATION_Y))); if (state >= BOARD_DISCRETIZATION_Y) { state = BOARD_DISCRETIZATION_Y - 1; } return state; } inline int ballVelXState(float x) { //should have been (x < 0) ? -1 : 1 //but returned value is used to access array. -1 and 1 need to be mapped to 0 and 1 return ((x < 0) ? 0 : 1); } inline int ballVelYState(float x) { //should have been (x < 0) ? -1 : ((x > 0) ? 1 : 0 //but returned value is used to access array. -1, 0 and 1 need to be mapped to 0, 1 and 2 return ((x < 0) ? 0 : ((x > 0) ? 2 : 1)); } inline int paddlePosState(float y) { int state = int(y / (float(BOARD_WIDTH) / float(BOARD_DISCRETIZATION_Y))); if (state >= BOARD_DISCRETIZATION_Y) { state = BOARD_DISCRETIZATION_Y - 1; } return state; } inline float getUtility(WorldStatus* worldStatus, ACTION action) { WorldState worldState = { ballPosXState(worldStatus->ballPosX), ballPosYState(worldStatus->ballPosY), ballVelXState(worldStatus->ballVelocityX), ballVelYState(worldStatus->ballVelocityY), paddlePosState(worldStatus->paddlePosY) }; return Q[ballPosXState(worldStatus->ballPosX)] [ballPosYState(worldStatus->ballPosY)] [ballVelXState(worldStatus->ballVelocityX)] [ballVelYState(worldStatus->ballVelocityY)] [paddlePosState(worldStatus->paddlePosY)] [int(action)]; } inline float getStateActionCount(WorldStatus* worldStatus, ACTION action) { return N[ballPosXState(worldStatus->ballPosX)] [ballPosYState(worldStatus->ballPosY)] [ballVelXState(worldStatus->ballVelocityX)] [ballVelYState(worldStatus->ballVelocityY)] [paddlePosState(worldStatus->paddlePosY)] [int(action)]; } inline void incrementStateActionCount(WorldStatus* worldStatus, ACTION action) { N[ballPosXState(worldStatus->ballPosX)] [ballPosYState(worldStatus->ballPosY)] [ballVelXState(worldStatus->ballVelocityX)] [ballVelYState(worldStatus->ballVelocityY)] [paddlePosState(worldStatus->paddlePosY)] [int(action)]++; } void makeMove(WorldStatus* worldStatus) { if (playerType == TRAINER_AI) { posY = worldStatus->ballPosY - (PADDLE_HEIGHT / 2); } else if (playerType == AI) { if (posY + (PADDLE_HEIGHT / 2) > worldStatus->ballPosY) { move(UP, AI_PADDLE_SPEED); } else if (posY + (PADDLE_HEIGHT / 2) < worldStatus->ballPosY) { move(DOWN, AI_PADDLE_SPEED); } else { move(STAY, AI_PADDLE_SPEED); } } else if(playerType == RL_AI) { if (!isTraining) { ACTION newAction; newAction = rlChooseAction(worldStatus, PLAYING); move(newAction, RL_AI_PADDLE_SPEED); } else { ACTION newAction; //new action is the actual action taken, may be a random action depending on exploration policy. This action is used as the oldAction for training in the next time frame newAction = rlChooseAction(worldStatus, TRAINING); // we have record of old world status, can train using this new world status. oldWorldStatus is empty in the very first iteration if (!oldWorldStatus.empty()) { rlLearn(worldStatus); } move(newAction, RL_AI_PADDLE_SPEED); incrementStateActionCount(worldStatus, newAction); oldAction = newAction; oldWorldStatus = *worldStatus; } } } float getReward(WorldStatus* worldStatus) { float newBallPosX = worldStatus->ballPosX + worldStatus->ballVelocityX; float newBallPosY = worldStatus->ballPosY + worldStatus->ballVelocityY; if (newBallPosX > 1) { if ((newBallPosY >= posY) && (newBallPosY <= (posY + PADDLE_HEIGHT))) { return 1; } else { return -1; } } else { return 0; } } //happens when we are in state S' already. void rlLearn(WorldStatus* newWorldStatus) { float reward = getReward(&oldWorldStatus); // use max-utility action as Q(s',a') to train ACTION knownBestAction = rlChooseAction(newWorldStatus, PLAYING); float newQ = getUtility(newWorldStatus, knownBestAction); //Q(s',a') float oldQ = getUtility(&oldWorldStatus, oldAction); //Q(s,a) float alpha = LEARNING_RATE_CONST/(LEARNING_RATE_CONST + getStateActionCount(&oldWorldStatus,oldAction)); // learning rate factor. Changes during the training Q[ballPosXState(oldWorldStatus.ballPosX)] [ballPosYState(oldWorldStatus.ballPosY)] [ballVelXState(oldWorldStatus.ballVelocityX)] [ballVelYState(oldWorldStatus.ballVelocityY)] [paddlePosState(oldWorldStatus.paddlePosY)] [int(oldAction)] = oldQ + alpha * (reward + gamma * newQ - oldQ); } ACTION rlChooseAction(WorldStatus* worldStatus, RlMode rlMode) { ACTION action; if (rlMode == TRAINING) { // epsilon percent of chance to choose random action float randomNum = (float)rand() / (float)RAND_MAX; if (randomNum < epsion) { action = (ACTION)(rand() % 3); } else { action = rlMaxAction(worldStatus); } return action; } else { return rlMaxAction(worldStatus); } } ACTION rlMaxAction(WorldStatus* worldStatus) { ACTION maxAction = STAY; float maxUtility = -9999; for (int action = 0; action < NUM_ACTION; action++) { if (getUtility(worldStatus, ACTION(action)) > maxUtility) { maxAction = (ACTION)action; maxUtility = getUtility(worldStatus, ACTION(action)); } } return maxAction; } private: void move(ACTION action, float velocity) { switch (action) { case(UP): { posY -= velocity; if (posY < 0) { posY = 0; } break; } case(DOWN): { posY += velocity; if (posY >(1 - PADDLE_HEIGHT)) { posY = 1 - PADDLE_HEIGHT; } break; } default: return; } } }; class Ball { public: float posX; float posY; float velocityX; float velocityY; Paddle* paddleL; Paddle* paddleR; Ball(Paddle* new_paddleL, Paddle* new_paddleR) { posX = 0.5; posY = 0.5; velocityX = 0.03; velocityY = 0.01; paddleL = new_paddleL; paddleR = new_paddleR; } void reset() { posX = 0.5; posY = 0.5; velocityX = 0.03; velocityY = 0.01; } BOUNCE_TYPE move() { // if bounced both on wall and paddle in same time frame, OFF_WALL is ignored. bool bouncedOnWall = 0; posY += velocityY; if (posY < 0) { posY = -posY; velocityY = -velocityY; bouncedOnWall = true; } else if (posY > 1) { posY = 2 - posY; velocityY = -velocityY; bouncedOnWall = true; } posX += velocityX; // ball reaches left end if (posX < 0) { if ((posY >= paddleL->posY) && (posY <= (paddleL->posY + PADDLE_HEIGHT))) { posX = -posX; float velocityVariationX = LO_RANDOM_VELOCITY_X + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI_RANDOM_VELOCITY_X - LO_RANDOM_VELOCITY_X))); float velocityVariationY = LO_RANDOM_VELOCITY_Y + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI_RANDOM_VELOCITY_Y - LO_RANDOM_VELOCITY_Y))); velocityX = -velocityX + velocityVariationX; assert(velocityX >= 0); // if ball is moving too slow on X axis if (velocityX < HI_RANDOM_VELOCITY_X) { velocityX = HI_RANDOM_VELOCITY_X; } // if ball is moving too fast on X axis else if (velocityX > BALL_SPEED_LIMIT) { velocityX = BALL_SPEED_LIMIT; } velocityY = velocityY + velocityVariationY; // if ball is moving too fast on Y axis if (velocityY > BALL_SPEED_LIMIT || velocityY < -BALL_SPEED_LIMIT) { if (velocityY > 0) { velocityY = BALL_SPEED_LIMIT; } else { velocityY = -BALL_SPEED_LIMIT; } } return OFF_LPADDLE; } else { return RL_AI_WIN; } } // ball reaches right end if (posX > 1) { if ((posY >= paddleR->posY) && (posY <= (paddleR->posY + PADDLE_HEIGHT))) { posX = 2 - posX; float velocityVariationX = LO_RANDOM_VELOCITY_X + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI_RANDOM_VELOCITY_X - LO_RANDOM_VELOCITY_X))); float velocityVariationY = LO_RANDOM_VELOCITY_Y + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (HI_RANDOM_VELOCITY_Y - LO_RANDOM_VELOCITY_Y))); velocityX = -velocityX + velocityVariationX; assert(velocityX <= 0); // if ball is moving too slow on X axis if (velocityX > -HI_RANDOM_VELOCITY_X) { velocityX = -HI_RANDOM_VELOCITY_X; } // if ball is moving too fast on X axis else if (velocityX < -BALL_SPEED_LIMIT) { velocityX = -BALL_SPEED_LIMIT; } velocityY = velocityY + velocityVariationY; // if ball is moving too fast on Y axis if (velocityY > BALL_SPEED_LIMIT || velocityY < -BALL_SPEED_LIMIT) { if (velocityY > 0) { velocityY = BALL_SPEED_LIMIT; } else { velocityY = -BALL_SPEED_LIMIT; } } return OFF_RPADDLE; } else { return AI_WIN; } } if (bouncedOnWall) { return OFF_WALL; } else { return NO_BOUNCE; } } }; class Game { public: bool gameOver; Paddle* paddleL; Paddle* paddleR; Ball* ball; Game() { srand(time(NULL)); } ~Game() { } void initialize(PLAYER_TYPE lPlayerType, PLAYER_TYPE rPlayerType) { //initialize and start game paddleL = new Paddle(0, lPlayerType); paddleR = new Paddle(1, rPlayerType); ball = new Ball(paddleL, paddleR); gameOver = false; } void destroy() { //clean up objects delete paddleL; delete paddleR; delete ball; } void reset() { gameOver = false; paddleL->reset(); paddleR->reset(); ball->reset(); } void trainRPaddle() { // BOUNCE_TYPE frameResult = NO_BOUNCE; paddleR->isTraining = true; for (int trainTrial = 0; trainTrial < TRAIN_TRIALS; trainTrial++) { reset(); while(!gameOver) { playOneFrame(); } } paddleR->isTraining = false; } BOUNCE_TYPE playOneFrame() { BOUNCE_TYPE frameResult; WorldStatus worldStatusL = {ball->posX, ball->posY, ball->velocityX, ball->velocityY, paddleL->posY}; WorldStatus worldStatusR = {ball->posX, ball->posY, ball->velocityX, ball->velocityY, paddleR->posY}; //while (!gameOver) //{ paddleL->makeMove(&worldStatusL); paddleR->makeMove(&worldStatusR); frameResult = ball->move(); if (frameResult == AI_WIN ) { gameOver = true; //printf("left Win\n"); } if (frameResult == RL_AI_WIN) { gameOver = true; //printf("right Win\n"); } //} return frameResult; } }; float gameBoardToWindowPosX(float gameBoardPos) { float windowPos = (gameBoardPos / GAME_BOARD_STRIDE) * SCREEN_STRIDE + SCREEN_MIN; return windowPos; } float gameBoardToWindowPosY(float gameBoardPos) { float windowPos = -((gameBoardPos / GAME_BOARD_STRIDE) * SCREEN_STRIDE + SCREEN_MIN); return windowPos; } void renderRPaddle(float paddlePosY) { float screenRPaddlePosY = gameBoardToWindowPosY(paddlePosY); glBegin(GL_POLYGON); //lower right glVertex2f(SCREEN_MAX, screenRPaddlePosY - PADDLE_HEIGHT_IN_WINDOW); //lower left glVertex2f(SCREEN_MAX - PADDLE_WIDTH, screenRPaddlePosY - PADDLE_HEIGHT_IN_WINDOW); //upper left glVertex2f(SCREEN_MAX - PADDLE_WIDTH, screenRPaddlePosY); //upper right glVertex2f(SCREEN_MAX, screenRPaddlePosY); glEnd(); } void renderLPaddle(float paddlePos) { float screenLPaddlePosY = gameBoardToWindowPosY(paddlePos); glBegin(GL_POLYGON); //lower right glVertex2f(SCREEN_MIN + PADDLE_WIDTH, screenLPaddlePosY - PADDLE_HEIGHT_IN_WINDOW); //lower left glVertex2f(SCREEN_MIN, screenLPaddlePosY - PADDLE_HEIGHT_IN_WINDOW); //upper left glVertex2f(SCREEN_MIN, screenLPaddlePosY); //upper right glVertex2f(SCREEN_MIN + PADDLE_WIDTH, screenLPaddlePosY); glEnd(); } void renderBall(float x, float y) { const float DEG2RAD = 3.14159 / 180; float ballRadius = 0.02; glBegin(GL_POLYGON); //for each degree of the circle, we draw a point for (int i = 0; i < 360; i++) { //convert degree to radians float degInRad = i * DEG2RAD; //DEG2RAD : how much radians is 1 degree //draw a dot on screen given x(1st argument) and y(second argument) coordinat glVertex2f(cos(degInRad) * ballRadius + gameBoardToWindowPosX(x), sin(degInRad) * ballRadius + gameBoardToWindowPosY(y)); } glEnd(); } int main(void) { float numRounds = 1; float avgRebounce = 0; float numRebounceThisRound = 0; BOUNCE_TYPE frameResult; Game* game = new Game(); game->initialize(TRAINER_AI, RL_AI); game->trainRPaddle(); // initialize glfw and exit if failed if (!glfwInit()) { exit(EXIT_FAILURE); } //telling he program the contextual information about openGL version glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); GLFWwindow* window = glfwCreateWindow(480, 480, "OpenGLtest", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); // the refresh between each frame. Setting it to 1 introduces a little delay for vSync glfwSwapInterval(2); while (!glfwWindowShouldClose(window)) { game->reset(); numRebounceThisRound = 0; while (!game->gameOver && !glfwWindowShouldClose(window)) { frameResult = game->playOneFrame(); if (frameResult == OFF_RPADDLE) { numRebounceThisRound++; } //Setup View float ratio; int width, height; //this function figures out the width and height of the window and set these variables glfwGetFramebufferSize(window, &width, &height); ratio = (float)width / height; //set up view port glViewport(0, 0, width, height); // GL_COLOR_BUFFER_BIT stores the color info of what's drawn on screen. glClear() clears this info glClear(GL_COLOR_BUFFER_BIT); //drawing. //from left to right of the window, the interval is [-1,1] . Similar for up and down // To draw a n sides GL_POLYGON on 2D surface, need to call glVertex2f() n times specifying the vertices of the polygon in some order //This example shows an example of a rectangle renderBall(game->ball->posX, game->ball->posY); renderLPaddle(game->paddleL->posY); renderRPaddle(game->paddleR->posY); //swap the front and back buffers of the specified window glfwSwapBuffers(window); //check for events glfwPollEvents(); } avgRebounce = avgRebounce + float(1 / numRounds)*(numRebounceThisRound - avgRebounce); numRounds++; } printf("avg Rebounce: %f\n", avgRebounce); game->destroy(); glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); }
b9f5a656f2515e8f0013ff8a78a0c8adeed3e78a
[ "C++" ]
1
C++
ww785612/Pong_RL_Learning
214bdc848f572a5051a1769956d9c9d584cd352f
352aa8389822fda86e7b189d712ab245a2b7cb19
refs/heads/master
<repo_name>ahmader/riot-html<file_sep>/src/stores/familystore.js // FamilyStore definition. // Flux stores house application logic and state that relate to a specific domain. // In this case, a list of family members. export default function FamilyStore() { if (!(this instanceof FamilyStore)) return new FamilyStore() riot.observable(this) // Riot provides our event emitter. var self = this self.family = { father: 'Bob', mother: null, children: [] }; // Our store's event handlers / API. // This is where we would use AJAX calls to interface with the server. // Any number of views can emit actions/events without knowing the specifics of the back-end. // This store can easily be swapped for another, while the view components remain untouched. self.on('app_init', function(family) { console.warn('FamilyStore::app_init'); // var cache = JSON.parse(localStorage.getItem('app_cache')) ; var cache = false; if (family) self.family=family; self.trigger('app_ready', cache || self.family); }) self.on('mother_update', function(newMother) { console.warn('FamilyStore::mother_update', self.family, newMother); self.family.mother=newMother; self.trigger('mother_changed', self.family); }) self.on('father_update', function(newFather) { console.warn('FamilyStore::father_update', self.family, newFather); self.family.father=newFather; self.trigger('father_changed', self.family); }) self.on('child_add', function(newChild) { console.warn('FamilyStore::child_add'); if (!newChild) newChild={name:'', gender:''}; newChild.age=3600; self.family.children.push(newChild); self.trigger('children_changed', self.family); }) self.on('child_remove', function(childId) { console.warn('FamilyStore::child_remove', childId); if (!self.family.children[childId]) return; self.family.children.splice(childId,1); self.trigger('family_changed', self.family); // self.trigger('children_changed', self.family); }) self.on('child_update', function(childId, child) { console.warn('FamilyStore::child_update', childId, child); self.family.children[childId] = Object.assign({}, self.family.children[childId], child); self.trigger('children_changed', self.family); }) self.on('child_update_gender', function(childId, gender) { console.warn('FamilyStore::child_update_gender', childId, gender); if (!gender || !self.family.children[childId]) return; self.family.children[childId].gender = gender; self.trigger('children_changed', self.family); }) // The store emits change events to any listening views, so that they may react and redraw themselves. }<file_sep>/webpack.config.js const webpack = require('webpack'); var path = require('path'); var commonConfig = require('./webpack.config.common'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin') var ExtractTextPlugin = require("extract-text-webpack-plugin"); var extractCSS = new ExtractTextPlugin('css/style.css'); var output = { path: path.resolve(__dirname, 'public'), // publicPath: 'http://www.example.com/build/', filename: 'js/bundle.js' }; module.exports = Object.assign(commonConfig, { output: output, module: { rules: commonConfig.module.rules.concat([{ test: /\.s?css$/, use: extractCSS.extract({ fallback: "style-loader", use: [ { loader: "css-loader", options: { minimize: true } }, { loader: 'sass-loader', options: { minimize: true } } ] }) }]) }, plugins: commonConfig.plugins.concat([ new CleanWebpackPlugin('public'), extractCSS, new webpack.LoaderOptionsPlugin({debug: true}), new webpack.optimize.CommonsChunkPlugin('vendor'), // new webpack.optimize.DedupePlugin(), new UglifyJSPlugin(), new webpack.optimize.AggressiveMergingPlugin() ]) });<file_sep>/src/js/main.js const defaultSettings = { title: 'default title', background: '#fff', }; const mainInfo = { info: 'main Info' }; export {defaultSettings, mainInfo}<file_sep>/README.md # ES6 Riot Starterkit With this starterkit boilerplate code we want to provide **a simple foundation for Riot applications**.<br> If you have any ideas on how to improve/simplify the structure you are welcome to help us. This starterkit is based on: * [Riot](https://muut.com/riotjs/). * [RiotControl](https://github.com/jimsparkman/RiotControl/). * [Sass (CSS with superpowers)](https://github.com/webpack-contrib/sass-loader). * [Webpack](http://webpack.github.io/). Features: * Javascript in ES6 using [Babel](https://babeljs.io/). * Riot tag script in ES6 * Use RiotControl to enable the flux-like app architecture TODO: * Use route, view and component to structure the app Optional Support: * [bootstrap v4.0.0](https://getbootstrap.com/). * [font-awesome](http://fontawesome.io/). * [jQuery](https://jquery.com/). * [Spectrum (The No Hassle jQuery Colorpicker)](https://bgrins.github.io/spectrum/). * [jQuery-ui](https://jqueryui.com/). ## Get the kit ``` $ git clone https://github.com/ahmader/riot-html.git && cd riot-html ``` ## Installation: ``` $ NODE_ENV=development npm install ``` ## Development: ``` $ npm start ``` A server with hot-reload will run at: [http://localhost:3000](http://localhost:3000) ## Building: ``` npm run build ``` A production minified version created at ./public folder ## Extras: ### SimpleHTTPServer : ``` cd public/ && python -m SimpleHTTPServer 8080 ``` ### Riot: Riot's default mini-ES6 method syntax cannot work when we are using babel, so we need to change: ```js // This would not work with babel buttonHandler(e) { // code } // Change to this this.buttonHandler = e => { // code } ``` You don't have to `import 'riot'` everywhere, instead, by using `webpack.ProvidePlugin` it is available everywhere. To Define global variable with webpack check this [stackoverflow](https://stackoverflow.com/a/40416826/1426938). ### jQuery and jquery-ui Also jQuery is available everywhere, only after you installed it. ``` npm install --save jquery ``` if you want window.$ to be available then add this code to `entry.js` ```js if (typeof jQuery != 'undefined') { // webpack will transpile global. to window. global.jQuery = global.jquery = global.$ = jQuery; } ``` For jquery-ui you can use `jquery-ui` official npm whereby you include what you need to use. (*recommended for size*) ``` npm install --save jquery jquery-ui ``` Then inside any tag ```js //import $ from 'jquery'; // no need to import jquery as its provided by `webpack.ProvidePlugin` import 'jquery-ui/themes/base/core.css'; // incase you need the core styles import 'jquery-ui/themes/base/theme.css'; // incase you need the theme styles import 'jquery-ui/themes/base/selectable.css'; // incase you need the selectable styles import 'jquery-ui/ui/widgets/selectable'; // incase you wanted to use $.fn.selectable import 'jquery-ui/ui/widgets/sortable'; // incase you wanted to use $.fn.sortable ``` Or if your project depend heavily on jquery-ui then use `jquery-ui-dist` where you can import all the library at once. [stackoverflow](https://stackoverflow.com/questions/35259835/how-to-import-jquery-ui-using-es6-es7-syntax)
b73a4c2dc8f06e5e44fa4233636d66d72713c344
[ "JavaScript", "Markdown" ]
4
JavaScript
ahmader/riot-html
321444d0241237a01a63d8a3896fc47afa52f57b
c1fe7d0177864a27dd4223ce6bf5f4d35fced638
refs/heads/master
<repo_name>akamit21/samagra<file_sep>/src/APIButton.jsx import React from "react"; import { Col, Button } from "react-bootstrap"; const APIButton = (props) => { return ( <Col md={6}> <Button type="button" className="my-2" variant="outline-dark" size="lg" block onClick={props.handler} > {props.name} </Button> </Col> ); }; export default APIButton; <file_sep>/src/DataTable.jsx import React from "react"; import { Col, Table } from "react-bootstrap"; const DataTable = (props) => { return ( <Col md={6}> <Table striped bordered hover> <tbody> <tr> <td>Start: </td> <td>{props.data.startTime}</td> </tr> <tr> <td>End: </td> <td>{props.data.endTime}</td> </tr> <tr> <td>Start Save: </td> <td>{props.data.saveStartTime}</td> </tr> <tr> <td>End Save: </td> <td>{props.data.saveEndTime}</td> </tr> </tbody> </Table> </Col> ); }; export default DataTable; <file_sep>/src/redux/reducers/rootReducer.js import { COMMENTS_REQUEST, COMMENTS_SUCCESS, // COMMENTS_FAILURE, PHOTOS_REQUEST, PHOTOS_SUCCESS, // PHOTOS_FAILURE, TODOS_REQUEST, TODOS_SUCCESS, // TODOS_FAILURE, POSTS_REQUEST, POSTS_SUCCESS, // POSTS_FAILURE, } from "../actionType"; let initialState = { error: false, comment: {}, photo: {}, todo: {}, post: {}, }; /** * root reducer * @param {*} state * @param {*} action {type, payload} */ export const rootReducer = (state = initialState, action) => { switch (action.type) { // comments case COMMENTS_REQUEST: { return { ...state, }; } case COMMENTS_SUCCESS: { return { ...state, comment: { startTime: action.payload.startTime, endTime: action.payload.endTime, saveStartTime: action.payload.saveStartTime, saveEndTime: action.payload.saveEndTime, }, }; } // photos case PHOTOS_REQUEST: { return { ...state, }; } case PHOTOS_SUCCESS: { return { ...state, photo: { startTime: action.payload.startTime, endTime: action.payload.endTime, saveStartTime: action.payload.saveStartTime, saveEndTime: action.payload.saveEndTime, }, }; } // todos case TODOS_REQUEST: { return { ...state, }; } case TODOS_SUCCESS: { return { ...state, todo: { startTime: action.payload.startTime, endTime: action.payload.endTime, saveStartTime: action.payload.saveStartTime, saveEndTime: action.payload.saveEndTime, }, }; } // posts case POSTS_REQUEST: { return { ...state, }; } case POSTS_SUCCESS: { return { ...state, post: { startTime: action.payload.startTime, endTime: action.payload.endTime, saveStartTime: action.payload.saveStartTime, saveEndTime: action.payload.saveEndTime, }, }; } default: return state; } }; <file_sep>/README.md # ReactJS Assignment - Samagra ## Problem Statement You have to make a single page web application which will download data from the following urls1 simultaneously (and record the timestamp of the start and end of the request) and save it in IndexedDB using models of your choice (and save the timestamp of start and end of the saving time). The UI of the app will be as shown below. The four Urls should be pinged at the same time (5-sec delay after opening the Activity) and the recorded times (timestamps) have to show in the UI under the heads of - [x] Start: When you ping the Url - [x] End: When you finish parsing the Url - [x] Start Save: When you start saving the Data - [x] End Save: When you end saving the data [ **Demo** ](https://samagra.now.sh/) ### Tech / Stack - - HTML5 - Bootstrap - JavaScript - React - Redux & JSON - JSONPlaceholder API ### Features implemented - - [x] fetch data from multiple APIs simultaneouly - [x] stored data into LocalStorage - [x] Unix Timestamp ### Required UI - ![Screenshot](./extra/2.jpeg) ### ScreenShot - ![Screenshot](./extra/1.jpeg) ### Instructions to Run ### `npm install` ### `npm start` Runs the app in the development mode. Open [http://localhost:3000](http://localhost:3000) to view it in the browser. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). <file_sep>/src/redux/actionType.js // fetch comments export const COMMENTS_REQUEST = "COMMENTS_REQUEST"; export const COMMENTS_SUCCESS = "COMMENTS_SUCCESS"; export const COMMENTS_FAILURE = "COMMENTS_FAILURE"; // fetch photos export const PHOTOS_REQUEST = "PHOTOS_REQUEST"; export const PHOTOS_SUCCESS = "PHOTOS_SUCCESS"; export const PHOTOS_FAILURE = "PHOTOS_FAILURE"; // fetch todos export const TODOS_REQUEST = "TODOS_REQUEST"; export const TODOS_SUCCESS = "TODOS_SUCCESS"; export const TODOS_FAILURE = "TODOS_FAILURE"; // fetch posts export const POSTS_REQUEST = "POSTS_REQUEST"; export const POSTS_SUCCESS = "POSTS_SUCCESS"; export const POSTS_FAILURE = "POSTS_FAILURE"; <file_sep>/src/Clock.jsx import React, { useState, useEffect } from "react"; const Clock = () => { const [time, setTime] = useState(Date.now()); useEffect(() => { let time = setInterval(() => { setTime(Date.now()); }, 1000); return () => { clearInterval(time); }; }); return <h1>{time}</h1>; }; export default Clock;
5ceb8ed8442e2f9d5d00fdc3471d9a6308ba589f
[ "JavaScript", "Markdown" ]
6
JavaScript
akamit21/samagra
4cf241eef029342136ce5b12a6f9f95738500259
d8e44e5596530f19151b54c84c07662c6b015e77
refs/heads/main
<file_sep>CREATE TABLE IF NOT EXISTS USERS ( userid INT PRIMARY KEY auto_increment, username VARCHAR(20), salt VARCHAR, password VARCHAR, firstname VARCHAR(20), lastname VARCHAR(20) ); CREATE TABLE IF NOT EXISTS NOTES ( noteid INT PRIMARY KEY auto_increment, notetitle VARCHAR(20), notedescription VARCHAR(1000), userid INT, foreign key (userid) references USERS(userid) ); CREATE TABLE IF NOT EXISTS FILES ( fileid INT PRIMARY KEY auto_increment, filename VARCHAR, contenttype VARCHAR, filesize VARCHAR, userid INT, -- filedata BLOB, foreign key (userid) references USERS(userid) ); CREATE TABLE IF NOT EXISTS CREDENTIALS ( credentialid INT PRIMARY KEY auto_increment, url VARCHAR(100), username VARCHAR (30), key VARCHAR, password VARCHAR, userid INT, foreign key (userid) references USERS(userid) ); INSERT INTO USERS (username,salt,password,firstname,lastname) VALUES ('thanhnhan3395','uCv7NPENHAnRoGXX/zrg2g==','hehYFfMnU2ywA7xNibCAQw==','Nhan','<NAME>'); INSERT INTO NOTES (notetitle,notedescription,userid) VALUES ('Example Note Title','Example Note Description',1), ('Meeting at 10AM','Attend the internal meeting at 10AM. This is an online meeting',1); INSERT INTO CREDENTIALS (url,username,key,password,userid) VALUES ('https://brse-sharing.nhanthanhtran.com/','<EMAIL>','Snt4vrMionVN9jnxjlarHw==','vr53olHCL/Nv9c8IgqOuvYan2mQCQW4wk7+JyX6mHzE=',1); INSERT INTO FILES (filename,contenttype,filesize,userid) VALUES ('example.txt','text','1kb',1)<file_sep>package com.udacity.jwdnd.course1.cloudstorage.mapper; import com.udacity.jwdnd.course1.cloudstorage.model.FileUpload; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper public interface FileMapper { @Select("SELECT * FROM FILES") List<FileUpload> getFiles(); @Select("SELECT * FROM FILES WHERE fileid=#{fileId}") FileUpload getFileById(Integer fileId); @Insert("INSERT INTO FILES(filename,contenttype,filesize,userid) VALUES (#{fileName},#{contentType},#{fileSize},#{userId})") Integer createFile(FileUpload file); } <file_sep>package com.udacity.jwdnd.course1.cloudstorage; import com.udacity.jwdnd.course1.cloudstorage.model.Credential; import com.udacity.jwdnd.course1.cloudstorage.services.CredentialService; import com.udacity.jwdnd.course1.cloudstorage.services.EncryptionService; import org.junit.jupiter.api.Test; import org.mybatis.spring.boot.test.autoconfigure.MybatisTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Import; import static org.junit.jupiter.api.Assertions.*; @MybatisTest @Import({CredentialService.class,EncryptionService.class}) public class CredentialServiceTests { @Autowired private CredentialService credentialService; @Autowired private EncryptionService encryptionService; @Test public void testCredentialServiceCreateCredential(){ Credential credential = new Credential(null,"https://brse-sharing.nhanthanhtran.com/","<EMAIL>",null,"<PASSWORD>",1); Integer credentialId = credentialService.createCredential(credential); assertNotNull(credentialId); Credential credentialAfterCreate = credentialService.getCredentialByid(credentialId); assertEquals(credential.getUrl(),credentialAfterCreate.getUrl()); assertEquals(credential.getUsername(),credentialAfterCreate.getUsername()); assertEquals(credential.getPassword(),encryptionService.decryptValue(credentialAfterCreate.getPassword(),credentialAfterCreate.getKey())); } @Test public void testCredentialServiceUpdateCredential(){ Credential credential = new Credential(null,"https://brse-sharing.nhanthanhtran.com/","<EMAIL>",null,"<PASSWORD>",1); Integer credentialId = credentialService.createCredential(credential); assertNotNull(credentialId); Credential credentialAfterCreate = credentialService.getCredentialByid(credentialId); Credential credentialUpdate = new Credential(credentialId,"https://test.com/","<EMAIL>",credentialAfterCreate.getKey(),"testPassword",1); Credential credentialAfterUpdate = credentialService.updateCredential(credentialUpdate); assertNotNull(credentialAfterUpdate); } }
975b82d2fc77f677b9b42c26224348365e534cf4
[ "Java", "SQL" ]
3
SQL
nhantran3395/nd035-c1-spring-boot-basics-project-starter
fb4a36a12f6c290e5439225e57a6d065d8fc090d
2da7e653ab5fb786eda364d41c32839aa2b18d63
refs/heads/master
<file_sep>from flask import Flask from flask_restful import reqparse, abort, Api, Resource from model import Exchange, logger import os from datetime import date app = Flask(__name__) app.config.from_object('config') api = Api(app) base_url = '/api/v1' # def abort_if_code_doesnt_exist(code, exchange): # latest_currencies = exchange.get_latest_currency(code) # if code not in latest_currencies['rates'][code]: # abort(404, message="{} doesn't exist".format(code)) class Convert(Resource): def get(self, value, from_currency, to_currency): logger.info("START Convert") exchange = Exchange() # abort_if_code_doesnt_exist(code=from_currency, exchange=exchange) converted_val, error = exchange.convert(value, from_currency=from_currency, to_currency=to_currency) if error: logger.error(f'{error["msg"]}', 'error') today = date.today() if converted_val: data = { "query": "/convert/{}/{}/{}".format(value, from_currency, to_currency), "converted_value": converted_val, "from": from_currency, "to": to_currency, "date": str(today) } logger.info("convert data {}".format(data)) else: data = { "query": "/convert/{}/{}/{}".format(value, from_currency, to_currency), "converted_value": {}, "from": from_currency, "to": to_currency, "date": str(today), "error": 1 } logger.info("convert data {}".format(data)) logger.info("END Convert") return data class Latest(Resource): map_currency = ["CZK", "EUR", "PLN", "USD"] def get(self, code): exchange = Exchange() latest_currencies = exchange.get_latest_currency(code) logger.info("START Latest: 'code' is %s", code) logger.info("Latest currencies {}".format(latest_currencies)) today = date.today() if "rates" in latest_currencies: # rates = {key: latest_currencies['rates'][key] for key in latest_currencies['rates'].keys() - self.map_currency} data = { "rates": latest_currencies['rates'], "base": code, "date": str(today) } logger.info("latest data {}".format(data)) else: data = { "rates": {}, "base": code, "date": str(today), "error": 1 } logger.error("latest data {}".format(data)) logger.info("END Latest") return data ## Actually setup the Api resource routing here ''' resource: convert, '/convert/value:/from:/to:' format: { "query": "/convert/19999.95/GBP/EUR", "value": 19999.95, "from": "GBP", "to": "EUR" "timestamp": xxxx } ''' api.add_resource(Convert, base_url + "/convert/<value>/<from_currency>/<to_currency>") ''' api.add latest, '/latest/base/code:' { "rates":{ "CZK": 1.5785, "EUR": 1.4785, "PLN": 1.6785, "USD": 0.2785, } , "base": "USD", "timestamp": xxx } ''' api.add_resource(Latest, base_url + "/latest/base/<code>") if __name__ == '__main__': port = int(os.environ.get('PORT', 6000)) app.run(host='0.0.0.0', port=port) <file_sep>from flask_wtf import FlaskForm from wtforms import FloatField, SubmitField, SelectField from wtforms.validators import DataRequired class ExchangeForm(FlaskForm): CURRENCY_CODE = [('CZK', 'CZK'), ('USD', 'USD'), ('PLN', 'PLN'), ('EUR', 'EUR')] currency_val = FloatField('Currency value', validators=[DataRequired()]) select_currency = SelectField(u'Select currency', choices=CURRENCY_CODE) select_converted = SelectField(u'Select currency', choices=CURRENCY_CODE) submit = SubmitField('Convert') <file_sep>Flask Flask-WTF WTForms coverage pytest flask-restful mongoengine >= 0.19.1 httpie<file_sep>import pytest @pytest.fixture def supply(): aa = 54 bb = 34 return [aa, bb] @pytest.fixture def supply_url(): return "https://reqres.in/api" <file_sep>[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ## Install ```bash git clone https://github.com/code-datum/currency-converter cd currency-converter virtualenv venv source venv/bin/activate pip install -r requirements.txt python app.py # User interface http://0.0.0.0:5000 python api.py # REST API http://0.0.0.0:6000 ``` Api command: conversion: http http://0.0.0.0:6000/api/v1/convert/12/USD/CAD Result: ```bash HTTP/1.0 200 OK Content-Length: 134 Content-Type: application/json Date: Fri, 28 Feb 2020 10:57:05 GMT Server: Werkzeug/1.0.0 Python/3.7.6 { "converted_value": 16.01897, "date": "2020-02-28", "from": "USD", "query": "/convert/12/USD/CAD", "to": "CAD" } ``` get latest currency: http http://0.0.0.0:6000/api/v1/latest/base/USDhttp://127.0.0.1:5000/ ```bash HTTP/1.0 200 OK Content-Length: 1036 Content-Type: application/json Date: Fri, 28 Feb 2020 11:06:12 GMT Server: Werkzeug/1.0.0 Python/3.7.6 { "base": "USD", "date": "2020-02-28", "rates": { "AUD": 1.520612915, "BGN": 1.7838380153, "BRL": 4.4668916454, "CAD": 1.3349142649, "CHF": 0.9692630427, "CNY": 7.0059284933, "CZK": 23.0600145932, "DKK": 6.8154870485, "EUR": 0.9120758847, "GBP": 0.7752188982, "HKD": 7.7942356804, "HRK": 6.8063662897, "HUF": 308.6191171105, "IDR": 14034.9963516965, "ILS": 3.4358810653, "INR": 71.6326158336, "ISK": 127.0521707406, "JPY": 109.8686610726, "KRW": 1211.0817219993, "MXN": 19.3908245166, "MYR": 4.2105071142, "NOK": 9.3869025903, "NZD": 1.5802626779, "PHP": 50.8637358628, "PLN": 3.9332360452, "RON": 4.3870850055, "RUB": 65.7654140825, "SEK": 9.6454761036, "SGD": 1.3949288581, "THB": 31.6499452754, "TRY": 6.1599781102, "USD": 1.0, "ZAR": 15.3611820503 } } ``` ## Screenshots ![Forms](convert-currency.png) <file_sep># ----------------------------------------------------------------------------# # Imports # ----------------------------------------------------------------------------# from flask import Flask, render_template, url_for, flash, redirect import pytest # from flask.ext.sqlalchemy import SQLAlchemy import logging from logging import Formatter, FileHandler from datetime import date from forms import ExchangeForm from model import Exchange import os # ----------------------------------------------------------------------------# # App Config. # ----------------------------------------------------------------------------# app = Flask(__name__) app.config.from_object('config') # db = SQLAlchemy(app) # ----------------------------------------------------------------------------# # procedures # ----------------------------------------------------------------------------# # ----------------------------------------------------------------------------# # Controllers. # ----------------------------------------------------------------------------# @app.route('/', methods=['GET', 'POST']) def exchange(): currency_val = None currency_title = None converted_val = None converted_title = None today = None form = ExchangeForm() if form.validate_on_submit(): '''TODO if everything is validated then give the data to Exchange methods 1. send to api 2. returned result to prepare and give to view ''' flash(f'Currency converted', 'success') currency_val = form.currency_val.data currency_code = form.select_currency.data converted_code = form.select_converted.data # calculate data from input exchange = Exchange() currency_title = exchange.get_currency_title(currency_code) converted_title = exchange.get_currency_title(converted_code) converted_val, error = exchange.convert(currency_val, from_currency=currency_code, to_currency=converted_code) if error: flash(f'{error["msg"]}', 'error') today = date.today() else: flash(f'Please fill the all fields', 'error') from_currency = {'value': currency_val, 'title': currency_title} to_currency = {'value': converted_val, 'title': converted_title} return render_template('pages/exchange.html', form=form, from_currency=from_currency, to_currency=to_currency, today=today) ''' @app.route("/register", methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): flash(f'Account created for {form.username.data}!', 'success') return redirect(url_for('home')) return render_template('pages/register.html', title='Register', form=form) ''' # Error handlers. @app.errorhandler(500) def internal_error(error): # db_session.rollback() return render_template('errors/500.html'), 500 @app.errorhandler(404) def not_found_error(error): return render_template('errors/404.html'), 404 if not app.debug: file_handler = FileHandler('error.log') file_handler.setFormatter( Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') ) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('errors') # ----------------------------------------------------------------------------# # Launch. # ----------------------------------------------------------------------------# # Default port: if __name__ == '__main__': app.run() # Or specify port manually: ''' if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) ''' <file_sep>import logging from urllib.parse import urlencode import requests DECIMAL_INDEX = 2 # Enable logging logging.basicConfig(filename='debug.log', filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) class Exchange: currencies_url = 'https://openexchangerates.org/api/currencies.json' base_api_url = 'https://api.exchangeratesapi.io' currencies_type = 'currencies' latest_type = 'latest' round_index = 5 def __init__(self): pass def convert(self, value, from_currency, to_currency='USD'): error = {} ''' convert currency use extend api :param value: :param from_currency: :param to_currency: :return decimal: ''' logger.info("Exchange.convert is run") content = self.get_latest_currency(from_currency) if 'rates' in content: to_currency_unit = content['rates'][to_currency] converted_money = round(float(value) * to_currency_unit, self.round_index) logger.info("converted currency: %s", converted_money) logger.info("Exchange.convert is run") else: logging.error("data isn't got") error = {"msg": "Currency isn't get from API"} converted_money = None return converted_money, error def query_to_api(self, type_query, args): if type_query == self.latest_type: # https://api.exchangeratesapi.io/latest?base=USD prefix_url = '/latest?' + urlencode({'base': args['code']}) logger.info("prefix url%s", self.base_api_url + prefix_url) content = requests.get(url=self.base_api_url + prefix_url).json() # content = {} elif type_query == self.currencies_type: content = requests.get(url=self.currencies_url).json() logger.info("query_url's result:{}".format(content)) return content def get_currency_title(self, code): ''' Return by code currencies title :return: string ''' # https://openexchangerates.org/api/currencies.json currencies_title = self.query_to_api('currencies', self.currencies_type) if code in currencies_title: return currencies_title[code] else: return None def get_latest_currency(self, from_currency): return self.query_to_api('latest', {'code': from_currency})
4bf40dcd9468e7eaed2c527f8b691a77f1f5e901
[ "Markdown", "Python", "Text" ]
7
Python
code-datum/currency-converter
2b0f4871928e6d27af1deb46d9f5d53b7ad75b85
3fcbd6d1f0bb5421ad537c479a81c9e5f664da05
refs/heads/master
<file_sep>import os from mindsdb.libs.constants.mindsdb import * from mindsdb.config import * import pandas as pd import lightwood class LightwoodBackend(): def __init__(self, transaction): self.transaction = transaction self.predictor = None def _create_lightwood_config(self): config = {} #config['name'] = 'lightwood_predictor_' + self.transaction.lmd['name'] config['input_features'] = [] config['output_features'] = [] for col_name in self.transaction.input_data.columns: if col_name in self.transaction.lmd['malformed_columns']['names']: continue col_stats = self.transaction.lmd['column_stats'][col_name] data_subtype = col_stats['data_subtype'] data_type = col_stats['data_type'] lightwood_data_type = None other_keys = {'encoder_attrs': {}} if data_type in (DATA_TYPES.NUMERIC): lightwood_data_type = 'numeric' elif data_type in (DATA_TYPES.CATEGORICAL): lightwood_data_type = 'categorical' elif data_subtype in (DATA_SUBTYPES.DATE): lightwood_data_type = 'categorical' elif data_subtype in (DATA_SUBTYPES.TIMESTAMP): lightwood_data_type = 'datetime' elif data_subtype in (DATA_SUBTYPES.IMAGE): lightwood_data_type = 'image' other_keys['encoder_attrs']['aim'] = 'balance' elif data_subtype in (DATA_SUBTYPES.TEXT): lightwood_data_type = 'text' # @TODO Handle lightwood's time_series data type else: self.transaction.log.error(f'The lightwood model backend is unable to handle data of type {data_type} and subtype {data_subtype} !') raise Exception('Failed to build data definition for Lightwood model backend') col_config = { 'name': col_name, 'type': lightwood_data_type } col_config.update(other_keys) if col_name not in self.transaction.lmd['predict_columns']: config['input_features'].append(col_config) else: config['output_features'].append(col_config) return config def train(self): lightwood_config = self._create_lightwood_config() if self.transaction.lmd['skip_model_training'] == True: self.predictor = lightwood.Predictor(load_from_path=os.path.join(CONFIG.MINDSDB_STORAGE_PATH, self.transaction.lmd['name'] + '_lightwood_data')) else: self.predictor = lightwood.Predictor(lightwood_config) self.predictor.learn(from_data=self.transaction.input_data.train_df, test_data=self.transaction.input_data.test_df) self.transaction.log.info('Training accuracy of: {}'.format(self.predictor.train_accuracy)) self.transaction.lmd['lightwood_data']['save_path'] = os.path.join(CONFIG.MINDSDB_STORAGE_PATH, self.transaction.lmd['name'] + '_lightwood_data') self.predictor.save(path_to=self.transaction.lmd['lightwood_data']['save_path']) def predict(self, mode='predict', ignore_columns=[]): if mode == 'predict': # Doing it here since currently data cleanup is included in this, in the future separate data cleanup lightwood_config = self._create_lightwood_config() df = self.transaction.input_data.data_frame if mode == 'validate': df = self.transaction.input_data.validation_df elif mode == 'test': df = self.transaction.input_data.test_df if self.predictor is None: self.predictor = lightwood.Predictor(load_from_path=self.transaction.lmd['lightwood_data']['save_path']) # not the most efficient but least prone to bug and should be fast enough if len(ignore_columns) > 0: run_df = df.copy(deep=True) for col_name in ignore_columns: run_df[col_name] = [None] * len(run_df[col_name]) else: run_df = df predictions = self.predictor.predict(when_data=run_df) formated_predictions = {} for k in predictions: formated_predictions[k] = predictions[k]['predictions'] return formated_predictions
ea27f73dea2dc9da5045ca751b71afe8bf2fed4b
[ "Python" ]
1
Python
chengjingfeng/mindsdb
80da03ee1186d3b6bf695323ba9d5d4ff254edab
6ddd9eefd713a63b42dc22ee4237a875f8b61f12
refs/heads/master
<repo_name>dooart/github-backlog-toolkit<file_sep>/src/tasks/index.js const tasksIds = [ 'issues-without-project', 'last-production-deploy', 'labeled-issues-in-projects', 'labeled-prs', 'unreleased-releases' ] const tasks = tasksIds.reduce((tasks, taskId) => { tasks[taskId] = require(`./${taskId}`).default return tasks }, {}) export default tasks <file_sep>/src/tasks/last-production-deploy.js import moment from 'moment' import repos from '../utils/repos' export default async (octokit, config) => { const messages = [] for (const repo of config.repos) { try { const repoInfo = { owner: repos.getOwner(repo), repo: repos.getRepoName(repo) } const refs = await octokit.git.listRefs({ ...repoInfo, namespace: 'tags/' }) const previous = refs.data[refs.data.length - 2].ref.substring( 'refs/tags/'.length ) const latest = refs.data[refs.data.length - 1].ref.substring( 'refs/tags/'.length ) const commits = (await octokit.repos.compareCommits({ ...repoInfo, base: previous, head: latest })).data.commits const lastCommit = commits[commits.length - 1] const lastCommitInfo = await octokit.git.getCommit({ ...repoInfo, commit_sha: lastCommit.sha }) const date = moment(lastCommitInfo.data.committer.date).fromNow() messages.push( `The last deploy of ${repo} to production happened ${date}.` ) } catch (e) { console.error(e) messages.push(`Error checking for last ${repo} deploy date.`) } } return messages } <file_sep>/src/tasks/issues-without-project.js import repos from '../utils/repos' export default async (octokit, config) => { const messages = [] for (const repo of config.repos) { try { const result = await octokit.search.issuesAndPullRequests({ q: `repo:${repo} type:issue no:project is:open` }) if (result.data.total_count) { messages.push( `There are ${ result.data.total_count } issues without project in ${repo}:\n ${repos.getGithubUrl( repo )}/issues?q=is:issue+is:open+no:project` ) } } catch (e) { console.error(e) messages.push(`Error checking ${repo} for issues without project.`) } } return messages } <file_sep>/src/tasks/labeled-prs.js import repos from '../utils/repos' export default async (octokit, config) => { const messages = [] for (const repo of config.repos) { try { const labels = repo.labels.map(label => `label:"${label}"`).join(' ') const result = await octokit.search.issuesAndPullRequests({ q: `repo:${repo.repoUrl} type:pr is:open ${labels}` }) if (result.data.total_count) { const foundLabels = result.data.items.reduce( (foundLabels, pr) => [ ...foundLabels, ...pr.labels .filter(label => repo.labels.includes(label.name)) .map(label => label.name) ], [] ) let message = repo.message || 'Found $number labeled prs ($labels) in $repo \n $repoUrl' message = message.replace('$repo', repo.repoUrl) message = message.replace('$number', result.data.total_count) message = message.replace( '$labels', [...new Set(foundLabels)].join(' + ') ) message = message.replace( '$repoUrl', `${repos.getGithubUrl(repo.repoUrl)}/pulls?q=is:pr+is:open` ) messages.push(message) } } catch (e) { console.error(e) messages.push(`Error checking ${repo} for issues without project.`) } } return messages } <file_sep>/README.md # Github Backlog Toolkit A toolkit to help teams using Github to organize their sprints. It runs different tasks to fetch information from Github. GBT currently does three things: 1. Find issues not assigned to any project boards 2. Find issues in project boards that contain specific labels 3. Prints the last time you've deployed a repository to production (last version tag) ### Using GBT in a project 1. Add it to your project using `yarn` or `npm` 2. Import GBT as a module 3. Send a configuration object as a parameter to the module (see `config.json.sample` for an example) ### Running GBT from the command line 1. Create a `config.json` file with the contents of `config.json.sample`. 2. Remove the tasks you don't want to run 3. Update the configuration to match your repositories, project boards, etc. 4. Set a `GITHUB_TOKEN` env var containing a valid Github token. <file_sep>/src/tasks/unreleased-releases.js import repos from '../utils/repos' export default async (octokit, config) => { const messages = [] for (const repo of config.repos) { try { const repoInfo = { owner: repos.getOwner(repo), repo: repos.getRepoName(repo) } const release = await octokit.repos.getLatestRelease({ ...repoInfo }) if (release.data.prerelease) { messages.push(`There is a release marked as prerelease in ${repo}.`) } } catch (e) { console.error(e) messages.push(`Error checking for unreleased releases in ${repo}.`) } } return messages } <file_sep>/src/utils/repos.js export default { getOwner: fullRepoName => fullRepoName.split('/')[0], getRepoName: fullRepoName => fullRepoName.split('/')[1], getGithubUrl: fullRepoName => `https://github.com/${fullRepoName}` } <file_sep>/src/task-runner.js import Octokit from '@octokit/rest' import tasks from './tasks' export default async config => { const octokit = new Octokit({ auth: config.githubToken || process.env.GITHUB_TOKEN, userAgent: 'github-backlog-toolkit 0.0.1' }) let allMessages = [] for (const task in config.tasks) { const messages = await tasks[task](octokit, config.tasks[task]) allMessages = [...allMessages, ...messages] } return allMessages } <file_sep>/src/utils/projects.js export default { getOwner: projectUrl => projectUrl.split('/')[0], getRepoName: projectUrl => { const split = projectUrl.split('/') if (split.length === 2) return null // org project eg. "org/123" return split[1] // repo project eg. "org/repo/123" }, getNumber: projectUrl => { const split = projectUrl.split('/') if (split.length === 2) return parseInt(split[1]) // org project eg. "org/123" return parseInt(split[2]) // repo project eg. "org/repo/123" } } <file_sep>/src/console.js import fs from 'fs' import taskRunner from './task-runner' const run = async () => { try { const config = JSON.parse(fs.readFileSync('./config.json', 'utf8')) const messages = await taskRunner(config) messages.forEach(message => console.log(message)) } catch (e) { console.error(e) } } run()
17e78e7e44a91a5a3530c719200ef77c717ae49b
[ "JavaScript", "Markdown" ]
10
JavaScript
dooart/github-backlog-toolkit
47cc3f480f07d0e66e4b804aa3c0ab31cfcfaf49
5a9d5875231e19ceef51ba4eb855faf47cfb61af
refs/heads/master
<repo_name>filipmikolajzeglen/how-to-sql-injection<file_sep>/src/pl/filipzeglen/injection/servlet/LoginServlet.java package pl.filipzeglen.injection.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DataSource ds = null; try { ds = getDataSource(); } catch (NamingException e) { e.printStackTrace(); response.sendError(500); } final String sqlQuery = "SELECT username, password FROM user WHERE username=? AND password=?"; try (Connection conn = ds.getConnection(); PreparedStatement statement = conn.prepareStatement(sqlQuery);) { String username = request.getParameter("username"); String password = request.getParameter("password"); statement.setString(1, username); statement.setString(2, password); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { String userFound = resultSet.getString("username"); request.getSession().setAttribute("username", userFound); if ("admin".equals(userFound)) { request.getSession().setAttribute("privigiles", "all"); } else { request.getSession().setAttribute("privigiles", "view"); } } else { request.getSession().setAttribute("username", "Nieznajomy"); request.getSession().setAttribute("privigiles", "none"); } request.getRequestDispatcher("result.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); response.sendError(500); } } private DataSource getDataSource() throws NamingException { Context initialContext = new InitialContext(); Context envContext = (Context) initialContext.lookup("java:comp/env"); return (DataSource) envContext.lookup("jdbc/users"); } }
4ddfeddcc6e2d9ab7c1b00f5a8b6f696d7f98448
[ "Java" ]
1
Java
filipmikolajzeglen/how-to-sql-injection
7eab4549f5f14b1a1de35c46ba8afbc9140ad25c
39cb242a4affad4bb99f9d400491d5f15fa2b1a7
refs/heads/master
<file_sep>import cv2 from utils.cvlab import Cvlab if __name__ == "__main__": path = '/win/專案資料/玻璃纖維/實驗圖片收集/整體實驗/20201116/line5-5附著-Feather__2020082503415405_Original-整體實驗/3_增加最後向外消除的範圍/6_canny_show_img.jpg' cvlab = Cvlab() img = cv2.imread(path) cvlab.imshow('viewer', img) cv2.waitKey(0) cv2.destroyAllWindows()
6c4ecedaa98e587d84d541a468dad9b3574afa60
[ "Python" ]
1
Python
Heegreis/Basic-Digital-Image-Processing
e08dfa15e4401cf6e82f986a23d1d7d51ed0b93a
c7a1caf586d6836d9b5cf48d602aa26989a2e4ae
refs/heads/master
<file_sep>def db_connection begin connection = PG.connect(dbname:'recipes') yield(connection) ensure connection.close end end class Recipe attr_reader :name, :id, :instructions, :description, :ingredients def initialize(name, id, instructions, description, ingredients) @name = name @id = id @description = description @instructions = instructions end def self.all recipes = nil db_connection do |connection| recipes = connection.exec('SELECT name, id, instructions, description FROM recipes') end recipes_array = [] recipes.each do |recipe| recipes_array << Recipe.new(recipe["name"],recipe["id"], recipe["instructions"], recipe["description"], nil) end recipes_array end def self.find(id) record = nil find_sql = "SELECT name, id, description, instructions FROM recipes WHERE recipes.id = $1" db_connection do |connection| record = connection.exec(find_sql, [id]).first end #binding.pry Recipe.new(record["name"], record["id"], record["instructions"], record["description"], nil) end def ingredients pieces = nil ingredients_sql = "SELECT ingredients.name AS ingredient, recipe_id FROM ingredients WHERE ingredients.recipe_id = $1" db_connection do |connection| pieces = connection.exec(ingredients_sql, [id]) end array_ofingredients = [] pieces.each do |piece| array_ofingredients << Ingredient.new(piece["ingredient"]) end array_ofingredients end end
5804b98bcb6703356ea8ee3bdea6c89762a78945
[ "Ruby" ]
1
Ruby
johnsko89/lunar-kitchen
cababeb3591df31ca0ec3135cd841e770d0e3ac7
7369ce474e639480c0606db5e998fdc485508c2d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebApplication4.Models; namespace WebApplication4.Controllers { public class MiTablasController : Controller { private CargaDatosEntities db = new CargaDatosEntities(); // GET: MiTablas public ActionResult Index() { return View(db.MiTabla.ToList()); } public ActionResult Buscar() { return View(db.MiTabla.ToList()); } // GET: MiTablas/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MiTabla miTabla = db.MiTabla.Find(id); if (miTabla == null) { return HttpNotFound(); } return View(miTabla); } // GET: MiTablas/Create public ActionResult Create() { return View(); } // POST: MiTablas/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "Id,Nombre,Detalle,Fecha,Precio,Cantidad")] MiTabla miTabla) { if (ModelState.IsValid) { db.MiTabla.Add(miTabla); db.SaveChanges(); return RedirectToAction("Index"); } return View(miTabla); } // GET: MiTablas/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MiTabla miTabla = db.MiTabla.Find(id); if (miTabla == null) { return HttpNotFound(); } return View(miTabla); } // POST: MiTablas/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "Id,Nombre,Detalle,Fecha,Precio,Cantidad")] MiTabla miTabla) { if (ModelState.IsValid) { db.Entry(miTabla).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(miTabla); } // GET: MiTablas/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } MiTabla miTabla = db.MiTabla.Find(id); if (miTabla == null) { return HttpNotFound(); } return View(miTabla); } // POST: MiTablas/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { MiTabla miTabla = db.MiTabla.Find(id); db.MiTabla.Remove(miTabla); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } public JsonResult BuscarDatosAutocomplete(string term) { var resultado = db.MiTabla.Where(x => x.Nombre.Contains(term)).Select(x => x.Nombre).ToList(); return Json(resultado, JsonRequestBehavior.AllowGet); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WebActualizacionDatos.Models; namespace WebActualizacionDatos.Controllers { public class DetalleController : Controller { } }
6fb181e600bb534c01b59166dcd9b17d9eb0c2cb
[ "C#" ]
2
C#
Martineg100/RepositorioNegocio
7f5b4894a08fe4eced197edef380266979a47181
12f208b471b9d7eeb367bc38e63e44967f8ebb50
refs/heads/master
<repo_name>anilca-lab/rcp2<file_sep>/setup.py from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Project objective', author='DataKindDC', license='MIT', ) <file_sep>/Code/Munging/ACS/tract_blockgroup_2016/readme.md # Prep ACS Tract & Blockgroup Features ## Introduction This folder contains two scripts: one that downloads raw ACS data, and<br> one that builds standardized features from that raw data. ## Setup * Make sure the necessary Python packages are installed using <br> ```pip install -r requirements.txt``` ## Download Raw Data The ```prep_acs_tract_block.py``` script downloads raw 2016 ACS 5-year<br> data at the Census tract and blockgroup level for the specified states.<br> The state name inputs should be the full name, in camel-case, with spaces <br> removed. For example, ```Arizona``` and ```NewHampshire``` are valid while <br> other variations are not. The data is downloaded from<br> https://www2.census.gov/programs-surveys/acs/summary_file/2016/data/5_year_by_state/ <br> The templates are pulled from <br> https://www2.census.gov/programs-surveys/acs/summary_file/2016/data/2016_5yr_Summary_FileTemplates.zip ### Usage You should only need to download the templates, and check the types, once. For the first state:<br> ```python prep_acs_tract_block.py Alabama --check_types``` <br> This will output col_lookup.csv in the current working directory that is <br> ingested by future calls to the script without the ```--check_types``` option. For subsequent states:<br> ```python prep_acs_tract_block.py Alaska Arkansas --template_folder 'templates/'``` ### Full Specification ``` usage: prep_acs_tract_block.py [-h] [-tf TEMPLATE_FOLDER] [-sp STATE_PATH] [-ct] [-mv MAX_VARS] [-op OUTPUT_PATH] state [state ...] Prep ACS data positional arguments: state state full name optional arguments: -h, --help show this help message and exit -tf TEMPLATE_FOLDER, --template_folder TEMPLATE_FOLDER template folder path. if None, will download to templates/ -sp STATE_PATH, --state_path STATE_PATH raw state data path. if None, will download to state folder -ct, --check_types check data types on load -mv MAX_VARS, --max_vars MAX_VARS approximate number of variables to output per file. the script allows up to 10 pct more to keep the number of files down -op OUTPUT_PATH, --output_path OUTPUT_PATH path to write raw files to ``` ## Build Features The ```build_acs_features.py``` script pulls the variables of interest out of<br> the raw files downloaded by the above script and divides them by the total <br> variables for use in modeling. ### Usage The first task to is build a list of variable names, one per line, from the<br> column lookup file built by ```prep_acs_tract_block.py```. Then run:<br> ```python build_acs_features.py vars_file lookup_file acs_files_path``` ### Full Specification ``` usage: build_acs_features.py [-h] [-o OUTPUT_FILE] vars_file lookup_file acs_files_path Build ACS features positional arguments: vars_file file with list of vars lookup_file column lookup filename acs_files_path folders with raw data optional arguments: -h, --help show this help message and exit -o OUTPUT_FILE, --output_file OUTPUT_FILE output file name (default acs_features) ``` <file_sep>/Code/Munging/ACS/tract_blockgroup_2016/build_acs_features.py # Pull out standardized variables from raw ACS files gathered by prep_acs.py import pandas as pd import numpy as np import logging import argparse import re import os import pdb def get_var_info(var_list, lu_df): """ determine appropriate denominators for creating features :param var_list: list of string variable names :param lu_df: column lookup dataframe ready from output of prep_acs.py :returns: dict with variable info ... keys=type,label,denom,denom_label """ vars = {v: {} for v in var_list} for v in vars.keys(): if v not in lu_df['code'].values: logging.warning('{0} not a valid code'.format(v)) del vars[v] else: # get var type and denominator temp = {'denom': '', 'denom_label': ''} temp['type'] = lu_df.loc[lu_df['code'] == v, 'type'].values[0] temp['label'] = lu_df.loc[lu_df['code'] == v, 'label'].values[0] if temp['type'] == 'Int32': if v[-3:] != '001': temp_denom = v[:-3] + '001' if temp_denom in lu_df['code'].values: temp['denom'] = temp_denom temp['denom_label'] = lu_df.loc[lu_df['code'] == \ temp_denom, 'label'].\ values[0] elif v != 'B00001_001': temp['denom'] = 'B00001_001' temp['denom_label'] = lu_df.loc[lu_df['code'] == \ temp_denom, 'label'].\ values[0] else: temp['denom'] = 'B00001_001' temp['denom_label'] = lu_df.loc[lu_df['code'] == \ temp_denom, 'label'].\ values[0] vars[v] = temp return vars def get_file_info(var_dict, lu_df): """ determine which raw files are needed to pull specified variales :param var_dict: variable info dict returned from get_var_info :param lu_df: column lookup dataframe ready from output of prep_acs.py :returns: list of necessary files, dict of vars per file """ all_vars = list(set(list(var_dict.keys()) + \ [var_dict[x]['denom'] for x in var_dict.keys()])) all_vars = [x for x in all_vars if x] file_to_var = {} for v in all_vars: file_num = lu_df.loc[lu_df['code'] == v, 'output_part_num'].values[0] if file_num in file_to_var.keys(): temp = file_to_var[file_num] file_to_var[file_num] = temp + [v] else: file_to_var[file_num] = [v] all_files = list(file_to_var.keys()) return all_files, file_to_var def build_acs_features_main(vars_file, lookup_file, acs_files_path, output_file='acs_features'): """ create standardized features from raw ACS data :param vars_file: string path and filename to list of variables :param lookup_file: string filename for column lookup file from prep_acs.py :param acs_files_path: string path to folder containing raw ACS data :returns: None """ logging.basicConfig(format='%(asctime)s - %(funcName)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) # get vars into a list try: f = open(vars_file, 'r') acs_vars = f.readlines() acs_vars = [x.strip() for x in acs_vars if x.strip()] except: logging.error('unable to read vars file {0}'.format(vars_file)) return # read column lookup file try: lu = pd.read_csv(lookup_file) except: logging.error('unable to read {0}'.format(lookup_file)) return # get variable and file info vars = get_var_info(acs_vars, lu) all_files, file_to_var = get_file_info(vars, lu) # get list of raw files and states raw_files = os.listdir(acs_files_path) states = list(set([re.sub('^([A-Za-z]+)_.*', '\\1', x) for x in raw_files])) states = [x for x in states if x[0].upper() == x[0]] states = sorted(states) # build df to hold features cols = ['state', 'geoid'] + sorted(list(vars.keys())) comb = pd.DataFrame(columns=cols) # process raw files state by state, doing calculations on each for s in states: logging.info('processing {state}'.format(state=s)) st_raw = pd.DataFrame() for f in all_files: filename = 'acs_output/{state}_raw_{file}.csv'.format(state=s, file=f) rel_cols = ['state', 'geoid'] + file_to_var[f] col_types = {x: float for x in file_to_var[f]} col_types.update({'state': str, 'geoid': str}) temp = pd.read_csv(filename, usecols=rel_cols, dtype=col_types) if st_raw.shape[0] == 0: st_raw = temp.copy() else: st_raw = pd.merge(st_raw, temp, how='outer', on=['state', 'geoid']) # do the calculations on the current state st_raw['state'] = st_raw['state'].str.upper() for v in vars.keys(): denom = vars[v]['denom'] if denom: valid_mask = (st_raw[denom].notnull()) & (st_raw[denom] != 0) st_raw[v] = (st_raw[v] / st_raw[denom]).where(valid_mask) st_raw.loc[~valid_mask, v] = np.nan st_raw = st_raw[cols] comb = comb.append(st_raw) comb = comb.reset_index() comb.drop('index', axis='columns', inplace=True) comb.to_csv(output_file + '.csv', index=False) logging.info('features written to {0}.csv'.format(output_file)) # write out transformations with open(output_file + '_transforms.csv', 'w') as o: for v in vars.keys(): line = '{code} = {label}'.format(code=v, label=vars[v]['label']) if vars[v]['denom']: line += ' ... DIVIDED BY ... {dlabel} ({code})'.\ format(dlabel=vars[v]['denom_label'], code=vars[v]['denom']) o.write(line + '\n') logging.info('transformations written to {0}_transfors.csv'.\ format(output_file)) def build_acs_features_cmd(): parser = argparse.ArgumentParser(description='Build ACS features') parser.add_argument('vars_file', type=str, help='file with list of vars') parser.add_argument('lookup_file', type=str, help='column lookup filename') parser.add_argument('acs_files_path', type=str, help='folders with raw data') parser.add_argument('-o', '--output_file', default='acs_features', help='output file name (default %(default)s)') args = parser.parse_args() build_acs_features_main(args.vars_file, args.lookup_file, args.acs_files_path, output_file=args.output_file) if __name__ == '__main__': build_acs_features_cmd()
5fc1beddda884d212c70701304bc8239fdb41753
[ "Markdown", "Python" ]
3
Python
anilca-lab/rcp2
c4da8f038858c6faa016711be1979de4d544e107
082008d94f8d96a18017a0a9c8066a5da5c26171
refs/heads/main
<repo_name>Ethan-Georlette/touch-nums<file_sep>/js/main.js 'use strict' var gNums = []; var gCurrNum = 1; var gStartTimer; function initGame() { gCurrNum = 1; gNums = createArr(); renderGame(); } function renderGame(num = 16) { gNums = createArr(num); var elTable = document.querySelector('table'); var strTableHTML = '<tr>\n'; for (var i = 0; i < num; i++) { var rndNum = drawNum(); strTableHTML += '\t<th onclick="isRight(this)" id="' + rndNum + '">' + rndNum + '</th>\n'; if ((i + 1) % Math.sqrt(num) === 0) { strTableHTML += '</tr>\n <tr>\n' } } // console.log(strTableHTML); // console.log(gNums); gNums = createArr(num); // console.log(gNums); elTable.innerHTML = strTableHTML; } function isRight(elCell) { var currCellNum = parseInt(elCell.id); if (!gNums[currCellNum - 1]) { console.log(currCellNum); return; } if (gCurrNum === currCellNum) { if (currCellNum === 1) { timerStart(); gStartTimer = Date.now(); } gNums[currCellNum - 1] = 0; gCurrNum++; elCell.style.opacity = '0.2'; } // console.logisWin(currCellNum)) } function timerStart() { var elTimer = document.querySelector('.timer'); var myVal = setInterval(function () { var time=((Date.now()-gStartTimer)/1000).toFixed(3) elTimer.textContent = time + ''; if (isWin()) { gameTimer(time) clearInterval(myVal); } }, 81) } function isWin() { if (!gNums[gNums.length - 1]) { var elResBtn = document.querySelector('.resBtn'); elResBtn.innerText = 'Play again'; return true; } return false; } function gameTimer(time) { var elWonMsg = document.querySelector('.winnerMsg'); elWonMsg.style.diplay = 'block' elWonMsg.innerHTML = '<h1> Good job! </br> Your time is:' + time + '</h1>'; } function restartGame(){ window.location="index.html"; } function createArr(count = 16) { var nums = []; for (var i = 1; i <= count; i++) { nums.push(i); } return nums; } function drawNum(nums = gNums) { var randIdx = getRandom(1, nums.length); return nums.splice(randIdx - 1, 1); } function getRandom(min, max) { return Math.floor(Math.random() * (max - min)) + min; }
edbd04064bd7dbbac0d1cae7fc47b353438a3bb3
[ "JavaScript" ]
1
JavaScript
Ethan-Georlette/touch-nums
d3aa982b94715dc440b12150af3d81fe04301044
e806dc24a8283ac6462450abc117d607013507d2
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: joao.nivaldo * Date: 30/10/2014 * Time: 19:01 */ class Cliente { private $id; private $nome; private $cpf; private $endereco; private $cidade; private $uf; private $telefone; /** * @return mixed */ public function getCidade() { return $this->cidade; } /** * @param mixed $cidade */ public function setCidade($cidade) { $this->cidade = $cidade; } /** * @return mixed */ public function getCpf() { return $this->cpf; } /** * @param mixed $cpf */ public function setCpf($cpf) { $this->cpf = $cpf; } /** * @return mixed */ public function getEndereco() { return $this->endereco; } /** * @param mixed $endereco */ public function setEndereco($endereco) { $this->endereco = $endereco; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getNome() { return $this->nome; } /** * @param mixed $nome */ public function setNome($nome) { $this->nome = $nome; } /** * @return mixed */ public function getTelefone() { return $this->telefone; } /** * @param mixed $telefone */ public function setTelefone($telefone) { $this->telefone = $telefone; } /** * @return mixed */ public function getUf() { return $this->uf; } /** * @param mixed $uf */ public function setUf($uf) { $this->uf = $uf; } /*function __construct($strNome = "") { $this->nome = $strNome; }*/ public function ordena($tipo='asc') { } }
d0a2d99aa54845ca401cc29cf06e45e76deb118c
[ "PHP" ]
1
PHP
joaonivaldo/gestaodeclientes
ad2b2842e7ee3a327b559ce45ecb6da2f216fa23
57654d7ce8f910463c84bcbf8b4db8ae470f0c23
refs/heads/master
<repo_name>Marco-Ba/Disp7seg<file_sep>/main.c /* * File: main.c * Author: 21193066 * * Created on 24 de Fevereiro de 2021, 14:05 */ #include <xc.h> #include "config.h" #include "delay.h" #include "display7seg.h" #include "botoes.h" void main(void) { char cont; char estado = 0; display7seg_init(); botoes_init(); while ( 1 ) { switch (estado) { case 0: if( s1() == 1) estado = 1; break; case 1: if( s1() == 0) estado = 2; break; case 2: ++cont; estado = 0; break; } display7seg( cont ); if( cont >= 10 ) cont = 0; if( cont < 0 ) cont = 9; } }
6596dd0def911c4322aba07d464665feac1c884c
[ "C" ]
1
C
Marco-Ba/Disp7seg
ccdaf4a4bfcb3935df0d56dd37b74d2421f5f6c3
d1d4129e59f00a0191ae6eccb0170f606926c2a7
refs/heads/main
<repo_name>johnsonlee/translator<file_sep>/src/main/java/io/johnsonlee/android/translate/TranslateAssistant.kt package io.johnsonlee.android.translate import android.content.Context import android.content.SharedPreferences import android.util.SparseArray import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.app.ComponentActivity import androidx.core.content.edit import androidx.core.util.set import androidx.core.view.marginLeft import androidx.core.view.marginTop import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.google.mlkit.nl.translate.Translation import com.google.mlkit.nl.translate.Translator import com.google.mlkit.nl.translate.TranslatorOptions import io.johnsonlee.android.translate.widget.DraggableLayout import java.lang.ref.WeakReference private const val PREF_NAME = "translate-assistant" private const val KEY_X = "x" private const val KEY_Y = "y" internal class TranslateAssistant( private val activity: ComponentActivity, private val options: TranslatorOptions ) : LifecycleObserver { // View ref => text hash code private val cache: SparseArray<Int> = SparseArray(100) private val clickListener: View.OnClickListener = View.OnClickListener { it.rootView.findViewByType<TextView>().filter(View::isShown).forEach { v -> val str = v.text.toString() val hash = System.identityHashCode(v) if (v.getTag(R.id.TAG_TRANSLATED) == true && str.hashCode() == cache[hash]) { return@forEach } cache[hash] = str.hashCode() val ref = WeakReference<TextView>(v) translator.translate(v.text.toString()).addOnSuccessListener { result -> v.setTag(R.id.TAG_TRANSLATED, true) ref.get()?.apply { text = result cache[System.identityHashCode(this)] = result.hashCode() } } } } private val dragListener: DraggableLayout.OnDragListener = object : DraggableLayout.OnDragListener { override fun onDragEnd(v: View) = pref.edit { putInt(KEY_X, v.marginLeft) putInt(KEY_Y, v.marginTop) } } private val pref: SharedPreferences by lazy { activity.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) } private val translator: Translator by lazy { Translation.getClient(options) } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { val content = activity.window.findViewById<ViewGroup>(android.R.id.content) ?: return activity.findViewById<ViewGroup>(R.id.google_translate_assistant)?.let { return } val layout = activity.layoutInflater.inflate(R.layout.translate_assistant, content, false) layout.findViewById<DraggableLayout>(R.id.google_translate_assistant).apply { initX = { pref.getInt(KEY_X, 0) } initY = { pref.getInt(KEY_Y, activity.findViewById<View>(android.R.id.content).height shr 1) } onClick = clickListener onDrag = dragListener content.addView(layout) } layout.bringToFront() } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { activity.findViewById<DraggableLayout>(R.id.google_translate_assistant) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { cache.clear() translator.close() } }<file_sep>/build.gradle import static org.gradle.kotlin.dsl.KotlinDependencyExtensionsKt.embeddedKotlinVersion buildscript { ext.kotlin_version = embeddedKotlinVersion ext.booster_version = '3.0.0' repositories { mavenLocal() google() mavenCentral() jcenter() maven { url 'https://plugins.gradle.org/m2/' } } dependencies { classpath "com.android.tools.build:gradle:4.1.1" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.dokka:dokka-gradle-plugin:1.4.10.2" classpath "io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.21.2" classpath "de.marcphilipp.gradle:nexus-publish-plugin:0.4.0" } } apply plugin: 'maven' apply plugin: 'signing' apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' apply plugin: 'org.jetbrains.dokka' apply plugin: 'io.codearte.nexus-staging' apply plugin: 'de.marcphilipp.nexus-publish' group = 'io.johnsonlee.translate' version = '1.0.0' android { compileSdkVersion 30 buildToolsVersion "29.0.3" defaultConfig { minSdkVersion 16 targetSdkVersion 30 versionCode 1 versionName project.version testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" consumerProguardFiles "consumer-rules.pro" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } defaultPublishConfig project.name.endsWith('-SNAPSHOT') ? 'debug' : 'release' compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } } repositories { mavenLocal() google() mavenCentral() jcenter() } dependencies { kapt 'androidx.lifecycle:lifecycle-common-java8:2.2.0' api "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" api 'androidx.cardview:cardview:1.0.0' api 'androidx.core:core-ktx:1.3.2' api 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' api 'androidx.activity:activity-ktx:1.1.0' implementation 'com.google.mlkit:translate:16.1.1' dokkaHtmlPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:1.4.10.2") } def OSSRH_USERNAME = project.properties['OSSRH_USERNAME'] ?: System.getenv('OSSRH_USERNAME') def OSSRH_PASSWORD = project.properties['OSSRH_PASSWORD'] ?: System.getenv('OSSRH_PASSWORD') dokkaHtml.configure { dokkaSourceSets { named("main") { noAndroidSdkLink.set(false) } } } task androidJavadocs(type: Javadoc, dependsOn: dokkaHtml) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) android.libraryVariants.all { variant -> if (variant.name == 'release') { owner.classpath += variant.javaCompileProvider.get().classpath } } exclude '**/R.html', '**/R.*.html', '**/index.html' } task androidJavadocsJar(type: Jar, dependsOn: dokkaHtml) { archiveClassifier.set('javadoc') from dokkaHtml.outputDirectory } task androidSourcesJar(type: Jar) { archiveClassifier.set('sources') from android.sourceSets.main.java.srcDirs } afterEvaluate { publishing { publications { release(MavenPublication) { from components.release } debug(MavenPublication) { from components.debug } withType(MavenPublication).configureEach { groupId = project.group artifactId = project.name version = project.version artifact androidSourcesJar artifact androidJavadocsJar pom { name = project.name url = "https://github.com/johnsonlee/${project.name}" description = project.description ?: project.name scm { connection = "scm:git:git://github.com/johnsonlee/${project.name}.git" developerConnection = "scm:git:<EMAIL>:johnsonlee/${project.name}.git" url = "https://github.com/johnsonlee/${project.name}" } licenses { license { name = 'Apache License' url = 'https://www.apache.org/licenses/LICENSE-2.0' } } withXml { xml -> xml.asNode().appendNode('developers').appendNode('developer').with { appendNode('id', 'johnsonlee') appendNode('email', '<EMAIL>') } } } } } } } nexusPublishing { repositories { sonatype { username = OSSRH_USERNAME password = <PASSWORD> } } } nexusStaging { packageGroup = "io.johnsonlee" username = OSSRH_USERNAME password = <PASSWORD> numberOfRetries = 50 delayBetweenRetriesInMillis = 3000 } signing { sign publishing.publications } <file_sep>/src/main/java/io/johnsonlee/android/translate/widget/DraggableLayout.kt package io.johnsonlee.android.translate.widget import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import androidx.core.view.updateLayoutParams private const val TAG = "DraggableLayout" open class DraggableLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { var initX: () -> Int = { 0 } var initY: () -> Int = { 0 } private var x: Int = 0 private var y: Int = 0 private var layouted: Boolean = false private var dragStar: Boolean = false private var clickListener: OnClickListener? = null private var dragListener: OnDragListener? = null private var longClickListener: OnLongClickListener? = null init { super.setOnLongClickListener { v -> dragStar = longClickListener?.onLongClick(v) ?: layoutParams is MarginLayoutParams if (dragStar) { dragListener?.onDragStart(v) } Log.i(TAG, "drag start $dragStar") dragStar } } var onClick: View.OnClickListener? get() = null set(value) { super.setOnClickListener(value) } var onDrag: OnDragListener? get() = dragListener set(value) { dragListener = value } private val boundary: IntArray get() { val p = parent as View val hp = p.paddingLeft + p.paddingRight val vp = p.paddingTop + p.paddingBottom val right = p.width - hp - width val bottom = p.height - vp - height return intArrayOf(0, 0, right, bottom) } override fun setOnLongClickListener(listener: OnLongClickListener?) { longClickListener = listener } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) if (!layouted) { val (l, t, r, b) = boundary post { updateLayoutParams<MarginLayoutParams> { leftMargin = initX().coerceAtLeast(l).coerceAtMost(r) topMargin = initY().coerceAtLeast(t).coerceAtMost(b) } } } layouted = true } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { x = event.x.toInt() y = event.y.toInt() } if (dragStar) { when (event.action) { MotionEvent.ACTION_MOVE -> { val (_, _, right, bottom) = boundary updateLayoutParams<MarginLayoutParams> { topMargin = (topMargin + event.y.toInt() - y).coerceAtLeast(0).coerceAtMost(bottom) leftMargin = (leftMargin + event.x.toInt() - x).coerceAtLeast(0).coerceAtMost(right) } dragListener?.onDragging(this, event) return true } MotionEvent.ACTION_UP -> { dragStar = false dragListener?.onDragEnd(this) } } } return super.onTouchEvent(event) } interface OnDragListener { fun onDragStart(v: View) = Unit fun onDragging(v: View, event: MotionEvent) = Unit fun onDragEnd(v: View) = Unit } }<file_sep>/src/main/java/io/johnsonlee/android/translate/TranslateProvider.kt package io.johnsonlee.android.translate import android.annotation.SuppressLint import android.app.Activity import android.app.Application import android.content.ContentProvider import android.content.ContentValues import android.database.Cursor import android.net.Uri import android.os.Bundle import android.util.Log import androidx.fragment.app.FragmentActivity import com.google.android.gms.tasks.OnCanceledListener import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.mlkit.common.MlKitException import com.google.mlkit.common.model.DownloadConditions import com.google.mlkit.nl.translate.TranslateLanguage import com.google.mlkit.nl.translate.Translation import com.google.mlkit.nl.translate.TranslatorOptions class TranslateProvider : ContentProvider(), Application.ActivityLifecycleCallbacks, OnCanceledListener, OnSuccessListener<Any?>, OnFailureListener { private val options = TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.KOREAN) .setTargetLanguage(TranslateLanguage.CHINESE) .build() @SuppressLint("ApplySharedPref") override fun onCreate(): Boolean { Translation.getClient(options) .downloadModelIfNeeded(DownloadConditions.Builder().requireWifi().build()) .addOnCanceledListener(this) .addOnSuccessListener(this) .addOnFailureListener(this) (context?.applicationContext as? Application)?.registerActivityLifecycleCallbacks(this) return true } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null override fun getType(uri: Uri): String? = null override fun insert(uri: Uri, values: ContentValues?): Uri? = null override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = 0 override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?) = 0 override fun onActivityPaused(activity: Activity) = Unit override fun onActivityStarted(activity: Activity) = Unit override fun onActivityDestroyed(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit override fun onActivityStopped(activity: Activity) = Unit override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (activity is FragmentActivity) { activity.lifecycle.addObserver(TranslateAssistant(activity, options)) } } override fun onActivityResumed(activity: Activity) = Unit override fun onCanceled() { Log.i(TAG, "MlKit downloading canceled") } override fun onSuccess(o: Any?) { Log.i(TAG, "MlKit download success") } override fun onFailure(e: Exception) { val cause = e.cause val code = (cause as? MlKitException)?.errorCode ?: MlKitException.UNKNOWN Log.e(TAG, "MlKit downloading failed: $code", cause) } companion object { private const val TAG = "TranslateProvider" } }<file_sep>/README.md # translator Translator is an Android library for in-app UI translation, it uses [ML Kit Text Translation](https://developers.google.com/ml-kit/language/translation) which powered by Google team. ![Screenshot](./art/screenshot.gif) ## Getting Started ```gradle dependencies { implementation "io.johnsonlee.translate:translator:1.0.0" } ``` <file_sep>/app/src/main/java/io/johnsonlee/android/translate/app/MainActivity.kt package io.johnsonlee.android.translate.app import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.fragment.app.FragmentActivity class MainActivity : FragmentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) findViewById<TextView>(R.id.txt_greeting).setOnClickListener { Toast.makeText(this, (it as TextView).text, Toast.LENGTH_SHORT).show() } } }<file_sep>/gradle.properties systemProp.org.gradle.internal.publish.checksums.insecure=true android.useAndroidX=true <file_sep>/src/main/java/io/johnsonlee/android/translate/View.kt package io.johnsonlee.android.translate import android.view.View import android.view.ViewGroup import java.util.Stack inline fun <reified T : View> View.findViewByType(): Array<T> { val views = mutableListOf<T>() val stack = Stack<View>() stack.push(this) while (stack.isNotEmpty()) { when (val v = stack.pop()) { is ViewGroup -> { for (i in 0 until v.childCount) { stack.push(v.getChildAt(i)) } } else -> if (v is T) { views += v } } } return views.toTypedArray() }
fe49d4fa0004d247140858750bbf8d53ab663445
[ "Markdown", "Kotlin", "INI", "Gradle" ]
8
Kotlin
johnsonlee/translator
46776d3d01ad9c3af3a828593e5845320f7b5608
499fc7c9237bfbbb1868e74298aabfa319350129
refs/heads/master
<file_sep># coding-the-matrix coding the matrix by Python this is my homework for the Matrix coding course. <file_sep>from image_mat_util import * from geometry_lab import * import math pmat_cmat = file2mat("pic.png") #mat2display(pmat_cmat[0], pmat_cmat[1]) #print(translation(2,3)) #print(rotation(math.pi/6)) #mat2display(rotate_about(225,225,math.pi/2)*pmat_cmat[0],scale_color(1,0.5,0.3)*pmat_cmat[1]) mat2display(reflect_about((0,115),(225,115))*pmat_cmat[0],pmat_cmat[1]) <file_sep>from mat import Mat from vec import * from matutil import rowdict2mat import math ## Task 1 def identity(labels = {'x','y','u'}): ''' In case you have never seen this notation for a parameter before, the way it works is that identity() now defaults to having labels equal to {'x','y','u'}. So you should write your procedure as if it were defined 'def identity(labels):'. However, if you want the labels of your identity matrix to be {'x','y','u'}, you can just call identity(). Additionally, if you want {'r','g','b'}, or another set, to be the labels of your matrix, you can call identity({'r','g','b'}). ''' return Mat((labels,labels),{(x,x):1 for x in labels}) ## Task 2 def translation(x,y): ''' Input: An x and y value by which to translate an image. Output: Corresponding 3x3 translation matrix. ''' return Mat(({'x','y','u'},{'x','y','u'}),{('x','x'):1,('y','y'):1,('u','u'):1, ('x','u'):x, ('y','u'):y}) ## Task 3 def scale(a, b): ''' Input: Scaling parameters for the x and y direction. Output: Corresponding 3x3 scaling matrix. ''' return Mat(({'x','y','u'},{'x','y','u'}),{('x','x'):a,('y','y'):b,('u','u'):1}) ## Task 4 def rotation(angle): ''' Input: An angle in radians to rotate an image. Output: Corresponding 3x3 rotation matrix. Note that the math module is imported. ''' return Mat(({'x','y','u'},{'x','y','u'}),{('x','x'):math.cos(angle),('y','y'):math.cos(angle),('x','y'):-math.sin(angle),('y','x'):math.sin(angle),('u','u'):1}) ## Task 5 def rotate_about(x,y,angle): ''' Input: An x and y coordinate to rotate about, and an angle in radians to rotate about. Output: Corresponding 3x3 rotation matrix. It might be helpful to use procedures you already wrote. ''' # first: center at (x,y) by translation(-x,-y) # second: rotation by angle # third: translation back: translation(x,y) return translation(x,y)*rotation(angle)*translation(-x,-y) ## Task 6 def reflect_y(): ''' Input: None. Output: 3x3 Y-reflection matrix. ''' return scale(-1, 1) ## Task 7 def reflect_x(): ''' Inpute: None. Output: 3x3 X-reflection matrix. ''' return scale(1, -1) ## Task 8 def scale_color(scale_r,scale_g,scale_b): ''' Input: 3 scaling parameters for the colors of the image. Output: Corresponding 3x3 color scaling matrix. ''' return Mat(({'r','g','b'},{'r','g','b'}),{('r','r'):scale_r,('g','g'):scale_g,('b','b'):scale_b}) ## Task 9 def grayscale(): ''' Input: None Output: 3x3 greyscale matrix. ''' return rowdict2mat({color:Vec({'r','g','b'},{'r':77/256,'g':151/256,'b':28/256}) for color in {'r','g','b'}}) ## Task 10 def reflect_about(p1,p2): ''' Input: 2 points that define a line to reflect about. Output: Corresponding 3x3 reflect about matrix. ''' #step1: translate by -P2 (could use P1 instead) #step2: rotate by -theta (theta is the angle between the x-axis and the line through the two given points) #step3: reflect through x-axis #step4: rotate by theta #step5: translate by P2 (could use P1 instead) x1, y1, x2, y2 = p1[0], p1[1], p2[0], p2[1] theta = math.atan2(y2 - y1, x2 - x1) return translation(x2,y2)*rotation(theta)*reflect_x()*rotation(-theta)*translation(-x2,-y2) <file_sep> from vec import Vec from mat import Mat from matutil import * from bitutil import noise from GF2 import one from ecc_lab import * from bitutil import * H = listlist2mat([[0,0,0,one,one,one,one],[0,one,one,0,0,one,one],[one,0,one,0,one,0,one]]) non_codeword = Vec({0,1,2,3,4,5,6}, {0: one, 1:0, 2:one, 3:one, 4:0, 5:one, 6:one}) #print(find_error(H*non_codeword)) code_word = Vec({0,1,2,3,4,5,6}, {0: one, 1:0, 2:one, 3:one, 4:0, 5:one}) R = listlist2mat([[0,0,0,0,0,0,one],[0,0,0,0,0,one,0],[0,0,0,0,one,0,0],[0,0,one,0,0,0,0]]) #print( R * code_word ) #Vec({0, 1, 2, 3, 4, 5, 6},{3: one}) str = "i am <NAME>i @ 2013!" bits = str2bits(str) str_back = bits2str(bits) print(str) print(len(str)) print(bits) print() print(len(bits)) matrix_of_bits = bits2mat(bits) print(matrix_of_bits) bits_back = mat2bits(matrix_of_bits) print(bits_back) print(str_back) print() print(len(str_back)) # try the noise P = bits2mat(str2bits(str)) C = G*P f = 0.5 E = noise(C, f) C_tilde = C + E C_correct = correct(C_tilde) codeword_decode = R*C_correct Rcv_str = bits2str(mat2bits(R*C_tilde)) ham_correct_str = bits2str(mat2bits(codeword_decode)) print("[original string]:") print(str) print("Prob is ",f) print("[rcved string]:") print(Rcv_str.encode('utf-8')) print("[hamming corrected string]:") print(ham_correct_str.encode('utf-8')) <file_sep>from mat import Mat from hw3 import * #M = Mat(({0, 1, 2}, {0, 1, 2}), {(0, 0): -1, (0, 1): 1, (0, 2): 2, (1, 0): 1, (1, 1): 2, (1, 2): 3, (2, 0): 2, (2, 1): 2, (2, 2): 1}) #v = Vec({0, 1, 2}, {0:1,1:2}) #vec = lin_comb_mat_vec_mult(M,v) #print (vec) A = Mat(({0, 1}, {'a', 'b', 'c'}), {(0, 'a'): 1, (0, 'b'): 2, (0, 'c'): 3, (1, 'a'): 4, (1, 'b'): 5}) B = Mat(({'a', 'b', 'c'}, {'x', 'y'}), {('a', 'x'): 1, ('b', 'y'): 1, ('c', 'x'): 1}) print(A) print(B) print(dot_prod_mat_mat_mult(A,B)) <file_sep>from vec import Vec from matutil import rowdict2mat def read_training_data(fname, features=None): """Given a file in appropriate format, returns the triple (feature_vectors, patient_diagnoses, D) feature_vectors is a dictionary that maps integer patient identification numbers to D-vectors where D is the set of feature labels, and patient_diagnoses is a dictionary mapping patient identification numbers to {+1, -1}, where +1 indicates malignant and -1 indicates benign. """ file = open(fname) params = ["radius", "texture", "perimeter","area","smoothness","compactness","concavity","concave points","symmetry","fractal dimension"]; stats = ["(mean)", "(stderr)", "(worst)"] feature_labels = set([y+x for x in stats for y in params]) feature_map = {params[i]+stats[j]:j*len(params)+i for i in range(len(params)) for j in range(len(stats))} if features is None: features = feature_labels feature_vectors = {} patient_diagnoses = {} for line in file: row = line.split(",") patient_ID = int(row[0]) patient_diagnoses[patient_ID] = -1 if row[1]=='B' else +1 feature_vectors[patient_ID] = Vec(features, {f:float(row[feature_map[f]+2]) for f in features}) return rowdict2mat(feature_vectors), Vec(set(patient_diagnoses.keys()), patient_diagnoses) def read_unclassified_data(fname): return read_training_data(fname)[0] <file_sep>from GF2 import * import itertools def gen_comb(input_vector): D = { 'a':[one,one,one,0,0,0,0], 'b':[0,one,one,one,0,0,0], 'c':[0,0,one,one,one,0,0], 'd':[0,0,0,one,one,one,0], 'e':[0,0,0,0,one,one,one], 'f':[0,0,0,0,0,one,one] } comb = set() for L in range(2, len(D.keys())+1): for subset in itertools.combinations(D.keys(), L): sub = [D[s] for s in subset] t = [0]*len(sub[0]) for p in range(len(sub)): t = [t[i] + sub[p][i] for i in range(len(t))] if t == list(input_vector): comb.add(subset) return comb u_0010010 = [0,0,one,0,0,one,0] u_0100010 = [0,one,0,0,0,one,0] print(gen_comb(u_0010010)) print("\n") print(gen_comb(u_0100010))<file_sep>d = {0:1000.0, 1:1200.50, 2:990} names = ['Larry', 'Curly', 'Moe'] listdict2dict = {names[k]:v for (k,v) in d.items() } print (listdict2dict) <file_sep> from GF2 import one from math import sqrt, pi from matutil import coldict2mat from solver import solve from vec import Vec from hw4 import * vec1 = Vec({0,1,2,3},{1:one,3:one}) vec2 = Vec({0,1,2,3},{2:one}) vec3 = Vec({0,1,2,3},{0:one,3:one}) vec4 = Vec({0,1,2,3},{0:one,1:one,2:one,3:one}) veclist = [vec1,vec2,vec3,vec4] avec = Vec({0,1,2,3},{0:one,1:one}) bvec = Vec({0,1,2,3},{0:one,2:one}) cvec = Vec({0,1,2,3},{0:one}) zerovec = Vec({0,1,2,3},{}) for i1 in range(0,2): for i2 in range(0,2): for i3 in range(0,2): for i4 in range(0,2): if i1*vec1+i2*vec2+i3*vec3+i4*vec4 == avec: pass #print ("avec:") #print (i1,i2,i3,i4) if i1*vec1+i2*vec2+i3*vec3+i4*vec4 == bvec: pass #print ("bvec:") #print (i1,i2,i3,i4) if i1*vec1+i2*vec2+i3*vec3+i4*vec4 == cvec: pass #print ("cvec:") #print (i1,i2,i3,i4) #problem 9 vec_a1 = Vec({0,1,2,3},{0:one,1:one,2:one,3:one}) vec_a2 = Vec({0,1,2,3},{0:one,2:one}) vec_a3 = Vec({0,1,2,3},{1:one,2:one}) vec_a4 = Vec({0,1,2,3},{1:one,3:one}) vec_b1 = Vec({0,1,2,3},{3:one}) vec_b2 = Vec({0,1,2,3},{2:one}) vec_b3 = Vec({0,1,2,3},{0:one,1:one,3:one}) vec_b4 = Vec({0,1,2,3},{0:one,1:one,2:one,3:one}) vec_c1 = Vec({0,1,2,3,4},{0:one,1:one,3:one,4:one}) vec_c2 = Vec({0,1,2,3,4},{2:one}) vec_c3 = Vec({0,1,2,3,4},{2:one,3:one,4:one}) vec_c4 = Vec({0,1,2,3,4},{0:one,2:one,3:one,4:one}) vec_c5 = Vec({0,1,2,3,4},{0:one,1:one,2:one,3:one,4:one}) veclist_a = [vec_a1,vec_a2,vec_a3,vec_a4] veclist_b = [vec_b1,vec_b2,vec_b3,vec_b4] veclist_c = [vec_c1,vec_c2,vec_c3,vec_c4,vec_c5] from itertools import * A = [0,1] zerovec = Vec({0,1,2,3},{}) zerovec_c = Vec({0,1,2,3,4},{}) for Alpha in product(A,repeat=len(veclist_c)): if sum(Alpha) > 0: if sum([Alpha[i]*veclist_c[i] for i in range(len(veclist_c))]) == zerovec_c: #print(Alpha) #exit() pass # problem 16 a0 = Vec({'a','b','c','d'}, {'a':1}) a1 = Vec({'a','b','c','d'}, {'b':1}) a2 = Vec({'a','b','c','d'}, {'c':1}) a3 = Vec({'a','b','c','d'}, {'a':1,'c':3}) L = [a0,a1,a2,a3] #print(is_superfluous(L, 3)) #True #print(is_superfluous([a0,a1,a2,a3], 3)) #True #print(is_superfluous([a0,a1,a2,a3], 0)) #True #print(is_superfluous([a0], 0)) #False #problem 17 a0 = Vec({'a','b','c','d'}, {'a':1}) a1 = Vec({'a','b','c','d'}, {'b':1}) a2 = Vec({'a','b','c','d'}, {'c':1}) a3 = Vec({'a','b','c','d'}, {'a':1,'c':3}) #superset_basis([a0, a3], [a0, a1, a2]) == [Vec({'d', 'b', 'c', 'a'},{'a': 1}), Vec({'d', 'b', 'c', 'a'},{'c': 3, 'a': 1}), Vec({'d', 'b', 'c', 'a'},{'b': 1})] #True print(superset_basis([a0, a3], [a0, a1, a2]))<file_sep>from GF2 import * def vec_dot_product(v,u): t = 0; for i in range(len(v)): t = t + v[i]*u[i] return t u1 = [one,one,0,0] u2 = [one,0,one,0] u3 = [one,one,one,one] all_set = ([x1,x2,x3,x4] for x1 in[one,0] for x2 in[one,0] for x3 in[one,0] for x4 in[one,0]) for vec in all_set: if one == vec_dot_product(vec,u1) and one == vec_dot_product(vec,u2) and one == vec_dot_product(vec,u3) and one == vec_dot_product(vec,[one,one,one,one]): print(vec) exit() <file_sep>def myFilter(L, num): return [x for x in L if 0 == x%num] def myLists(L): return [[y+1 for y in range(x)] for x in L] def myConcat(L): current = "" for x in L: current = current + str(x) return current print(myConcat([1,2,5]))<file_sep>from vec import Vec from mat import Mat class DummyItem(object): def __init__(self): self.multiplications = [] def __getattr__(self, _): return self def __getitem__(self, _): return self def __mul__(self, v): self.multiplications.append(v) return v def __rmul__(self, v): self.multiplications.append(v) return v dummy = DummyItem() class Tester(object): def __init__(self, labels): self.D = labels self.right = [] self.left = [] def __getitem__(self, k): return 0 def __setitem__(self, k, v): pass class VecTester(Tester): def __mul__(self, v): self.right.append(v) vn = type(v).__name__ if vn == 'Vec': return 0 if vn == 'Mat': return Vec(v.D[1], {}) def __rmul__(self, v): self.left.append(v) vn = type(v).__name__ if vn == 'Vec': return 0 if vn == 'Mat': return Vec(v.D[0], {}) class MatTester(Tester): def __mul__(self, v): self.right.append(v) vn = type(v).__name__ if vn == 'Vec': return Vec(self.D[0], {}) if vn == 'Mat': return Vec(self.D[1], {}) def __rmul__(self, v): self.left.append(v) vn = type(v).__name__ if vn == 'Vec': return Vec(self.D[1], {}) if vn == 'Mat': return Vec((v.D[0], self.D[1]), {}) <file_sep># Please fill out this stencil and submit using the provided submission script. ## Problem 1 def myFilter(L, num): return [x for x in L if 0 != x%num] ## Problem 2 def myLists(L): return [[y+1 for y in range(x)] for x in L] ## Problem 3 def myFunctionComposition(f, g): return {x:g[f[x]] for x in f if f[x] in g } ## Problem 4 # Please only enter your numerical solution. complex_addition_a = 5 + 3j complex_addition_b = 0 + 1j complex_addition_c = -1 + .001j complex_addition_d = .001 + 9j ## Problem 5 GF2_sum_1 = 1 GF2_sum_2 = 0 GF2_sum_3 = 0 ## Problem 6 def mySum(L): current = 0 for x in L: current = current + x return current ## Problem 7 def myProduct(L): current = 1 for x in L: current = current * x return current ## Problem 8 def myMin(L): current = -999999999 if len(L) > 0: current = L[0] for x in L: if current > x: current = x return current ## Problem 9 def myConcat(L): current = "" for x in L: current = current + x return current ## Problem 10 def myUnion(L): current = set([]) for x in L: current = current | x return current<file_sep>from vec import * from hw2 import * D = {'a','b','c'} v1 = Vec(D, {'a': 1}) v2 = Vec(D, {'a': 0, 'b': 1}) v3 = Vec(D, { 'b': 2}) v4 = Vec(D, {'a': 10, 'b': 10}) vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 1}) #True print(vec_sum([v1, v2, v3, v4], D) == Vec(D, {'b': 13, 'a': 12})) <file_sep>import math def vec_dot_product(v,u): t = 0; for i in range(len(v)): t = t + v[i]*u[i] return t u = [-math.sqrt(2)/2,math.sqrt(2)/2] v = [math.sqrt(2)/2,-math.sqrt(2)/2] print(vec_dot_product(u,v))<file_sep>from GF2 import * def vec_dot_product(v,u): t = 0; for i in range(len(v)): t = t + v[i]*u[i] return t u1 = [2,3,-4,1] u2 = [1,-5,2,0] u3 = [4,1,-1,-1] all_set = ([x1,x2,x3,x4] for x1 in range(-10,10) for x2 in range(-10,10) for x3 in range(-10,100) for x4 in range(-10,10)) for vec in all_set: if 10 == vec_dot_product(vec,u1) and 35 == vec_dot_product(vec,u2) and 8 == vec_dot_product(vec,u3): print(vec) exit()
262567492288cc795b29d6a0e267759a6af17c29
[ "Markdown", "Python" ]
16
Markdown
mtfelix/coding-the-matrix
c959f4e49749e3526147d0ca732ec85277226d1d
fb31de741b6ac0214d69dd9cae4f2950fae00226
refs/heads/master
<file_sep>function changeListOrder(col, dir, controller, admin){ post_data={format: 'JSON', col: col, dir: dir}; var url=admin+"/"+controller+"/ajax_change_list_order"; $.post(url, post_data); var redir = admin+'/'+controller; location.href = redir; }<file_sep>//========================================================= // FreshBooks Calendar Widget // // http://www.freshbooks.com // (c) 2007 2ndSite Inc. //--------------------------------------------------------- var FbCalendar = { idCounter: 0, // Index of last initialized calendar instance instances: [], // Array of calendar instances hashInstances: {}, heightOffset: 2, // Number of pixels formatType: 0, // Display format type -- see: this.formatDate() borderColor: '#dddddd', weekDayNames: [ "S", "M", "T", "W", "T", "F", "S" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // Constants SINGLE: 1, DOUBLE: 2, LEFT: 4, RIGHT: 8, ABOVE: 16, BELOW: 32, BOTH: 0, PREV_ONLY: 1, NEXT_ONLY: 2, get: function(id) { if (typeof(id) == 'number') return this.instances[id]; else return this.hashInstances[id]; }, setFormat: function(index) { this.formatType = index; }, formatDate: function(date) { switch (this.formatType) { case 0: return formatDate(date, 'MM/dd/yy'); case 1: return formatDate(date, 'MM/dd/yyyy'); case 2: return formatDate(date, 'dd/MM/yy'); case 3: return formatDate(date, 'dd/MM/yyyy'); case 4: return formatDate(date, 'yy-MM-dd'); case 5: return formatDate(date, 'yyyy-MM-dd'); } }, datesEqual: function(d1, d2) { return !(d1 > d2) && !(d1 < d2); }, // Attempt to pull the month/year from the dateString according to // the current format type -- return value is a hash extractDate: function(dateString) { var month = null, year = null; day = null; var thisYear = (new Date).getFullYear(); var thisCentury = Math.round(thisYear / 100); var lastCentury = thisCentury - 1; var dateSplit = this.formatType < 4 ? dateString.split('/') : dateString.split('-') switch (this.formatType) { case 0: // mm/dd/yy month = dateSplit[0]; year = dateSplit[2]; day = dateSplit[1]; if (year) { year = year > '50' ? lastCentury + year : thisCentury + year; } break; case 1: // mm/dd/yyyy month = dateSplit[0]; year = dateSplit[2]; day = dateSplit[1]; break; case 2: // dd/mm/yy month = dateSplit[1]; year = dateSplit[2]; day = dateSplit[0]; if (year) { year = year > '50' ? lastCentury + year : thisCentury + year; } break; case 3: // dd/mm/yyyy month = dateSplit[1]; year = dateSplit[2]; day = dateSplit[0]; break; case 4: // yy-mm-dd month = dateSplit[1]; year = dateSplit[0]; day = dateSplit[2]; if (year) { year = year > '50' ? lastCentury + year: thisCentury + year; } break; case 5: // yyyy-mm-dd month = dateSplit[1]; year = dateSplit[0]; day = dateSplit[2]; break; } // Convert to integers if (month != null) { month = parseInt(month.replace(/^0/, '')); } if (year != null) { year = parseInt(year.replace(/^0/, '')); } if (day != null) { day = parseInt(day.replace(/^0/, '')); } // Return a hash return { month: month, year: year, day: day } }, showCalendarEvent: function(e) { if (!e) var e = window.event; if (e.target) var id = e.target.id; if (e.srcElement) var id = e.srcElement.id; FbCalendar.get(id).show(); }, hideCalendarEvent: function(e) { if (!e) var e = window.event; if (e.target) var id = e.target.id; if (e.srcElement) var id = e.srcElement.id; FbCalendar.get(id).hide(); }, refreshCalendarEvent: function(e) { for (var i = 0; i < FbCalendar.instances.length; i++) { var cal = FbCalendar.instances[i]; cal.hide(); } }, mouseOverEvent: function(id) { FbCalendar.get(id).mouseOverCalendar = true; }, mouseOutEvent: function(id) { FbCalendar.get(id).mouseOverCalendar = false; }, mouseClickEvent: function(id) { inputId = FbCalendar.get(id).input_id; inputElem = document.getElementById(inputId); inputElem.focus(); }, create: function(id, type) { // Insert a new div inside the calendar_area div var mouseOverStr = ' onmouseover="FbCalendar.mouseOverEvent(\'' + id + '\')" '; var mouseOutStr = ' onmouseout="FbCalendar.mouseOutEvent(\'' + id + '\')" '; var mouseClickStr = ' onclick="FbCalendar.mouseClickEvent(\'' + id + '\')" '; var style = 'fb-double'; if (type & FbCalendar.SINGLE) style = 'fb-single'; var output = '' + '<iframe class="fb-iframe" id="' + id + '_cal_iframe' + '" src="iframe_dummy.html" frame style="display:none;"></iframe>' + '<div class="fb-container" style="display:none" id="' + id + '_container"' + mouseOverStr + mouseOutStr + mouseClickStr + '>' + '<div class="fb-calendar ' + style + '" style="background-color:' + FbCalendar.borderColor + '" id="' + id + '_calendar">' + '</div></div>'; // Insert the div before the input for which it was created var container = document.createElement('div'); container.innerHTML = output; var anchor = document.getElementById('fb_calendar_anchor'); anchor.parentNode.insertBefore(container, anchor); // Instantiate the calendar object var newCalendar = { currentMonth: null, currentYear: null, lastSelected: null, lastInputValue: null, visible: false, type: type, dirtyFlag: true, input_id: id, div_id: id + '_calendar', iframe_id: id + '_cal_iframe', container_id: id + '_container', id: this.idCounter++, dates: [[], []], mouseOverCalendar: false, buildTable: function(month, year, cal, options) { var realDate = new Date(year, month - 1, 1); var month = realDate.getMonth() + 1; var year = realDate.getFullYear(); var firstWeekDay = realDate.getDay(); var lastDayOfMonth = new Date(year, month, 0).getDate(); var dayCounter = 0; var cellCounter = 0; var out = ''; out += '<div class="calPad"><table cellspacing="1" cellpadding="0" style="background-color: #ddd;" id="cal_main">'; out += ' <thead><tr><td class="button">'; // Previous month button if (options == FbCalendar.BOTH || options == FbCalendar.PREV_ONLY) { out += ' <a href="#" class="prev" onclick="FbCalendar.get(' + this.id + ').prevYear(); event.cancelBubble=true; return false;">&#60;&#60;&nbsp;&nbsp;</a>'; out += ' <a href="#" class="prev" onclick="FbCalendar.get(' + this.id + ').prevMonth(); event.cancelBubble=true; return false;">&#60;</a>'; /*out += '</td><td class="button">'; out += ' <a href="#">&lt;</a>';*/ } out += ' </td>'; // Date header out += ' <td colspan="5" class="title">' + FbCalendar.monthNames[month-1] + ' ' + year + '</td>'; // Next month button out += ' <td class="button">'; if (options == FbCalendar.BOTH || options == FbCalendar.NEXT_ONLY) { out += ' <a href="#" class="next" onclick="FbCalendar.get(' + this.id + ').nextMonth();event.cancelBubble=true;return false;">&#62;</a>'; out += ' <a href="#" class="next" onclick="FbCalendar.get(' + this.id + ').nextYear();event.cancelBubble=true;return false;">&nbsp;&nbsp;&#62;&#62;</a>'; /*out += '</td><td class="button">'; out += ' <a href="#">&gt;</a>';*/ } out += ' </td></tr></thead>'; // Weekday names - S, M, T, W ... out += ' <tbody><tr class="days">'; for (i = 0; i < 7; i++) { out += ' <td>' + FbCalendar.weekDayNames[i] + '</td>'; } out += ' </tr>'; // Now, the guts of the calendar for (row = 0; row < 6; row++) { out += '<tr>' for (col = 0; col < 7; col++) { var afterFirstDay = cellCounter >= firstWeekDay; var beforeLastDay = cellCounter < lastDayOfMonth + firstWeekDay; cellCounter += 1; // "Close" button if (col > 4 && row > 4 && (options == FbCalendar.NEXT_ONLY || options == FbCalendar.BOTH)) { out += '<td class="button cal_close" colspan="2">' + '<a href="#" onclick="FbCalendar.get(' + this.id + ').hide(true);event.cancelBubble=true;return false;">Close</a></td>'; break; } if (afterFirstDay && beforeLastDay) { // Get a date object for this day date = new Date(year, month - 1, dayCounter + 1); // The unique id for this table cell elem_id = this.div_id + "_" + cal + "_" + dayCounter; // Was this date selected earlier if (this.lastSelectedDate && FbCalendar.datesEqual(date, this.lastSelectedDate)) out += '<td id="' + elem_id + '" class="selected">'; else out += '<td id="' + elem_id + '">'; out += '<a href="#" onclick="FbCalendar.get(' + this.id + ').pickDate(' + cal + ', ' + dayCounter + ');event.cancelBubble=true;return false;">' + (dayCounter + 1) + '</td>'; // Store the date in our 2d array this.dates[cal][dayCounter] = date; dayCounter += 1; } else { // Empty table cell -- no day falls on this cell out += '<td class="cal_empty">&nbsp;</td>'; } } out += '</tr>'; } out += '</tbody></table></div>'; return out; }, //---------------------------------------------------------------------// // Render the calendar -- prepare it for display (don't show it) render: function() { var firstWeekDay = new Date(this.currentYear, this.currentMonth - 1, 1).getDay(); var lastDayOfMonth = new Date(this.currentYear, this.currentMonth, 0).getDate(); var div = document.getElementById(this.div_id); div.innerHTML = ''; if (type == FbCalendar.DOUBLE) { // Double-month calendar leftTable = this.buildTable( this.currentMonth, this.currentYear, 0, FbCalendar.PREV_ONLY ); rightTable = this.buildTable( this.currentMonth + 1, this.currentYear, 1, FbCalendar.NEXT_ONLY ); //div.innerHTML += leftTable + '<div class="fb-divider"><img alt="WESGRO" src="images/spacerTrans.gif"/></div>' + rightTable; div.innerHTML += leftTable + rightTable; } else { // Single-month calendar table = this.buildTable( this.currentMonth, this.currentYear, 0, FbCalendar.BOTH ); div.innerHTML += table; } // Add close button div.innerHTML += '<div style="clear:both">'; /* div.innerHTML += '<div class="close"><a href="#" onclick="FbCalendar.get(' + this.id + ').hide(true);event.cancelBubble=true;return false;">Close</a></div>'*/ // Mark as no longer dirty this.dirtyFlag = false; }, // render() //---------------------------------------------------------------------// nextYear: function() { this.changeDate(this.currentMonth, this.currentYear+1, true); }, //---------------------------------------------------------------------// prevYear: function() { this.changeDate(this.currentMonth, this.currentYear-1, true); }, //---------------------------------------------------------------------// nextMonth: function() { if (this.currentMonth == 12) this.changeDate(1, this.currentYear + 1, true); else this.changeDate(this.currentMonth + 1, this.currentYear, true); }, //---------------------------------------------------------------------// prevMonth: function() { if (this.currentMonth == 1) this.changeDate(12, this.currentYear - 1, true); else this.changeDate(this.currentMonth - 1, this.currentYear, true); }, //--------------------------------------------------------------------// // Read date from input readDate: function() { var inputElem = document.getElementById(this.input_id); var dateString = inputElem.value; var date = FbCalendar.extractDate(dateString); if (dateString != '' && date.month && date.year) { this.changeDate(date.month, date.year); if (date.day) { this.lastInputValue = inputElem.value; this.lastSelectedDate = new Date(date.year, date.month - 1, date.day); this.dirtyFlag = true; } } // date && year }, //---------------------------------------------------------------------// // Change the current month(s) shown on the calendar changeDate: function(month, year, setfocus) { this.currentMonth = month; this.currentYear = year; this.render(); // Return focus if (setfocus) { inputElem = document.getElementById(this.input_id); inputElem.focus(); } }, attachTo: function(elemId) { elem = document.getElementById(elemId); elem.onclick = function(e) { alert(e.target); if (!e) var e = window.event; if (e.target) var id = e.target.id; if (e.srcElement) var id = e.srcElement.id; document.getElementById(FbCalendar.get(id)).focus(); } }, //---------------------------------------------------------------------// pickDate: function(cal, index) { var input = document.getElementById(this.input_id); input.value = FbCalendar.formatDate(this.dates[cal][index]); this.lastInputValue = input.value; this.dirtyFlag = true; this.lastSelectedDate = this.dates[cal][index]; this.hide(true); // force hide }, //---------------------------------------------------------------------// // Hides the calendar hide: function(force) { // Don't hide if the mouse is over the calendar // OPTIONAL: force the hide using the 'force' param if (force || !this.mouseOverCalendar) { div = document.getElementById(this.container_id); div.style.display = 'none'; iframe = document.getElementById(this.iframe_id); iframe.style.display = 'none'; this.visible = false; } }, //---------------------------------------------------------------------// // Reveals the calendar show: function() { // Before showing the calendar, we read the value from the input box, // and if its legible, we change the date on the calendar var inputElem = document.getElementById(this.input_id); if (!this.visible && inputElem.value != this.lastInputValue) { this.readDate(); } if (this.dirtyFlag) { this.render(); } // Get the calendar container var div = document.getElementById(this.container_id); div.style.position = 'absolute'; // Find the coordinates and dimensions of all the players // -- input box, calendar, window var inputCoords = findPos(inputElem); var inputDims = proto_getDimensions(inputElem); var windowDims = util_windowDims(); var scrollDims = util_scrollDims(); var calDims = proto_getDimensions(div); // Re-orient the calendar to fit inside the window // Width if ((inputCoords[0] + calDims[0] > windowDims[0]) && (inputCoords[0] - calDims[0] + inputDims[0] > 0)) div.style.left = (inputCoords[0] + inputDims[0] - calDims[0]) + 'px'; else div.style.left = inputCoords[0] + 'px'; // Height if ((inputCoords[1] + inputDims[1] + calDims[1] > windowDims[1] + scrollDims[1]) && (inputCoords[1] - calDims[1] > scrollDims[1])) { div.style.top = (inputCoords[1] - proto_getHeight(div) - FbCalendar.heightOffset) + 'px'; } else { div.style.top = (inputCoords[1] + proto_getHeight(inputElem) + + FbCalendar.heightOffset) + 'px'; } // Do the same for the iframe var iframe = document.getElementById(this.iframe_id); iframe.style.position = 'absolute'; iframe.style.left = div.style.left; iframe.style.top = div.style.top; iframe.style.width = proto_getWidth(div) + 'px'; iframe.style.height = proto_getHeight(div) + 'px'; iframe.style.display = 'block'; div.style.display = 'block'; this.visible = true; }, refresh: function() { if (this.visible) { this.hide(); this.show(); } }, //---------------------------------------------------------------------// // Reveals/hides the calendar, depending on its current state toggleVisible: function() { if (this.visible) this.hide(); else this.show(); } } // Add an onclick event to the input HTML element to which this calendar // is "attached" var input = document.getElementById(id); var container = document.getElementById(newCalendar.container_id); // Cross-platform event hackery because Daniel won't let me use Prototype :( :( if (input.addEventListener) { // Firefox/Mozilla/Opera input.addEventListener('focus', FbCalendar.showCalendarEvent, false); input.addEventListener('blur', FbCalendar.hideCalendarEvent, false); input.addEventListener('keydown', FbCalendar.hideCalendarEvent, false); window.addEventListener('resize', FbCalendar.refreshCalendarEvent, false); // Moved most mouseover events to the div's themselves // -- fixed a bunch of problems //container.addEventListener('mouseover', FbCalendar.mouseOverEvent, false); //container.addEventListener('mouseout', FbCalendar.mouseOutEvent, false); } else if (input.attachEvent) { // MSIE 6.x/7.x //input.attachEvent('onfocus', FbCalendar.showCalendarEvent); input.attachEvent('onfocus', FbCalendar.showCalendarEvent); input.attachEvent('onblur', FbCalendar.hideCalendarEvent); input.attachEvent('onkeydown', FbCalendar.hideCalendarEvent); window.attachEvent('onresize', FbCalendar.refreshCalendarEvent); //container.attachEvent('onmouseover', FbCalendar.mouseOverEvent); //container.attachEvent('onmouseout', FbCalendar.mouseOutEvent); } // Add the calendar object to the list of instances this.instances[newCalendar.id] = newCalendar; this.hashInstances[id] = newCalendar; var today = new Date(); newCalendar.changeDate(today.getMonth()+1,today.getFullYear()); return newCalendar; } } // This method was pulled from prototype.js function proto_getHeight(element) { return proto_getDimensions(element)[1]; } function proto_getWidth(element) { return proto_getDimensions(element)[0]; } function proto_getDimensions(element) { var display = element.style.display; if (display != 'none' && display != null) // Safari bug return [element.offsetWidth, element.offsetHeight];//{width: element.offsetWidth, height: element.offsetHeight}; // All *Width and *Height properties give 0 on elements with display none, // so enable the element temporarily var els = element.style; var originalVisibility = els.visibility; var originalPosition = els.position; var originalDisplay = els.display; els.visibility = 'hidden'; els.position = 'absolute'; els.display = 'block'; var originalWidth = element.clientWidth; var originalHeight = element.clientHeight; els.display = originalDisplay; els.position = originalPosition; els.visibility = originalVisibility; return [originalWidth, originalHeight];//{width: originalWidth, height: originalHeight} } // Author: <NAME> // http://www.quirksmode.org/js/findpos.html // License: http://www.quirksmode.org/about/copyright.html function findPos(obj) { var curleft = curtop = 0; if (obj.offsetParent) { curleft = obj.offsetLeft; curtop = obj.offsetTop; while (obj = obj.offsetParent) { curleft += obj.offsetLeft; curtop += obj.offsetTop; } } return [curleft, curtop]; } // Author: <NAME> <<EMAIL>> // http://www.mattkruse.com/javascript/date/source.html var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'); function LZ(x) {return(x<0||x>9?"":"0")+x} function formatDate(date,format) { format=format+""; var result=""; var i_format=0; var c=""; var token=""; var y=date.getYear()+""; var M=date.getMonth()+1; var d=date.getDate(); var E=date.getDay(); var H=date.getHours(); var m=date.getMinutes(); var s=date.getSeconds(); var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; // Convert real date parts into formatted versions var value=new Object(); if (y.length < 4) {y=""+(y-0+1900);} value["y"]=""+y; value["yyyy"]=y; value["yy"]=y.substring(2,4); value["M"]=M; value["MM"]=LZ(M); value["MMM"]=MONTH_NAMES[M-1]; value["NNN"]=MONTH_NAMES[M+11]; value["d"]=d; value["dd"]=LZ(d); value["E"]=DAY_NAMES[E+7]; value["EE"]=DAY_NAMES[E]; value["H"]=H; value["HH"]=LZ(H); if (H==0){value["h"]=12;} else if (H>12){value["h"]=H-12;} else {value["h"]=H;} value["hh"]=LZ(value["h"]); if (H>11){value["K"]=H-12;} else {value["K"]=H;} value["k"]=H+1; value["KK"]=LZ(value["K"]); value["kk"]=LZ(value["k"]); if (H > 11) { value["a"]="PM"; } else { value["a"]="AM"; } value["m"]=m; value["mm"]=LZ(m); value["s"]=s; value["ss"]=LZ(s); while (i_format < format.length) { c=format.charAt(i_format); token=""; while ((format.charAt(i_format)==c) && (i_format < format.length)) { token += format.charAt(i_format++); } if (value[token] != null) { result=result + value[token]; } else { result=result + token; } } return result; } function util_windowDims() { var width = 0; var height = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE width = window.innerWidth; height = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' width = document.documentElement.clientWidth; height = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { //IE 4 compatible width = document.body.clientWidth; height = document.body.clientHeight; } return [width, height]; } function util_scrollDims() { var scrOfX = 0, scrOfY = 0; if( typeof( window.pageYOffset ) == 'number' ) { //Netscape compliant scrOfY = window.pageYOffset; scrOfX = window.pageXOffset; } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) { //DOM compliant scrOfY = document.body.scrollTop; scrOfX = document.body.scrollLeft; } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) { //IE6 standards compliant mode scrOfY = document.documentElement.scrollTop; scrOfX = document.documentElement.scrollLeft; } return [ scrOfX, scrOfY ]; } <file_sep>WesgroDMDesign ============== Wesgro Destination Marketing HTML5 Design Screens
8d5591ecd194a805cf2c1196a4e9582695480bce
[ "JavaScript", "Markdown" ]
3
JavaScript
BarryBotha/WesgroDMDesign
84dff487f9bf3511a25b4f80327a2c3d347bcbb9
baa404c182fc8b675716fec5507c2f19cdd68f6f
refs/heads/master
<file_sep>package Task19_FirstAndReserveTeam_SU; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); int number = Integer.parseInt(drucker.nextLine()); Team someTeam = new Team("JavaTeam"); for (int i = 0; i < number ; i++) { String [] inputArray = drucker.nextLine().split("\\s+"); Person p = new Person(inputArray[0],inputArray[1],Integer.parseInt(inputArray[2])); someTeam.addPlayer(p); } System.out.printf("First team have %d players%n",someTeam.getFirstTeam().size()); System.out.printf("Reserve team have %d players%n",someTeam.getSecondTeam().size()); } } <file_sep>package Task19_VendingMachineTests; import Task19_VendingMachine_V1.User; import Task19_VendingMachine_V1.UsersCoins; import Task19_VendingMachine_V1.WishProduct; import org.junit.Assert; import org.junit.Test; public class UserTest { @Test public void cancelledOrderShouldReturnStringWithMyChange() { WishProduct wishProduct = new WishProduct("Coke"); UsersCoins usersCoins = new UsersCoins("penny - 5, nickel - 0, dime - 5, quarter - 0"); User user = new User(wishProduct, usersCoins); Assert.assertEquals("Your order has been cancelled!" + System.lineSeparator()+ "Your refund is:" + System.lineSeparator()+ "penny - 5" + System.lineSeparator()+ "nickel - 0" + System.lineSeparator()+ "dime - 5" + System.lineSeparator()+ "quarter - 0" + System.lineSeparator()+ "The Sum is: 0.55£", user.cancelledOrder()); } } <file_sep>package Task19_VendingMachine_V1; public class WishProduct { private Product product; public WishProduct(String productName) { this.setSelectedProduct(productName); } public Product getProduct() { return this.product; } public void setSelectedProduct(String productName) { if (!containsEnum(productName)) { throw new IllegalArgumentException("There is no such a product!"); } this.product = Product.valueOf(productName); } public boolean containsEnum(String productName) { for (Product p : Product.values()) { if (p.name().equals(productName)) { return true; } } return false; } } <file_sep>Write a program to check if two given String is Anagram of each other. Your function should return true if two Strings are Anagram, false otherwise. A string is said to be an anagram if it contains the same characters and same length, but in a different order, e.g. army and Mary are anagrams.<file_sep>Hello guys, today's programming exercise is to write a program to find repeated characters in a String. For example, if given input to your program is "Java", it should print all duplicates characters, i.e. characters appear more than once in String and their count like a = 2 because of character 'a' has appeared twice in String "Java". This is also a very popular coding question on the various level of Java interviews and written tests, where you need to write code. On difficulty level, this question is at par with the prime numbers or Fibonacci series, which are also very popular on junior level Java programming interviews and it's expected from every programmer to know how to solve them. Read more: https://www.java67.com/2014/03/how-to-find-duplicate-characters-in-String-Java-program.html#ixzz6JQ8qBRwD<file_sep>rootProject.name = 'play-ground' <file_sep>Your program must produce a String contains the word in reverse order , for example if given input is "Java is Great" then your program should return "Great is Java". <file_sep>This is generally asked as follow-up or alternative of the previous program. This time you need to check if given Integer is palindrome or not. An integer is called palindrome if it's equal to its reverse, e.g. 1001 is a palindrome, but 1234 is not because the reverse of 1234 is 4321 which is not equal to 1234. You can use divide by 10 to reduce the number and modulus 10 to get the last digit. This trick is used to solve this problem.<file_sep>package Task9_RemoveDuplicatesFromArray; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class V2_RemoveDuplicatesSet { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your values separated by space:"); String input = drucker.nextLine(); if (input.isEmpty()||input.equals(" ")){ System.out.println("Please enter a non empty value"); } else { List<String> myList = Arrays.stream(input.split("\\s+")).collect(Collectors.toList()); HashSet<String> result = new HashSet<>(); for (String s : myList) { result.add(s); } result.stream().forEach(el-> System.out.print(el+" // ")); } } } <file_sep>Create a Team class. Add to this team all person you read. All person younger than 40 go in first team, others go in reverse team. At the end print first and reserve team sizes.<file_sep>NOTE: You need a public class Main. Create a restaurant package with the following classes and hierarchy: There are Food and Beverages in the restaurant and they are all products. The Product class must have the following members: • A public constructor with the following parameters: String name, BigDecimal price • name – String • price – BigDecimal • Getters for the fields Beverage and Food classes are products. The Beverage class must have the following members: • A public constructor with the following parameters: String name, BigDecimal price, double milliliters • name – String • price – BigDecimal • milliliters – double • Getter for milliliters The Food class must have the following members: • A constructor with the following parameters: String name, BigDecimal price, double grams • name – String • price – double • grams – double • Getter for grams HotBeverage and ColdBeverage are beverages and they accept the following parameters upon initialization: String name, BigDecimal price, double milliliters Coffee and Tea are hot beverages. The Coffee class must have the following additional members: • double COFFEE_MILLILITERS = 50 • BigDecimal COFFEE_PRICE = 3.50 • caffeine – double • Getter for caffeine MainDish, Dessert and Starter are food. They all accept the following parameters upon initialization: String name, BigDecimal price, double grams. Dessert must accept one more parameter in its constructor: double calories. • calories – double • Getter for calories Make Salmon, Soup and Cake inherit the proper classes. A Cake must have the following members upon initialization: • double CAKE_GRAMS = 250 • double CAKE_CALORIES = 1000 • BigDecimal CAKE_PRICE = 5 A Salmon must have the following members upon initialization: • double SALMON_GRAMS = 22 <file_sep>Create a class PriceCalculator that calculates the total price of a holiday, given the price per day, number of days, the season and a discount type. The discount type and season should be enums. Use the class in your main() method to read input and print on the console the price of the whole holiday. The price per day will be multiplied depending on the season by: • 1 during Autumn • 2 during Spring • 3 during Winter • 4 during Summer The discount is applied to the total price and is one of the following: • 20% for VIP clients - VIP • 10% for clients, visiting for a second time - SecondVisit • 0% if there is no discount - None Input On a single line you will receive all the information about the reservation in the format: “<pricePerDay> <numberOfDays> <season> <discountType>”, where: • The price per day will be a valid decimal in the range [0.01…1000.00] • The number of days will be a valid integer in range [1…1000] • The season will be one of: Spring, Summer, Autumn, Winter • The discount will be one of: VIP, SecondVisit, None Output On a single line, print the total price of the holiday, rounded to 2 digits after the decimal separator. Examples input output 50.25 5 Summer VIP 804.00 40 10 Autumn SecondVisit 360.00 120.20 2 Winter None 721.20 <file_sep>package Task9_RemoveDuplicatesFromArray; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class V1_RemoveDuplicates { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your values separated by space:"); String inputs = drucker.nextLine(); List<String> myList = new LinkedList<>(); myList = Arrays.stream(inputs.split(" ")).collect(Collectors.toList()); List<String> resultList = new LinkedList<>(); for (String eachValue : myList) { if (!resultList.contains(eachValue)){ resultList.add(eachValue); } } resultList.stream().forEach(el-> System.out.println(el)); } } <file_sep>It's relatively easy to reverse an array if you have the luxury to use another array, but how would you reverse an array if a temporary buffer is not allowed?<file_sep>package Task3_StringPalindrome; import java.util.Scanner; public class V1_StringPalindrome { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your input:"); String input = drucker.nextLine(); input = input.toLowerCase(); boolean isItPalindrome = true; int wordLength = input.length(); if (wordLength == 1) { isItPalindrome = false; } else { for (int i = 0; i < wordLength / 2; i++) { if (input.charAt(i) != input.charAt(wordLength - 1 - i)) { isItPalindrome = false; break; } } } if (!isItPalindrome) { System.out.println("No att all!"); } else { System.out.println("Yes baby!"); } } } <file_sep>Create a class Animal, which holds two fields: • name: String • favouriteFood: String Animal has one abstract method explainSelf(): String. You should add two new classes - Cat and Dog. Override the explainSelf() method by adding concrete animal sound on a new line. (Look at examples below) You should be able to use the class like this: Main public static void main(String[] args) { Animal cat = new Cat("Oscar", "Whiskas"); Animal dog = new Dog("Rocky", "Meat"); System.out.println(cat.explainSelf()); System.out.println(dog.explainSelf()); } <file_sep>You need to write a program to calculate the square root of a number without using the Math.sqrt() function of JDK. You need to write your logic and method to calculate the square root. You can though use the popular algorithm, like Newton's method.<file_sep>This problem is similar to the String Palindrome problem we have discussed above. If you can solve that problem, you can solve this as well. You can use indexOf() or substring() to reverse a String or alternatively, convert the problem to reverse an array by operating on character array instead of String. If you want to brush up your data structure skill you can also check Data Structures and Algorithms: Deep Dive Using Java course on Udemy before solving this question.<file_sep>package Task1_FibonacciSeries; import java.util.Scanner; public class V1_FibonacciSeries { public static void main(String[] args) { System.out.println("Enter number upto which Fibonacci series to print: "); Scanner drucker = new Scanner(System.in); int number = Integer.parseInt(drucker.nextLine()); int fibFirst = 0; int fibSecond = 1; int fibonacci = 0; System.out.printf("Fibonacci series upto %d numbers:%n",number); for (int i = 0; i < number; i++) { if (fibonacci == 0 || fibonacci == 1) { System.out.print(1 + " "); } else { System.out.print(fibonacci + " "); } fibonacci = fibFirst + fibSecond; fibFirst = fibSecond; fibSecond = fibonacci; } } } <file_sep>package Task1_FibonacciSeries; import java.util.LinkedHashMap; import java.util.Scanner; public class V3_FibonacciSeriesMemoization { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Enter number upto which Fibonacci series to print: "); int number = Integer.parseInt(drucker.nextLine()); LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>(); System.out.printf("Fibonacci series upto %d numbers:%n", number); for (int i = 0; i < number; i++) { Integer fibonacci; if (i == 0 || i == 1) { System.out.print(1 + " "); cache.put(i, 1); continue; } fibonacci = cache.get(i - 1) + cache.get(i - 2); cache.put(i, fibonacci); System.out.print(fibonacci + " "); } } } <file_sep>package Task8_ReverseString; import java.util.Scanner; public class V1_ReverseStringArray { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your text"); String inputString = drucker.nextLine(); System.out.println(reverseIt(inputString)); } private static String reverseIt(String input) { if (input == null || input.isEmpty()) { return "damn"; } char[] myArray = input.toCharArray(); StringBuilder result = new StringBuilder(); for (int i = myArray.length - 1; i >= 0; i--) { result.append(myArray[i]); } return result.toString(); } } <file_sep>This one of the popular OOAD (object-oriented analysis and design) question from Java Interviews. You will be given 3 hours to design and code a vending machine satisfying some of the business requirements. You also need to write unit tests to prove your code satisfy those requirements. You need to design a Vending Machine which Accepts coins of 1,5,10,25 Cents i.e. penny, nickel, dime, and quarter. Allow user to select products Coke(25), Pepsi(35), Soda(45) Allow user to take refund by canceling the request. Return selected product and remaining change if any Allow reset operation for vending machine supplier. <file_sep>Simple Java program to find GCD (Greatest common Divisor) or GCF (Greatest Common Factor) or HCF (Highest common factor). The GCD of two numbers is the largest positive integer that divides both the numbers fully i.e. without any remainder. Read more: https://www.java67.com/2012/08/java-program-to-find-gcd-of-two-numbers.html#ixzz6JWQzf7SD<file_sep>package Task19_Ferrari_SU; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please write the name of the driver."); String input = drucker.nextLine(); Ferrari myFerrari = new Ferrari(input); System.out.println(myFerrari.toString()); } } <file_sep>package Task4_IntegerPalindrome; import java.util.Scanner; public class V1_IntegerPalindrome { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your NUMBER:"); int number = Integer.parseInt(drucker.nextLine()); // some change if (number < 10 && number > -10) { System.out.println(false); } else { int reversedNumber = Integer.parseInt(reverseNumberAsString(number)); System.out.println(number + " <--> " + reversedNumber); System.out.println(number == reversedNumber); } } private static String reverseNumberAsString(int startNumber) { StringBuilder reversed = new StringBuilder(); while (startNumber != 0) { if (startNumber < 0) { reversed.append('-'); startNumber = Math.abs(startNumber); } reversed.append(startNumber % 10); startNumber = startNumber / 10; } return reversed.toString(); } } <file_sep>We will write a Java program which will take input from the user, both array and the number to be searched and then perform a binary search to find that number in a given array.<file_sep>Write a Java program to check if a given number is prime or not. Remember, a prime number is a number which is not divisible by any other number, e.g. 3, 5, 7, 11, 13, 17, etc. Be prepared for cross, e.g. checking till the square root of a number, etc. <file_sep>package Task7_Factorial; import java.math.BigInteger; import java.util.Scanner; public class V1_FactorialRecursion { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your number:"); int inputNumber = Integer.parseInt(drucker.nextLine()); System.out.println(calculateFactorial(inputNumber)); } private static BigInteger calculateFactorial(int numb) { if (numb == 0) { return BigInteger.valueOf(1); } return BigInteger.valueOf(numb).multiply(calculateFactorial(numb-1)); } } <file_sep>package Task19_Restaurant_SU; import java.math.BigDecimal; public class Main { public static void main(String[] args) { Salmon mySalmon = new Salmon(BigDecimal.valueOf(50)); System.out.println(mySalmon.getName()); System.out.println(mySalmon.getGrams()); System.out.println(mySalmon.getPrice()); } } <file_sep>You need to write a simple Java program to check if a given String is palindrome or not. A Palindrome is a String which is equal to the reverse of itself, e.g., "Bob" is a palindrome because of the reverse of "Bob" is also "Bob." Though be prepared with both recursive and iterative solution of this problem. The interviewer may ask you to solve without using any library method, e.g. indexOf() or subString() so be prepared for that.<file_sep>Pattern based exercises are a good way to learn nested loops in Java. There are many pattern based exercises and one of them is printing Pyramid structure as shown below: * * * * * * * * * * * * * * * <file_sep>package Task12_GCDofTwoNumbers; import java.util.Arrays; import java.util.Scanner; public class V2_GCDofTwoNumbersRecursive { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter two numbers, separated by space"); String input = drucker.nextLine(); if (input.length() < 3 || !input.contains(" ")) { System.out.println("Invalid input"); return; } try { int[] numbers = Arrays.stream(input.split("\\s+")).mapToInt(Integer::parseInt).toArray(); int firstNumber = numbers[0]; int secondNumber = numbers[1]; System.out.printf("The GCD is: %d", findGCDRecursive(firstNumber,secondNumber)); System.out.println(9%27); } catch (Exception e) { System.out.println("Invalid input!"); } } private static int findGCDRecursive(int first, int second) { if (second == 0) { return first; } return findGCDRecursive(second, first % second); } } <file_sep>package Task8_ReverseString; import java.util.Scanner; public class V2_ReverseString { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your text"); String inputText = drucker.nextLine(); System.out.println(reverseText(inputText)); } private static String reverseText(String input) { String result = ""; int counter = input.length(); for (int i = 0; i < counter; i++) { result = result + input.substring(counter - 1 - i); input = input.substring(0, counter - 1 - i); } return result; } } <file_sep>Write a program to remove duplicates from an array in Java without using the Java Collection API. The array can be an array of String, Integer or Character, your solution should be independent of the type of array.<file_sep>package Task12_GCDofTwoNumbers; import java.util.Arrays; import java.util.Scanner; public class V1_GCDofTwoNumbers { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your two numbers separated by space"); String input = drucker.nextLine(); if (input.isEmpty() || !input.contains(" ") || input.length() < 3) { System.out.println("Invalid input!"); return; } int firstNumber; int secondNumber; try { int[] numbers = Arrays.stream(input.split("\\s+")) .mapToInt(Integer::parseInt).toArray(); firstNumber = numbers[0]; secondNumber = numbers[1]; } catch (Exception e) { System.out.println("Invalid input!"); return; } int smallerNumber = Math.min(firstNumber, secondNumber); for (int i = smallerNumber; i > 0; i--) { if (firstNumber % i == 0 && secondNumber % i == 0) { System.out.printf("The greatest common divisor is %d", i); break; } } } } <file_sep>Model an application which contains a class Ferrari and an interface. Your task is simple, you have a car - Ferrari, its model is "488-Spider" and it has a driver. Your Ferrari should have functionality to use brakes and push the gas pedal. When the brakes are pushed down print "Brakes!", and when the gas pedal is pushed down - "Zadu6avam sA!". As you may have guessed this functionality is typical for all cars, so you should implement an interface to describe it. <<Interface>> Car + brakes() : String + gas() : String Your task is to create a Ferrari and set the driver's name to the passed one in the input. After that, print the info. Take a look at the Examples to understand the task better. Ferrari - driverName: String - model: String + Ferrari (String) + brakes() : String + gas() : String + toString(): String Input On the single input line, you will be given the driver's name. Output On the single output line, print the model, the messages from the brakes and gas pedal methods and the driver's name. In the following format: "{model}/{brakes}/{gas pedal}/{driver's name}" Constraints The input will always be valid, no need to check it explicitly! The Driver's name may contain any ASCII characters.   Example Input Output <NAME> 488-Spider/Brakes!/brum-brum-brum-brrrrr/Dominic Toretto <NAME> 488-Spider/Brakes!/brum-brum-brum-brrrrr/<NAME>ner <file_sep>package Task19_HotelReservation_SU; public enum DiscountType { None(0), SecondVisit(10), VIP(20); private int discountTypeMultiplier; DiscountType(int discountTypeMultiplier) { this.discountTypeMultiplier = discountTypeMultiplier; } public double getDiscountTypeMultiplier() { return 1 - this.discountTypeMultiplier / 100.0; } } <file_sep>A number is called an Armstrong number if it is equal to the cube of its every digit. For example, 153 is an Armstrong number because of 153= 1+ 125+27, which is equal to 1^3+5^3+3^3. You need to write a program to check if the given number is Armstrong number or not. <file_sep>package Task4_IntegerPalindrome; import java.util.Scanner; public class V2_IntegerPalindromeWithoutString { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your NUMBER:"); int number = Integer.parseInt(drucker.nextLine()); int reversedNumber = reverseNumber(number); System.out.println(number + " <--> " + reversedNumber); System.out.println(number == reversedNumber); } private static int reverseNumber(int input) { int result = 0; while (input != 0) { int lastDigit = input % 10; result = result * 10 + lastDigit; input = input / 10; } return result; } } <file_sep>package Task11_PrintRepeatedCharOfString; import java.util.LinkedHashMap; import java.util.Scanner; public class V2_PrintRepeatedCharOfStringMap { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your text"); String inputText = drucker.nextLine(); LinkedHashMap<Character, Integer> myMap = new LinkedHashMap<>(); for (Character eachChar : inputText.toCharArray()) { if (!myMap.containsKey(eachChar)) { myMap.put(eachChar, 1); } else { myMap.put(eachChar, myMap.get(eachChar) + 1); } } myMap.entrySet().stream().filter(e -> e.getValue() != 1).forEach(pair -> { Character myChar = pair.getKey(); Integer count = pair.getValue(); System.out.println(myChar + " : " + count); }); } } <file_sep>package Task19_VendingMachine_V1; public enum Product { Coke(25), Pepsi(35), Soda(45); private final int price; Product(int price){ this.price = price; } public int getPrice(){ return this.price; } } <file_sep>package Task11_PrintRepeatedCharOfString; import java.util.LinkedHashSet; import java.util.Scanner; public class V1_PrintRepeatedCharOfStringSet { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your input:"); String input = drucker.nextLine(); LinkedHashSet<Character> someSet = returnDuplicates(input); if (someSet == null) { System.out.println("There are no duplicates"); } else { for (Character everyChar : someSet) { System.out.println(everyChar); } } } private static LinkedHashSet<Character> returnDuplicates(String text) { char[] myArray = text.toCharArray(); LinkedHashSet<Character> mySet = new LinkedHashSet<>(); LinkedHashSet<Character> resultSet = new LinkedHashSet<>(); for (char c : myArray) { if (!mySet.contains(c)) { mySet.add(c); } else { resultSet.add(c); } } if (!resultSet.isEmpty()) { return resultSet; } return null; } } <file_sep>package Task5_ArmstrongNumber; import java.util.Scanner; public class V1_ArmstrongNumber { public static void main(String[] args) { Scanner drucker = new Scanner(System.in); System.out.println("Please enter your number:"); int numberToCheck = Integer.parseInt(drucker.nextLine()); System.out.println(armstrongChecker(numberToCheck)); } private static boolean armstrongChecker(int numb) { double armstrongCandidate = 0.0; int startNumb = numb; while (numb != 0) { armstrongCandidate = armstrongCandidate + Math.pow(numb % 10, 3); numb = numb / 10; } return armstrongCandidate == startNumb; } } <file_sep>This is one of the simplest programs you can expect in interviews. It is generally asked to see if you can code or not. Sometimes interviewer may also ask about changing a recursive solution to iterative one or vice-versa.<file_sep>Write a simple Java program which will print Fibonacci series, e.g. 1 1 2 3 5 8 13 ... . up to a given number. We prepare for cross questions like using iteration over recursion and how to optimize the solution using caching and memoization.
e4f0047dd9eb9a89703bc66e2b7da33cec05e224
[ "Markdown", "Java", "Gradle" ]
45
Java
NikolayBaramov/play-ground
70cb3db11f50e70515b11265960a2be0d08192a9
fd503165bff027ce921152f0180c8c1c264d50a2
refs/heads/master
<repo_name>mdwetzel/Caesar-Cipher<file_sep>/caesar_cipher.rb class CaesarCipher def self.find_decrypted_letter(array, letter) array[array.find_index(letter) - 3] unless letter.nil? end def self.find_encrypted_letter(array, letter) array[array.find_index(letter) + 3] unless letter.nil? end def self.decrypt(encrypted_string) uppercase_letters = [*'A'..'Z'] lowercase_letters = [*'a'..'z'] message = String.new encrypted_string.each_char do |char| letter = char unless char =~ /[\s\d]/ message += ' ' if letter.nil? next if letter.nil? message += letter =~ /[a-z]/ ? find_decrypted_letter(lowercase_letters, letter) : find_decrypted_letter(uppercase_letters, letter) end message end def self.encrypt(string) uppercase_letters = [*'A'..'Z'] lowercase_letters = [*'a'..'z'] message = String.new string.each_char do |char| letter = char unless char =~ /[\s\d]/ message += ' ' if letter.nil? next if letter.nil? message += letter =~ /[a-z]/ ? find_encrypted_letter(lowercase_letters, letter) : find_encrypted_letter(uppercase_letters, letter) end message end end<file_sep>/main.rb require_relative 'caesar_cipher' print "Enter the string to be decrypted: " puts "The decrypted message is: " + CaesarCipher.decrypt(gets) print "Enter the message to be encrypted: " puts "The encrypted message is: " + CaesarCipher.encrypt(gets)
bddc5723af3f67fc5afb39ab2162cb87caefe5ef
[ "Ruby" ]
2
Ruby
mdwetzel/Caesar-Cipher
bd8a2665aefc9bf5a85aae25cc40884f5c16d5f7
6ef466b3fc887dcb412b5a4ddc26beece69c238b
refs/heads/master
<repo_name>dairnarth/vswm<file_sep>/vswm.c #include <signal.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <X11/keysym.h> #include <X11/XF86keysym.h> #include <X11/XKBlib.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> /* Defaults */ #define BARCLASS "Bar" #define BARCOMMAND "$HOME/.config/lemonbar/lemonlaunch" #define BORDER_WIDTH 1 #define BORDER_COLOUR 0xebdbb2 #define GAP_TOP 30 #define GAP_RIGHT 5 #define GAP_BOTTOM 5 #define GAP_LEFT 5 /* Structs */ typedef struct Key Key; typedef void (*Events)(XEvent *event); struct Key { unsigned int modifier; KeySym keysym; void (*function)(XEvent *event, char *command); char *command; }; /* Function Declarations */ static int barcheck(Window window); static void barconfig(XEvent *event); static void bardestroy(void); static void barlaunch(void); static void configure(XEvent *event); static void destroy(XEvent *event, char *command); static void enter(XEvent *event); static void focus(XEvent *event, char *command); static void fullscreen(XEvent *event, char *command); static void grab(void); static int ignore(Display *display, XErrorEvent *event); static void key(XEvent *event); static void launch(XEvent *event, char *command); static void loop(void); static void map(XEvent *event); static void quit(XEvent *event, char *command); static void refresh(XEvent *event, char *command); static void remap(XEvent *event); static void scan(void); static void setup(void); static void size(void); static void updatetitle(Window window); /* Variables */ static int screen, width, height; static int running = 1; static int isfullscreen = 0; static int border_width = BORDER_WIDTH; static int gap_top = GAP_TOP; static int gap_right = GAP_RIGHT; static int gap_bottom = GAP_BOTTOM; static int gap_left = GAP_LEFT; static Display *display; static Window root; static Window barwin; static Atom netactivewindow, netsupported; static Key keys[] = { /* Modifiers, Key, Function, Arguments */ { Mod4Mask, XK_t, launch, "st -e tmux-default" }, { Mod4Mask, XK_w, launch, "st -e setsid qutebrowser" }, /* TODO: Fix actual problem (ERROR 10: No Child Processes) */ { Mod4Mask, XK_space, launch, "dmenu_run -p 'RUN '" }, { Mod4Mask, XK_q, destroy, 0 }, { Mod4Mask|ShiftMask, XK_r, refresh, 0 }, { Mod4Mask|ShiftMask, XK_q, quit, 0 }, { Mod4Mask|ShiftMask, XK_x, launch, "safe_shutdown" }, { Mod4Mask, XK_Tab, focus, "next" }, { Mod4Mask|ShiftMask, XK_Tab, focus, "prev" }, { Mod4Mask, XK_Return, fullscreen, 0 }, { 0, XF86XK_AudioMute, launch, "pamixer -t" }, { 0, XF86XK_AudioLowerVolume, launch, "pamixer -d 5" }, { 0, XF86XK_AudioRaiseVolume, launch, "pamixer -i 5" }, { ShiftMask, XF86XK_AudioLowerVolume, launch, "pamixer -d 1" }, { ShiftMask, XF86XK_AudioRaiseVolume, launch, "pamixer -i 1" }, { 0, XF86XK_MonBrightnessDown, launch, "light -U 5" }, { 0, XF86XK_MonBrightnessUp, launch, "light -A 5" }, { ShiftMask, XF86XK_MonBrightnessDown, launch, "light -U 1" }, { ShiftMask, XF86XK_MonBrightnessUp, launch, "light -A 1" }, }; static const Events events[LASTEvent] = { [ConfigureRequest] = configure, [EnterNotify] = enter, [KeyPress] = key, [MapRequest] = map, }; /* Function Implementations */ int barcheck(Window window) { char *class; XClassHint classhint = { NULL, NULL }; XGetClassHint(display, window, &classhint); class = classhint.res_class; if (strcmp(class, BARCLASS) == 0) { return 0; } else { return 1; } if (classhint.res_class) XFree(classhint.res_class); if (classhint.res_name) XFree(classhint.res_name); } void barconfig(XEvent *event) { barwin = event->xmaprequest.window; XMoveResizeWindow(display, barwin, 5, 5, 1268, 18); } void bardestroy(void) { XSetCloseDownMode(display, DestroyAll); XKillClient(display, barwin); } void barlaunch(void) { XEvent *event = { NULL }; launch(event, BARCOMMAND); } void configure(XEvent *event) { XConfigureRequestEvent *request = &event->xconfigurerequest; XWindowChanges changes = { .x = request->x, .y = request->y, .width = request->width, .height = request->height, .border_width = request->border_width, .sibling = request->above, .stack_mode = request->detail, }; XConfigureWindow(display, request->window, request->value_mask, &changes); } void destroy(XEvent *event, char *command) { (void)command; XSetCloseDownMode(display, DestroyAll); XKillClient(display, event->xkey.subwindow); } void enter(XEvent *event) { Window window = event->xcrossing.window; XSetInputFocus(display, window, RevertToParent, CurrentTime); XRaiseWindow(display, window); remap(event); updatetitle(window); } void focus(XEvent *event, char *command) { (void)event; int next = command[0] == 'n'; XCirculateSubwindows(display, root, next ? RaiseLowest : LowerHighest); } void fullscreen(XEvent *event, char *command) { (void)command; if (isfullscreen == 0) { border_width = 0; gap_top = 0; gap_right = 0; gap_bottom = 0; gap_left = 0; isfullscreen = 1; bardestroy(); } else if (isfullscreen == 1) { border_width = BORDER_WIDTH; gap_top = GAP_TOP; gap_right = GAP_RIGHT; gap_bottom = GAP_BOTTOM; gap_left = GAP_LEFT; isfullscreen = 0; barlaunch(); } remap(event); } void grab(void) { unsigned int i; for (i = 0; i < sizeof(keys) / sizeof(struct Key); i++) XGrabKey(display, XKeysymToKeycode(display, keys[i].keysym), keys[i].modifier, root, True, GrabModeAsync, GrabModeAsync); } int ignore(Display *display, XErrorEvent *event) { (void)display; (void)event; return 0; } void key(XEvent *event) { unsigned int i; KeySym keysym = XkbKeycodeToKeysym(display, event->xkey.keycode, 0, 0); for (i = 0; i < sizeof(keys) / sizeof(struct Key); i++) if (keysym == keys[i].keysym && keys[i].modifier == event->xkey.state) keys[i].function(event, keys[i].command); } void launch(XEvent *event, char *command) { (void)event; if (fork() == 0) { if (display) close(XConnectionNumber(display)); setsid(); execl("/bin/bash", "bash", "-c", command, 0); exit(1); } } void loop(void) { XEvent event; while (running && !XNextEvent(display, &event)) if (events[event.type]) events[event.type](&event); } void map(XEvent *event) { Window window = event->xmaprequest.window; XWindowChanges changes = { .border_width = border_width }; XSelectInput(display, window, StructureNotifyMask | EnterWindowMask); XSetWindowBorder(display, window, BORDER_COLOUR); XConfigureWindow(display, window, CWBorderWidth, &changes); barcheck(window) ? XMoveResizeWindow(display, window, gap_left, gap_top, width, height) : barconfig(event); XMapWindow(display, window); } void quit(XEvent *event, char *command) { (void)event; (void)command; running = 0; } void refresh(XEvent *event, char *command) { (void)event; (void)command; size(); scan(); } void remap(XEvent *event) { XMapRequestEvent *request = &event->xmaprequest; int revert; XGetInputFocus(display, &request->window, &revert); refresh(NULL, NULL); map(event); } void scan(void) { unsigned int i, n; Window r, p, *c; if (XQueryTree(display, root, &r, &p, &c, &n)) { for (i = 0; i < n; i++) if (c[i] != barwin) XMoveResizeWindow(display, c[i], gap_left, gap_top, width, height); if (c) XFree(c); } } void setup(void) { signal(SIGCHLD, SIG_IGN); XSetErrorHandler(ignore); screen = XDefaultScreen(display); root = XDefaultRootWindow(display); XSelectInput(display, root, SubstructureRedirectMask); XDefineCursor(display, root, XCreateFontCursor(display, 68)); netsupported = XInternAtom(display, "_NET_SUPPORTED", False); netactivewindow = XInternAtom(display, "_NET_ACTIVE_WINDOW", False); XChangeProperty(display, root, netsupported, XA_ATOM, 32, PropModeReplace, (unsigned char *) &netactivewindow, 1); size(); grab(); scan(); barlaunch(); } void size(void) { width = XDisplayWidth(display, screen) - \ (gap_right + gap_left + (border_width * 2)); height = XDisplayHeight(display, screen) - \ (gap_top + gap_bottom + (border_width * 2)); } void updatetitle(Window window) { XEvent event; event.type = ClientMessage; event.xclient.window = window; event.xclient.message_type = netactivewindow; event.xclient.format = 32; event.xclient.data.l[0] = 1; event.xclient.data.l[1] = CurrentTime; event.xclient.data.l[2] = window; XSendEvent(display, root, False, (SubstructureNotifyMask|SubstructureRedirectMask), &event); XChangeProperty(display, root, netactivewindow, XA_WINDOW, 32, PropModeReplace, (unsigned char *) &window, 1); } int main(void) { if (!(display = XOpenDisplay(0))) exit(1); setup(); loop(); } <file_sep>/README.md # vswm - very stupid window manager Probably the most stupid window manager ever created, written over an ancient relic of a library called Xlib -- a library so old that it preceeded the birth of planet Earth itself. - There are no workspaces. - All windows are the same size. - Windows can not be moved or resized (other than fullscreen, but all windows are affected.) - Only one window is visible at a time. - This certainly isn't for everyone. ## Keybindings | Key | Function | |--------------------------|---------------------------| | MOD4 + Tab | focus next window | | MOD4 + Shift + Tab | focus prev window | | MOD4 + q | kill window | | MOD4 + Shift + r | refresh wm [^1] [^2] | | MOD4 + return | fullscreen mode | | MOD4 + w | qutebrowser [^3] | | MOD4 + t | default tmux session [^4] | | MOD4 + space | dmenu\_run | | XF86\_MonBrightnessDown | light -U 5 | | XF86\_MonBrightnessUp | light -A 5 | | XF86\_AudioLowerVolume | pamixer -d 5 | | XF86\_AudioRaiseVolume | pamixer -i 5 | | XF86\_AudioMute | pamixer -t | [^1]: Resize and reposition windows. Useful when connecting or disconnecting an external monitor, if e.g. screen size differ. [^2]: This should no longer be necessary as the function is called whenever a window is entered. [^3]: Currently requires a hacky solution to avoid a 'No Child Processes' error. [^4]: Highly recommend changing this keybinding to just open a terminal, or create a script called tmux-default in your $PATH that creates/attaches a tmux session. ## Configuration ### Keybindings Keybindings are stored in the keys[] array. Modify them to your liking. ### Gaps Gaps are defined manually with the macros GAP\_TOP, GAP\_LEFT, GAP\_RIGHT, and GAP\_BOTTOM. These values are in pixels. ### Border The border is defined by the macros BORDER\_WIDTH and BORDER\_COLOUR. BORDER\_WIDTH takes an integer value in pixels. BORDER\_COLOUR takes an RGB value in the form "0xRRGGBB". ### Bar In order for the current bar support to function, you will need to define the macros BARCLASS and BARCOMMAND. BARCLASS should be the WM\_CLASS of your chosen bar. (This can be found by running xprop on your bar). BARCOMMAND is the command required to launch your bar. [^5] [^5]: This has only been tested with lemonbar so far. ## Dependencies You need the Xlib header files. ## Installation Clean. $ make clean Compile. $ make Install. $ make install All in one go. $ make clean install Uninstall. $ make uninstall You may need to run install as root. DESTDIR and PREFIX are supported. ## Credits fehawen for all of his previous work on this project and for inspiring me to continue attempting to learn how to write a window manager. i3: https://github.com/i3/i3 \ dwm: https://git.suckless.org/dwm \ sowm: https://github.com/dylanaraps/sowm \ berry: https://github.com/JLErvin/berry \ tinywm: http://incise.org/tinywm.html \ katriawm: https://www.uninformativ.de/git/katriawm \ <file_sep>/Makefile LIBS = -lX11 CFLAGS += -std=c99 -Wall -Wextra -pedantic -Os PREFIX ?= /usr BINDIR ?= $(PREFIX)/bin CC ?= gcc all: vswm vswm: vswm.o $(CC) -o $@ $^ $(LIBS) $(LDFLAGS) install: all install -d $(DESTDIR)$(BINDIR) install -m 755 vswm $(DESTDIR)$(BINDIR) uninstall: rm -f $(DESTDIR)$(BINDIR)/vswm clean: rm -f vswm *.o .PHONY: all install uninstall clean
0d116e62ccca92a0b1c00dc1413a7a3b5b4b9013
[ "Markdown", "C", "Makefile" ]
3
C
dairnarth/vswm
edf9e834a7014c22a4246f9f8d5a69f505bf3a81
621e3fc1404ca082433afb401b8ef4af8c4d399a
refs/heads/master
<file_sep>class FlatsController < ApplicationController def index(list, msg) @flats = list @msg = msg end def new @flat = Flat.new end def show @flat = Flat.find(params[:id]) end def create Flat.create(params_secure) redirect_to flat_path(params[:id]) end def edit @flat = Flat.find(params[:id]) end def update Flat.find(params[:id]).update(params_secure) redirect_to flat_path(params[:id]) end def destroy f = Flat.find(params[:id]) f.destroy redirect_to flats_path end def search if params[:search].nil? index(Flat.all, "") else index(Flat.where('name LIKE ?', "#{params[:search]}"), "You searched for #{params[:search]}. We found #{Flat.where('name LIKE ?', "#{params[:search]}").length} flats out of our #{Flat.all.length} on our website.") end end private def params_secure params.require(:flat).permit(:name, :address, :description, :price_per_night, :number_of_guest) end end
f281c8de1a3a24961e0bbcddcbc539728e8d837b
[ "Ruby" ]
1
Ruby
santigibo/rails-simple-airbnb
ea38f908cd6a6caa93f3733dd465146aab870952
d42286d173d1cdc39b2ae41c0fd03baf0cee5b35
refs/heads/master
<file_sep>var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/tripplanner'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'mongodb connection error:')); var Place, Hotel, ThingsToDo, Restaurant, Day; var Schema = mongoose.Schema; var placeSchema = new Schema ({ address: String, city: String, state: String, phone: String, location: [Number, Number] }); var hotelSchema = new Schema ({ name: String, place: [placeSchema], num_stars: Number, amenities: String }); hotelSchema.pre('save', function(next) { var cleanStars = function(stars) { stars = parseInt(stars, 10); if (stars > 5) return 5; else if (stars < 1) return 1; return stars; }; this.num_stars = cleanStars(this.num_stars); next(); }); var thingsToDoSchema = new Schema ({ name: String, place: [placeSchema], age_range: String }); var restaurantSchema = new Schema ({ name: String, place: [placeSchema], cuisine: String, price: Number }); restaurantSchema.pre('save', function(next) { var cleanPrice = function(price) { price = parseInt(price, 10); if (price > 5) return 5; else if (price < 1) return 1; return price; }; this.price = cleanPrice(this.price); next(); }); var daySchema = new Schema({ dayNum: Number, hotel: [{ type: Schema.Types.ObjectId, ref: 'Hotel' }], restaurant: [{ type: Schema.Types.ObjectId, ref: 'Restaurant' }], thing: [{ type: Schema.Types.ObjectId, ref: 'ThingsToDo' }] }); Place = mongoose.model('Place', placeSchema); Hotel = mongoose.model('Hotel', hotelSchema); ThingsToDo = mongoose.model('ThingsToDo', thingsToDoSchema); Restaurant = mongoose.model('Restaurant', restaurantSchema); Day = mongoose.model('Day', daySchema); module.exports = { 'Place': Place, 'Hotel': Hotel, 'ThingsToDo': ThingsToDo, 'Restaurant': Restaurant, 'Day': Day }; <file_sep>var ActivityView = function(activity, type) { this.activity = activity; this.$el = $( this.render() ); this.generateMarker(type); }; ActivityView.prototype.render = function() { return '<li>' + this.activity.name + '</li>'; }; ActivityView.prototype.generateMarker = function (type) { var color = { hotel : 'blue', thing : 'yellow', restaurant : 'green' }[type]; this.marker = new google.maps.Marker({ map: map, title: this.activity.name, position: this.getLatLng(), icon: 'http://maps.google.com/mapfiles/ms/icons/' + color + '-dot.png' }); }; ActivityView.prototype.getLatLng = function() { var latlngarr = this.activity.place[0].location; return new google.maps.LatLng(latlngarr[0],latlngarr[1]); }; <file_sep>// dependencies: days, DayView, // builds a new day object and calls this.create() to save to server var Day = function() { this.dayNum = days.length + 1; this.hotel = []; this.restaurant = []; this.thing = []; this.dayView = new DayView(this); this.dayBtnView = new DayBtnView(this); //save to the database this.create(); }; // make a new server-side day and set front-end day ID to server day ID Day.prototype.create = function() { var self = this; $.post( '/day', {dayNum: this.dayNum} ).done( function(serverDay) { self._id = serverDay._id; }); }; Day.prototype.addActivity = function(type, id) { for (var i = 0; i < data[type].length; i++) { if (data[type][i]._id === id) { var foundActivity = data[type][i]; var activityView = new ActivityView(foundActivity, type); this[type].push(foundActivity); this.dayView.markers.push(activityView.marker); this.dayView.display[type].append(activityView.$el); break; } } };<file_sep>var ActivitiesView = function(type) { var self = this; var label = {hotel: 'Hotels', restaurant: 'Restaurants', thing: 'Things to Do'}; this.type = type; this.$el = $( this.render(label[type]) ); this.$select = this.$el.find('select'); this.$button = this.$el.find('button'); this.populateList(); $('.top-row').append( this.$el ); this.$button.on('click', function (e) { e.preventDefault(); var id = self.$select.val(); currentDay.addActivity(self.type,id); }); }; ActivitiesView.prototype.populateList = function() { var self = this; data[this.type].forEach( function (datum) { self.$select.append('<option value="' + datum._id + '">' + datum.name + '</option>'); }); }; ActivitiesView.prototype.render = function(label) { return '<div class="col-sm-4 col-xs-12">'+ '<form role="form" class="tp-form">'+ '<label for="' + this.type + 'Select">' + label + '</label>'+ '<div class="row">'+ '<div class="col-xs-9">'+ '<select name="' + this.type + 'Select" class="form-control">'+ '</select>'+ '</div>'+ '<div class="col-xs-3">'+ '<button type="submit" data-select="' + this.type + '" class="btn btn-primary addToDay">Add</button>'+ '</div>'+ '</div>'+ '</form>'+ '</div>'; }; var types = ['hotel', 'restaurant', 'thing']; types.forEach( function (type) { new ActivitiesView(type); });<file_sep>var $daysList = $('#days-list'); var $addDay = $('#addDay'); var $dayTitle = $('#day-title'); var days = []; var types = ['hotel', 'thing', 'restaurant']; var selectors = {}; var currentDay; // Build selectors[] & DOM <option>s (must run above) types.forEach( function (type) { selectors[type] = $('#' + type + 'Select'); data[type].forEach( function (activity) { selectors[type].append('<option value="' + activity._id + '">' + activity.name + '</option>'); }); }); // FUNCTION DECLARATIONS // Ajax call function var newMongoDay = function () { var num = data.day.length; $.post('/day/', {numDays: num}); }; var writeVisitToServer = function (dayId, type, activityId) { var postData = { activityId: activityId, type: type }; // the callback function below will be called if this request completes // successfully. the server's response to this request is passed into // this callback function as "responseData." var postCallback = function (responseData) { console.log('added activity to day ' + dayId); }; // jQuery Ajax call $.post( '/day/' + dayId + '/activity', postData, postCallback); }; // get hotel, thing, or restaurant object by id var findById = function (type, id) { for (var i = 0; i < data[type].length; i++) { if ( data[type][i]._id === id ) { return data[type][i]; } } return null; }; // Day constructor with properties var Day = function() { this.dayNum = days.length + 1; this.hotel = []; this.thing = []; this.restaurant = []; this.markers = []; }; Day.prototype.addActivity = function(type, id) { // body... }; // pushes new Day, calls switchDay, appends button w/ click var addDay = function () { newMongoDay(); var humanNum; // days.push( new Day() ); humanNum = data.day.length; switchDay(humanNum-1); $daysList.append('<button type="button" class="btn btn-default btn-day" id="goToDay' + humanNum + '">Day ' + humanNum + '</button>'); $( '#goToDay' + humanNum ).click( function (e) { e.preventDefault(); switchDay( Number(humanNum - 1) ); }); }; // takes activity object and returns google API coordinates var getGLatLng = function(activity) { var latLngArr = activity.place[0].location; return new google.maps.LatLng(latLngArr[0], latLngArr[1]); }; // deletes markers from map and from markers[] var clearMarkers = function () { while (currentDay.markers.length) { currentDay.markers.pop().setMap(null); } }; // draws markers for currentDay and sets them as markers[] var putMarkersOnMap = function () { if (currentDay.markers) { clearMap(null); currentDay.markers = []; } types.forEach( function (type) { var color = { hotel : 'blue', thing : 'yellow', restaurant : 'green' }[type]; currentDay[type].forEach ( function (activity) { currentDay.markers.push( new google.maps.Marker({ map: map, title: activity.name, position: getGLatLng(activity), icon: 'http://maps.google.com/mapfiles/ms/icons/' + color + '-dot.png' })); }); }); }; // renders itinerary DOM based on currentDay var renderDayPanel = function() { var str = '<li><h3>Hotel</h3><ul class="list-unstyled">'; currentDay.hotel.forEach(function(h) { str += '<li>' + h.name + '</li>'; }); str += '</ul></li><li><h3>Restaurants</h3><ul class="list-unstyled">'; currentDay.restaurant.forEach(function(h) { str += '<li>' + h.name + '</li>'; }); str += '</ul></li><li><h3>Things to Do</h3><ul class="list-unstyled">'; currentDay.thing.forEach(function(h) { str += '<li>' + h.name + '</li>'; }); str += '</ul></li>'; $('#day-panel').html(str); }; // sets all currentDay.markers to null map var clearMap = function () { for (var i = 0; i < currentDay.markers.length; i++) { currentDay.markers[i].setMap(null); } }; // change DOM title, clears today map, switches days & draws var switchDay = function (dayTarget) { $dayTitle.html('Plan for Day ' + Number(dayTarget + 1) ); if (currentDay) clearMap(); currentDay = data.day[dayTarget]; renderDayPanel(); putMarkersOnMap(); }; // not working yet var findMarkerIndex = function (title) { for (var i = 0; i < currentDay.markers.length; i++) { if (currentDay.markers[i].title === title) return i; } return null; }; // not currently working var removeItem = function(name, type) { console.log('Trying to delete '+ name + ' of ' + type); currentDay.markers[findMarkerIndex(name)].setMap(null); currentDay.markers.splice( findMarkerIndex(name), 1 ); if (type === 'hotel') { currentDay.hotel = ''; } else if (type === 'thing') { currentDay.things.splice(currentDay.things.indexOf(name), 1); } else { currentDay.restaurants.splice(currentDay.restaurants.indexOf(name), 1); } }; // BIND HANDLERS & INSTANTIATE // adds click events to 'add' activity buttons $('.addToDay').on( 'click', function(e) { e.preventDefault(); var type = $(this).attr('data-select'); var selection = $(selectors[type]); var id = selection.val(); if (!currentDay) return alert('You need to select a day before adding activities'); if ( type === 'hotel' || (type === 'restaurant' && currentDay[type].length === 3) ) { currentDay[type].shift(); } currentDay[type].push( findById(type,id) ); renderDayPanel(); putMarkersOnMap(); writeVisitToServer(currentDay.dayNum, type, id); }); // adds click event to 'add day' button $addDay.click( function (e) { e.preventDefault(); addDay(); }); // Instantiate the first day. :-) addDay();<file_sep>// dependencies: switchDay (in days model) var DayBtnView = function (day) { this.day = day; this.$el = $( this.render() ); var self = this; this.$el.on('click', function() { switchDay(self.day); }); }; DayBtnView.prototype.render = function() { return '<button class="btn btn-default">Day ' + this.day.dayNum + '</button>'; };
89e363e023fa23d0e353383b5bb7cd6d5e72caea
[ "JavaScript" ]
6
JavaScript
jaimieli/tripplanner
0a1dc005805a89f82abf97233d646f9aef2afe71
c3c655d694571381de1f54c852461cb52b399be7
refs/heads/master
<repo_name>Polak149/Unity<file_sep>/Assets/Standard Assets/LavaPackage/Lava3/Sources/Scripts/lavaUnderwaterFree.js var enableUnderlavaEffect = true; var lavaLevel = 20; var enableDeathLavaAnimation = true; var playerObject : GameObject; var steamSound : GameObject; var screamSound : GameObject; var cameraObject : GameObject; var lightObject : GameObject; private var steamFlag = false; private var i = 0.0; private var originalColour; originalColour = renderer.material.color; private var playerPos:Vector3; playerPos = playerObject.transform.position; private var RotZ; RotZ = transform.eulerAngles.z; private var x; private var y; private var z; private var r; r = transform.localPosition.z; private var angleX; private var angleY; private var positionZ; positionZ = transform.localPosition.z; private var positionY; positionY = transform.localPosition.y; private var positionX; positionX = transform.localPosition.x; function FixedUpdate() { //rotating and moving object as camera is looking angleX = cameraObject.transform.eulerAngles.x* Mathf.PI/180; angleY = cameraObject.transform.eulerAngles.y* Mathf.PI/180; playerPos = playerObject.transform.position; //rotating Underlava plain as camera goes transform.eulerAngles = new Vector3((-1)*cameraObject.transform.eulerAngles.x+90, playerObject.transform.eulerAngles.y+180, RotZ); //moving Underlava plain as camera goes angleX = cameraObject.transform.eulerAngles.x * Mathf.PI/180; y = r*Mathf.Sin(angleX); z = r-r*Mathf.Cos(angleX); transform.localPosition.z = positionZ - z; transform.localPosition.y = positionY - y; //main function if(playerPos.y<lavaLevel+12 && enableUnderlavaEffect == true) { if (i<=1 && i>=0) i+=0.01; renderer.renderer.material.color = new Color(originalColour.r, originalColour.g, originalColour.b, i); lightObject.light.intensity = 8; if (enableDeathLavaAnimation==true) { //Disabling any movement SpecjalBehaviour.DisableMovement(); // camera rotation if (cameraObject.transform.eulerAngles.x>0 && cameraObject.transform.eulerAngles.x<=90) cameraObject.transform.eulerAngles.x -=5; if (cameraObject.transform.eulerAngles.x<360 && cameraObject.transform.eulerAngles.x>=270) cameraObject.transform.eulerAngles.x +=5; //sinking if (playerObject.transform.position.y >22) playerObject.transform.position.y -= 0.1; //sound of burning in lava if (steamFlag == false) { screamSound.audio.Play(); steamSound.audio.Play(); steamFlag = true; } } } else { i=0; steamFlag = false; renderer.material.color = new Color(originalColour.r, originalColour.g, originalColour.b, i); lightObject.light.intensity = 0; } }<file_sep>/Assets/Standard Assets/Editor/MorphInspector.cs using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(MorphMaster))] class MorphInspector : Editor { public override void OnInspectorGUI () { MorphMaster master = (MorphMaster)target; EditorGUILayout.BeginVertical(); GUILayout.Label (" Morphs: "); for (int a = 0; a < master.morphs.Count; a++) { EditorGUILayout.Space(); MorphTarget morph = master.morphs[a]; if (! morph.morph) morph.expandedEdit = true; EditorGUILayout.BeginHorizontal(); string nn = EditorGUILayout.TextField(morph.morphName); if (nn != morph.morphName) morph.morphName = nn; if (morph.expandedEdit) { if (morph.morph) { if (GUILayout.Button ("(delete)")) { master.morphs.RemoveAt(a); a--; } if (GUILayout.Button ("(Shrink)")) morph.expandedEdit = false; } else { if (GUILayout.Button ("(delete)")) { master.morphs.RemoveAt(a); a--; } } } else { if (GUILayout.Button ("(Details)")) morph.expandedEdit = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); float val = EditorGUILayout.Slider(morph.percent, Mathf.Min(morph.percent, morph.min), Mathf.Max (morph.percent, morph.max)); if (val != morph.percent) { morph.percent = val; master.Regenerate(); } if (GUILayout.Button("rand")) { morph.SetRandomly(); master.ApplyMorphs(); } EditorGUILayout.EndHorizontal(); if (morph.expandedEdit) { string label = "Mesh:"; if (! morph.morph) label = "MESH NEEDED ----->"; Mesh newmesh = (Mesh)EditorGUILayout.ObjectField(label, morph.morph, typeof(Mesh), true); if (newmesh != morph.morph) { morph.morph = newmesh; morph.Regenerate(master); } val = EditorGUILayout.FloatField("Min:", morph.min); if (val != morph.min) morph.min = val; val = EditorGUILayout.FloatField("Max:", morph.max); if (val != morph.max) morph.max = val; GUILayout.Label ("Randomization Info:"); EditorGUILayout.BeginHorizontal(); GUILayout.Label ("% Chance: "); val = EditorGUILayout.Slider(morph.randomActivationChance, 0, 1); if (val != morph.randomActivationChance) morph.randomActivationChance = val; EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); } if (GUILayout.Button("Add Morph")) master.morphs.Add(new MorphTarget()); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label (" Master Controls: "); if (GUILayout.Button("Randomize All")) { master.Randomize(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.ObjectField("Mesh:", master.baseMesh, typeof(Mesh), true); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Regenerate")) master.Regenerate(); if (GUILayout.Button("Delete and regenerate")) { master.baseMesh = null; master.Regenerate(); } EditorGUILayout.EndHorizontal(); GUILayout.EndVertical(); } } <file_sep>/Assets/Standard Assets/Character Controllers/Sources/Scripts/SpecjalBehaviour.js private var x = 0.0; private var y = 0.0; private var z = 0.0; //AIR FLOAT VAR private static var i=0; private static var flag = false; private static var restartFlag = true; static var flapSound; flapSound = GameObject.Find("flap sound"); //MOVEMENT var disableMovementButton = false; var enableMovementButton = false; static var movement = true; //OTHER var lavaDisableResetButton = false; //!!!!BEHAVIOURS!!!!!\\ //---MOVEMENT---\\ static function EnableMovement() { movement = true; } static function DisableMovement() { movement = false; } function Update () { //Enable Movement if (enableMovementButton == true && movement == false) { EnableMovement(); enableMovementButton = false; } if (disableMovementButton == true && movement == true) { DisableMovement(); disableMovementButton = false; } //Lava disable reset if (lavaDisableResetButton == true) { EnableMovement(); transform.position.y +=100; lavaDisableResetButton = false; } } <file_sep>/Assets/Standard Assets/LavaPackage/Lava3/Sources/Scripts/bubble script.js var maxX : float; var minX : float; var maxZ : float; var minZ : float; var maxY : float; var minY : float; var bobbles : int; // createt boobles per frame var bubbleObject : GameObject; private var call:boolean = true; private var bobbleArray = new Array(); private var i; function Start() { bobbleArray.length = bobbles; for (i = 0; i<bobbleArray.length; i++) { bobbleArray[i] = Instantiate(bubbleObject, Vector3(Random.Range(minX,maxX),Random.Range(minY,maxY),Random.Range(minZ,maxZ)), transform.rotation); bobbleArray[i].animation["sinking"].wrapMode = WrapMode.Loop; bobbleArray[i].animation.Play ("sinking"); bobbleArray[i].audio.Play(); } } function Update () { for (i = 0; i<bobbleArray.length; i++) { bobbleArray[i] = Instantiate(bubbleObject, Vector3(Random.Range(minX,maxX),Random.Range(minY,maxY),Random.Range(minZ,maxZ)), transform.rotation); bobbleArray[i].animation.Play ("sinking"); bobbleArray[i].audio.Play(); Destroy(bobbleArray[i], bobbleArray[i].animation["sinking"].length); } } <file_sep>/Assets/Standard Assets/Scripts/MorphTarget.cs using UnityEngine; using System.Collections; [System.Serializable] public class MorphTarget { public string morphName = "?"; public bool expandedEdit = false; public Mesh morph; public float percent = 0; public float min = -1; public float max = 2; public float randomActivationChance = 1; protected float lastPercent = 0; /// <summary> /// Optimization should help the speed some, instead of recalculating the offsets /// each time anything changes in any of them. /// </summary> protected Vector3[] offVert, offNorm; public void Regenerate(MorphMaster master) { Debug.Log ("Generating offset data for morph " + morphName + " on " + master.name); Mesh baseMesh = master.baseMesh; offVert = new Vector3[baseMesh.vertexCount]; offNorm = new Vector3[baseMesh.vertexCount]; for (int a=0; a < baseMesh.vertices.Length; a++) { offVert[a] = morph.vertices[a] - baseMesh.vertices[a]; offNorm[a] = morph.normals[a] - baseMesh.normals[a]; } master.ApplyMorphs(); } public void ApplyMorph(MorphMaster master, ref Vector3[] verts, ref Vector3[] normals) { Debug.Log("Applying morph " + morphName + " at " + percent); if ((offVert == null) || (offVert.Length == 0)) { Regenerate (master); } for (int a=0; a < verts.Length ; a++) { verts[a] += offVert[a] * percent; normals[a] = (normals[a] + offNorm[a] * percent).normalized; } lastPercent = percent; } public void SetRandomly() { if (Random.value > randomActivationChance) { percent = 0; return; } percent = Random.value * (max - min); percent += min; } } <file_sep>/Assets/Standard Assets/Scripts/MorphMaster.cs using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Using Morph Master allows you to use Blender Shape Keys in Unity. Setup: you must save /// a distinct blender file with each shape key in turn, as well as the fundamental file /// you plan to use as your baseline. Drag your rigged entity (rigging optional) onto the /// scene view, then add Morph Master, and one Morph Target for each shape key file. /// </summary> public class MorphMaster : MonoBehaviour { public List<MorphTarget> morphs = new List<MorphTarget>(); /// <summary> /// The active mesh within the mesh filter. /// </summary> protected Mesh activeMesh; /// <summary> /// This is the original sharedMesh. /// </summary> public Mesh baseMesh; // Use this for initialization void Start () { Regenerate (); } // Update is called once per frame void Update () { } public void Regenerate() { bool resetSource = baseMesh != null; if (resetSource) Debug.Log ("Our Shared Mesh is a custom mesh, so we'll reset it to the original shared mesh."); else Debug.Log ("We are presuming our Shared Mesh is the source mesh, and saving it as an original."); MeshFilter filter = GetComponent<MeshFilter>(); if (filter) { if (resetSource) filter.sharedMesh = baseMesh; else baseMesh = filter.sharedMesh; activeMesh = (Mesh)Mesh.Instantiate(baseMesh); activeMesh.name = "MORPH CLONE VARIANT ON " + activeMesh.name; filter.sharedMesh = activeMesh; } else { SkinnedMeshRenderer smr = GetComponent<SkinnedMeshRenderer>(); if (smr) { if (resetSource) smr.sharedMesh = baseMesh; else baseMesh = smr.sharedMesh; activeMesh = (Mesh)Mesh.Instantiate(baseMesh); activeMesh.name = "MORPH CLONE VARIANT ON " + activeMesh.name; smr.sharedMesh = activeMesh; } else { Debug.LogError("I couldn't find a mesh rendering class!"); return; } } ApplyMorphs (); } public void Randomize() { for (int a = 0; a < morphs.Count; a++) morphs[a].SetRandomly(); ApplyMorphs (); } public void ApplyMorphs() { if (! activeMesh) Regenerate(); Vector3[] verts = baseMesh.vertices; Vector3[] normals = baseMesh.normals; for (int a = 0; a < morphs.Count; a++) { morphs[a].ApplyMorph(this, ref verts, ref normals); } activeMesh.vertices = verts; activeMesh.normals = normals; activeMesh.RecalculateBounds(); } } <file_sep>/Assets/Standard Assets/Scripts/General Scripts/skrzydlaczscript.js var speed : float; var radius : float; var rotationOffset : float; var randomAngle : boolean; var changeDirection : boolean; private var angle; private var x; private var z; private var oryginalX; private var oryginalZ; private var rotationAngle; function Start() { //randomize starting angle and setting object rotation if (randomAngle) { angle = Random.Range(0.0,360.0)* Mathf.PI/180; transform.eulerAngles.y = angle*180/Mathf.PI + rotationOffset; } else angle = rotationOffset; // saving oryginal position oryginalX = transform.position.x; oryginalZ = transform.position.z; } function Update () { if (!changeDirection) { angle += speed*Mathf.PI/180; transform.eulerAngles.y = -angle*180/Mathf.PI + rotationOffset; } else { angle -= speed*Mathf.PI/180; transform.eulerAngles.y = -angle*180/Mathf.PI - rotationOffset; } if (angle>2*Mathf.PI) { angle -=2*Mathf.PI; } x = Mathf.Cos(angle)*radius; z = Mathf.Sin(angle)*radius; transform.position.x = oryginalX + x; transform.position.z = oryginalZ + z; }<file_sep>/Assets/Standard Assets/LavaPackage/Lava3/Sources/Scripts/LavaTrigger.js var movieSpeed : float = 0.1; var movieFrame : Texture[]; var redPlain : Texture; var steamSound : GameObject; static var lava : boolean = false; private var i=0; private var startFlag = false; private var alphaValue : float = 0.0; private var alphaValuePlain : float = 0.0; private var guiEffectStart : float = 1000; private var guiEffectEnd : float = 700; private var burningScaling : float; private var animationWidth; private var animationHeight; static var lavaDeath : boolean = false; var burningDamage : float = 2; var life = 0; function Start() { animationHeight = Screen.height+guiEffectStart; animationWidth = Screen.width+guiEffectStart; } function OnTriggerEnter() { Debug.Log("wpadl do lawy"); lava = true; } function OnTriggerExit() { Debug.Log("wyszedł z lawy"); lava = false; } function LateUpdate() { if (lava == true) { if (!startFlag) { steamSound.audio.volume = 1; steamSound.audio.Play(); startFlag = true; if (burningScaling<30) burningScaling = guiEffectStart*burningDamage/(life+0.1); } if (alphaValue <= 1) alphaValue += 0.05; //and assign the value of it to a variable if (animationWidth-burningScaling>Screen.width+guiEffectEnd) animationWidth -= burningScaling; if (animationHeight-burningScaling>Screen.height+guiEffectEnd) animationHeight -= burningScaling; if (life>0) life -=burningDamage; else { SpecjalBehaviour.movement = false; lavaDeath = true; } } else { if (alphaValue > 0) alphaValue -= 0.02; //and assign the value of it to a variable if (animationWidth+burningScaling<=Screen.width+guiEffectStart+guiEffectEnd) animationWidth += burningScaling/2; if (animationHeight+burningScaling<=Screen.height+guiEffectStart+guiEffectEnd) animationHeight += burningScaling/2; if(steamSound.audio.volume <= 0) steamSound.audio.Stop(); else steamSound.audio.volume -= 0.1; startFlag = false; } } function OnGUI () { var colPreviousGUIColor : Color = GUI.color; //assign variable to current GUI color (just in case you're using a different value other than default) GUI.color = new Color(colPreviousGUIColor.r, colPreviousGUIColor.g, colPreviousGUIColor.b, alphaValue); //Assign new color to GUI, only affecting the alpha channel if (alphaValue>0)//burning animation support { if (i>=movieFrame.length-1) i=0; else i++; wait(movieSpeed); GUI.DrawTexture(new Rect((animationWidth-Screen.width)/-2,(animationHeight-Screen.height)/-2, animationWidth, animationHeight), movieFrame[i]); //exist until visible } GUI.color = colPreviousGUIColor; //Reset alpha and color. DrawWithoutAlpha(); } function DrawWithoutAlpha() { var colPreviousGUIColor : Color = GUI.color; //assign variable to current GUI color (just in case you're using a different value other than default) GUI.color = new Color(colPreviousGUIColor.r, colPreviousGUIColor.g, colPreviousGUIColor.b, alphaValuePlain); //Assign new color to GUI, only affecting the alpha channel if (lavaDeath) { alphaValuePlain+=0.0035; GUI.DrawTexture(new Rect (0, 0, animationWidth, animationHeight), redPlain); //exist until visible } } function wait(time) { yield WaitForSeconds(time); } <file_sep>/Assets/MetaMorph/Scripts/PlayMoon DEMO.js var soundclip : AudioClip; var TextObject : GameObject; function Start () { // Let's wait for the sytem to finsh loading... yield WaitForSeconds (2); while ( true ) // This is an endless loop, bu we want it this way for the demo... { var lines_of_data = new Array(); // Okay, let's start animating the skeleton. While this is not a part of MetaMorph, it // does show how skeletal animation and mesh deformation can work together. animation.Play("Sing", PlayMode.StopAll); // Let's start a Morph animation from an exported blender ShapeKey animation file. // We run these by name. Display_Text(lines_of_data, "Playing 0 Seconds......................."); Display_Text(lines_of_data, "Example of running an animation synched to bones and music..."); var aanimation = "<NAME>"; mm_Animate_Play( aanimation, 1.0, 0 ); // Why are we waiting if MetaMorph can synch? Sound does not always synch the same between systems. // In this case, there seems to be a 0.2 second differance between blender playing the song, and Unity // It may not always be this large of a gap, or might be larger. yield WaitForSeconds (0.2); // Play the sound file "I'm your Moon" by <NAME> // http://www.jonathancoulton.com/2006/08/25/thing-a-week-47-im-your-moon/ // Thanks for the demo song! In exchange, I now share a Charon MoonMon model, // the MetaMorph codebase, and anything else in this Unity Pak... audio.PlayOneShot(soundclip); // Let's let the Bones, Morph, and Sound play out... yield WaitForSeconds (10); Display_Text(lines_of_data, "Playing 10 Seconds......................."); Display_Text(lines_of_data, "Example of running a morph while an animation is running: Smile!"); mm_Morph_Add( "Charon-Smile", 0.0, 1.0, 1.0); yield WaitForSeconds (10); Display_Text(lines_of_data, "Playing 20 Seconds......................."); Display_Text(lines_of_data, "Example of running multiple morphs while an animation is running: Wink!"); mm_Morph_Add( "Charon-Left Eye Close", 0.0, 1.0, 0.1); mm_Morph_Add( "Charon-Cheek Up Left", 0.0, 1.0, 0.1); mm_Morph_Add( "Charon-Brow-Left", 0.0, 1.0, 0.1); yield WaitForSeconds (1); Display_Text(lines_of_data, "And kill the morphs to unwink..."); mm_Morph_Remove( "Charon-Left Eye Close", 0.3); mm_Morph_Remove( "Charon-Cheek Up Left", 0.3); mm_Morph_Remove( "Charon-Brow-Left", 0.3); yield WaitForSeconds (9); Display_Text(lines_of_data, "Playing 30 Seconds......................."); yield WaitForSeconds (1); Display_Text(lines_of_data, "In a few moments, that animation we started a while back will do something..."); yield WaitForSeconds (1); Display_Text(lines_of_data, "(Yes, not only is it still going, it staying synched with the bones 35 seconds later)"); yield WaitForSeconds (1); Display_Text(lines_of_data, "And let's turn off the smile for this..."); mm_Morph_Remove( "Charon-Smile", 0.5); yield WaitForSeconds (7); Display_Text(lines_of_data, "Playing 40 Seconds......................."); yield WaitForSeconds (1); Display_Text(lines_of_data, "See? Nice huh? Some day I may finish this lipsynch. Maybe..."); yield WaitForSeconds (1); Display_Text(lines_of_data, "It still shows that long morph animations can be used with bones for character work..."); yield WaitForSeconds (1); yield WaitForSeconds (7); Display_Text(lines_of_data, "Playing 40 Seconds......................."); yield WaitForSeconds (1); Display_Text(lines_of_data, "Time to clean up... Killing bone animation, song, and any the animation is still running (which it is not.)"); // Let's clean up after ourselves, shall we? yield WaitForSeconds (1); // Stop the audio audio.Stop(); // Stop the bones animation.Stop("Sing"); // And an example of how to check is an animation is still running and kill it if it is... result = mm_Animate_Frame( aanimation ); // Why return an array? For nulls. Null means it's no longer playing. // zero just means it may be on the first frame. if (result == null) { Display_Text(lines_of_data, "<NAME> is done!"); } else { Display_Text(lines_of_data, "<NAME> still playing at: " + result[0]); Display_Text(lines_of_data, "Stopping "+aanimation); mm_Animate_Stop( aanimation, 1 ); } yield WaitForSeconds (10); Display_Text(lines_of_data, "Okay, At the bottom of the script PlayMoon.js is a basic API manual. You have a lot of options..."); yield WaitForSeconds (1); Display_Text(lines_of_data, "Feel free to use this script to try them out and see how they work..."); yield WaitForSeconds (1); Display_Text(lines_of_data, "The MetaMorph.js is the actual program that does the morph work..."); yield WaitForSeconds (1); Display_Text(lines_of_data, "Everything is commented, so be sure to have a look around... "); yield WaitForSeconds (1); Display_Text(lines_of_data, "Modding this for your own use is why we gave away the source code."); yield WaitForSeconds (1); Display_Text(lines_of_data, "Be sure to thank Rezzable.com and Heritage-Key.com for allowing this code to go public."); yield WaitForSeconds (5); Display_Text(lines_of_data, "And now for something totally wierd..."); yield WaitForSeconds (3); animation.Play("Melt", PlayMode.StopAll); mm_Animate_Play( "<NAME>", 1.0, 1 ); yield WaitForSeconds (5); Display_Text(lines_of_data, "Looping Demo in 10 seconds..."); yield WaitForSeconds (8); animation.Play("Sing", PlayMode.StopAll); mm_Animate_Stop( "<NAME>", 0.0 ); yield WaitForSeconds (0.1); animation.Stop(); yield WaitForSeconds (2); mm_SetShape_Reset( ); //And loop... } } // -------------------------------------------------------------------------------------------------------------------------------------------- // METAMORPH LINK CODE. API INFORMATION FOLLOWS. // -------------------------------------------------------------------------------------------------------------------------------------------- // ---------------------------------------------------------------------- // The following code allows easy relay to the metamorph script. // You can just call directly instead of relaying, but this was // Added for ease-of-use. // ---------------------------------------------------------------------- var MetaMorphScriptObject : GameObject; // This is the object the MetaMorph Script is in. You could assign this by code of Inspector... // Used for function mm_Animate_Play below. private var Animation_Style_End : int = 0; private var Animation_Style_Freeze : int = 1; private var Animation_Style_Loop : int = 2; private var Animation_Style_PingPong : int = 3; // Morph Functions function mm_Morph_Add( Morph_Name : String, Start_Level : float, End_Level : float, TimeFrame : float ) { // Morph_Name: this is the name of the morph, as designated in Diff_Maps.Name // Start_Level: sets the starting morph level. normally, you would use zero to start // End_Level: The morph level you want to end up at. // TimeFrame: How long to take to fade from start to end. // Keep in mind, even when the morph has finished timeframe, it's still morphing the mesh every frame until stopped by mm_Morph_Remove. // If you want to have a morph be added 'permanenty' to the mesh, use mm_SetShape_Set. // These work with mm_Animate_Play, allowing you to use morphs while animations are running. // This is good for things like randomized blinking, for example. // morph effects are additive, meaning that two morphs with overlapping effects do not average, they add to each other. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_Morph_Add( Morph_Name, Start_Level, End_Level, TimeFrame ); } function mm_Morph_Remove(Morph_Name : String, TimeFrame : float) { // Morph_Name: this is the name of the morph to stop effecting the mesh. // TimeFrame: is how long it takes for the morph to fade out. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_Morph_Remove( Morph_Name, TimeFrame ); } function mm_Morph_Level( Morph_Name : String ) : Array // [float] { // Morph_Name: this is the name of the morph you are questing information on. // If the returned array is null, then the morph is not active. Otherwise, array[0] is a float of how much the morph is effecting the mesh. link = test_MetaMorph_Link(MetaMorphScriptObject); return (link.GetComponent(MetaMorph).mm_Morph_Level( Morph_Name )); } function mm_Morph_Playing( ) : Array // strings { // Morph_Name: this is the name of the morph you are questing information on. // returns an array of all the morphs (not animations or Setshapes) effecting the mesh. link = test_MetaMorph_Link(MetaMorphScriptObject); return (link.GetComponent(MetaMorph).mm_Morph_Playing( )); } // Animation Functions function mm_Animate_Play( Morph_Animation_Name : String, Speed_Multiple : float, Style : int ) { // Morph_Animation_Name: The name of the animation you are starting from Animation_Recordings.Name // Speed_Multiple: This allows you to speed up and slow down an animation. 1.0 is normal. Higher is faster. Lower is slower. // Style: Animation_Style_End = 0, Animation_Style_Freeze = 1, Animation_Style_Loop 2, Animation_Style_PingPong = 3 // These are NOT morphs, though they use Morph data. They are datastreams of morph levels stored by frame. // They are use to play back complex animation from Blender 3d made with shapekeys. // Starts playing an animation. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_Animate_Play( Morph_Animation_Name, Speed_Multiple, Style ); } function mm_Animate_Stop( Morph_Animation_Name : String, Ease_Out : float ) { // Morph_Animation_Name: Name of the animation to stop. // Ease_Out: How long to take easing out of the animation running. // stops an animation by fading it out. To fade it out instantly, use and ease_out of zero. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_Animate_Stop( Morph_Animation_Name, Ease_Out ); } function mm_Animate_Frame( Morph_Animation_Name : String ) : Array // [int] { // Morph_Animation_Name: Name of the animation to get the current frame from. // returns the current frame of the animation. // returns the current frame being played of the named animation. link = test_MetaMorph_Link(MetaMorphScriptObject); return (link.GetComponent(MetaMorph).mm_Animate_Frame( Morph_Animation_Name )); } // gives a list of the names of currently playing animations. function mm_Animate_Playing( ) : Array // strings { // returns a list of the names of currently playing animations. link = test_MetaMorph_Link(MetaMorphScriptObject); return (link.GetComponent(MetaMorph).mm_Animate_Playing( )); } // ---------------------------------------------------------------------- // SetShape Functions // ---------------------------------------------------------------------- function mm_SetShape_Set( Morph_Name : String, Morph_Level : float ) { // Morph_Name: Name of the morph to apply. // Morph_Level: How much to apply it. 1.0 is fully. // With this, you can set a morph shape into the default mesh. // This means no FPS cost for it to be visible, but a large cost to set it. // Do NOT call this per frame. Use the mm_Morph set of functions to animate getting to a shape, and then kill the morph while setting the shape. // It stacks, so each new shape added is added to all the previous ones. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_Animate_Play( Morph_Name, Morph_Level,0 ); } function mm_SetShape_Reset( ) { // This function resets the modded mesh back to the default. // Again, this is for SetShape, and does not effect morphs or animations. link = test_MetaMorph_Link(MetaMorphScriptObject); link.GetComponent(MetaMorph).mm_SetShape_Reset( ); } // ---------------------------------------------------------------------- // Tool Functions // ---------------------------------------------------------------------- // This is a debug function. // It's not needed, but tries to find the metamorph script in the MetaMorphScriptObject, then the same object, and then just complains and quits... function test_MetaMorph_Link(MetaMorphObj : GameObject) { var ActualMetaMorphObj : GameObject; if(MetaMorphObj.GetComponent(MetaMorph)) { ActualMetaMorphObj = MetaMorphObj; } else if (!gameObject.GetComponent(MetaMorph)) { ActualMetaMorphObj = gameObject; } else { Debug.Log("Cannot find Object with MetaMorph Script."); Debug.Break(); } return ActualMetaMorphObj; } // This tool just outputs the text to the debug window and text mesh... function Display_Text(lines_of_data : Array , textdata : String) : Array { lines_of_data.Add(textdata); if (lines_of_data.length > 8) { lines_of_data.RemoveAt(0); } var textbox : String = ""; for (var x : int = 0 ; x < lines_of_data.length ; x++) { textbox = textbox + lines_of_data[x] + "\n"; } TextObject.GetComponent(TextMesh).text = textbox; print (textdata); return lines_of_data; } <file_sep>/Assets/MetaMorph/Scripts/MetaMorph.js // ----------------------------------------------------------------------- // Classes and variables for MetaMorph // ----------------------------------------------------------------------- // MetaMorph_Settings stores key settings for the MetaMorph Toolkit. var MetaMorph_Settings : MetaMorph_Setting_class; class MetaMorph_Setting_class { var MM_Mesh_Object : GameObject; // This is the pointer to the mesh this script should be effecting. var MM_Is_Boned : boolean = true; // If true, then this mesh has bones. false is used for meshes with no bones, var MM_UV_Layer_One : boolean = true; // If true, use the first UV layer. Otherwise use the second. var MM_Recalculate_Normals : boolean = false; // This decides if "mesh.RecalculateNormals()" is run each frame the mesh is changed. Expensive, so don't use it unless you have to. var MM_Only_When_Visible : boolean = true; // This sets if MetaMorph animates meshes that are not currently being seen. var MM_Verbose : int = 0; // 0 = quiet, 1 = notices, 2 = streaming data. } // Diff_Maps store the Diff Map textures that each represent a shapekey from blender. var Diff_Maps : Diff_Map_class[]; class Diff_Map_class { var Name : String; // This name acts as the ID for a shapekey item. It needs to be the same name as the shapekey in blender. var DM_Image : Texture2D; // This is the DiffMap texture used to reshape the mesh var DM_Multiplier : float = 0.0; // This multiplier should be the same as in the animation textfiles. var DM_Scale : Vector3 = Vector3(1,1,1); // This allows adjustment of the shape on xyz scales. Not normally needed. } // Animation_Recordings store the text files that allow keyframed shapekeys to be used from blender. var Animation_Recordings : Animation_Recording_class[]; class Animation_Recording_class { var Name : String; // This name acts as the ID for a shapekey animation set. var AR_Text : TextAsset; // This is the textfile with the animation data. } // ----------------------------------------------------------------------- // Global variables // ----------------------------------------------------------------------- private var Is_Visible = false; // Internal check so see if the mesh is currently visible. private var Is_Ready = false; // Internal check so see if the mesh is finished loading data. private var MeshChanged = 0; // Internal check so see if the mesh has changed. private var mesh : Mesh; // Link to the mesh object. private var Base_Mesh = new Array (); // This mesh data is the original set. it is NEVER modified. Backup copy for resets. private var Mod_Mesh = new Array (); // This mesh data is used for modding and morphing. // Storage for seam stitcher data. This data stores the information needed to reconnect the UV seams on the mesh after a morph. private var Seam_Verts = new Array (); private var Seam_NextSameVert = new Array (); // Storage for the shapes taken from Diff_Maps. This is a paired array set. That means they are used at the same time, and have to use the same array pointer to be useful. // The reason the morphs use this trick to store data, is if it stored the whole mesh set from Base_Mesh, it would take to long to process every frame. // This way, you only pay for what is being morphed. private var Morph_Shapes_Data = new Array (); // This data is an array of an array[Diffmap number][vector3 vert data]. It only stores the verys being moved, using Morph_Shapes_Links below to know what's relative to Base_Mesh. private var Morph_Shapes_Links = new Array (); // This data is an array of an array[Diffmap number][links to verts in Base_Mesh]. The order of this array is relative to Morph_Shapes_Data above. private var Morph_Animation_Data = new Array (); // This data is an array of [animation number][line number / frame +3][individual data for each Diffmap number]. private var Playing_Animations = new Array (); // array [Animation_Recording#] [line] [single-entry] // ----------------------------------------------------------------------- // Main Functions // ----------------------------------------------------------------------- function Start() { // Let's load all the animations and morphs... Init_MetaMorph(); } function Update () { // Process all Morph animations... // Note this neat trick where we only process animations every other frame. For facial morphs, this can be a serious saver // Remove it if you want... if (Time.frameCount % 2 == 0) Apply_Morphs(); } function OnBecameInvisible () { // We need a Mehs render for this to work. You may need to either place this script in the mesh itself, or place a mesh renderer component into the object this script is in. // If not, then turn off MetaMorph_Settings.MM_Only_When_Visible. if (MetaMorph_Settings.MM_Only_When_Visible) { Is_Visible = false; } } function OnBecameVisible() { // We need a Mehs render for this to work. You may need to either place this script in the mesh itself, or place a mesh renderer component into the object this script is in. // If not, then turn off MetaMorph_Settings.MM_Only_When_Visible. Is_Visible = true; } function OnDisable() { //This code resets the mesh back to normal after you quit out of the game. // Not sure why it doesn't reset on it's own, but there you have it. Mod_Mesh = Base_Mesh; mesh.vertices = Base_Mesh.ToBuiltin(Vector3); RecalcNorms(); } // ----------------------------------------------------------------------- // Init Functions (These are called by Start, and are run only ONCE) // ----------------------------------------------------------------------- function Init_MetaMorph() { // Here we load all the data into the MetaMorph system. // Unti it finishes loading, commands will not really work. Load_Mesh_Data(); Load_Mesh_Seams(); Load_Diff_Maps(); Load_Animation_Recordings(); // Everything is loaded. Let the morphing BEGIN!!! // Or at least become available. Is_Ready = true; // Oh and let seen if it is visible. // And or if MetaMorph_Settings.MM_Only_When_Visible is true... if (MetaMorph_Settings.MM_Mesh_Object.renderer.isVisible || !MetaMorph_Settings.MM_Only_When_Visible) { Is_Visible = true; } } function Load_Mesh_Data() { Report("Loading Mesh Data", 1); // setup mesh based on type of object. if (MetaMorph_Settings.MM_Is_Boned == true) { mesh = MetaMorph_Settings.MM_Mesh_Object.GetComponent(SkinnedMeshRenderer).sharedMesh ; } else { mesh = MetaMorph_Settings.MM_Mesh_Object.GetComponent(MeshFilter).mesh ; } Base_Mesh = mesh.vertices; // This data is for restoring the original mesh. Mod_Mesh = mesh.vertices; // And this is for modding. } function Load_Mesh_Seams() { Report("Loading Mesh Seams", 1); //This function finds inital overlapping verts and treats them so they ALWAYS overlap. // This means your mesh should never have overlapping verts that are NOT along a UV seam. // Setup the builtin array for fast data processing. var FastMesh : Vector3[] = Base_Mesh.ToBuiltin(Vector3); // We're going to go though every vert, and see if any other verts are for ( var vert=0 ; vert<FastMesh.length ; vert++ ) { Seam_NextSameVert.Add( -1 ); for ( var findvert=vert+1 ; findvert<FastMesh.length ; findvert++ ) { if (FastMesh[vert] == FastMesh[findvert]) { Seam_NextSameVert[vert] = findvert; Seam_Verts.Add(vert); findvert = FastMesh.length; } } } Report("Found " + Seam_Verts.length + " seam verts...",1); } function Load_Diff_Maps() { Report("Loading Diff Maps", 1); // First, get the UV data from the mesh... var Base_uvs : Vector2[]; if (MetaMorph_Settings.MM_UV_Layer_One == true) { Base_uvs = mesh.uv; } else { Base_uvs = mesh.uv2; } // let's cycle through all the diff maps in Diff_Maps. var Diff_Map_Loop_Max : int = Diff_Maps.length; for ( var Diff_Map_Loop=0 ; Diff_Map_Loop<Diff_Map_Loop_Max ; Diff_Map_Loop++ ) { // Temporary variables for building var Load_Diff_Map = new Array (); var Load_Diff_Map_L = new Array (); if (Diff_Maps[Diff_Map_Loop].DM_Scale == Vector3(0,0,0)) { Diff_Maps[Diff_Map_Loop].DM_Scale = Vector3(1,1,1); } // Set the name if it was not alreay set... if (Diff_Maps[Diff_Map_Loop].Name == "") { Diff_Maps[Diff_Map_Loop].Name = Diff_Maps[Diff_Map_Loop].DM_Image.name; } // Grab the Diff Map data... var A_Diff_Map : Diff_Map_class = Diff_Maps[Diff_Map_Loop]; // And get the parts of it we need for processing... var Diff_Map_Image : Texture2D = A_Diff_Map.DM_Image; var Diff_Map_Scale : Vector3 = A_Diff_Map.DM_Scale; // We now read the mesh, uv, and Diff Map to get the shape data. and store it. for (var vert=0;vert<Base_uvs.length;vert++) { var UV_x : int = Base_uvs[vert].x * Diff_Map_Image.width; var UV_y : int = Base_uvs[vert].y * Diff_Map_Image.height; // These var test_x : int = (Diff_Map_Image.GetPixel(UV_x, UV_y).r - 0.5) * 255; var test_y : int = (Diff_Map_Image.GetPixel(UV_x, UV_y).g - 0.5) * 255; var test_z : int = (Diff_Map_Image.GetPixel(UV_x, UV_y).b - 0.5) * 255; if ( !(test_x == 0 && test_y == 0 && test_z == 0) ) { // Okay, now we grab the color data for the pixel under the UV point for this vert. We then convert it to a number from -1.0 to 1.0, and multiply it by Diff_Map_Scale. var UVC_r : float = ((Diff_Map_Image.GetPixel(UV_x, UV_y).r / 0.5) - 1 ) * -1 * Diff_Map_Scale.x; // Why -1? Because the relation to blender is reversed for some reason... var UVC_g : float = ((Diff_Map_Image.GetPixel(UV_x, UV_y).g / 0.5) - 1 ) * Diff_Map_Scale.y; var UVC_b : float = ((Diff_Map_Image.GetPixel(UV_x, UV_y).b / 0.5) - 1 ) * Diff_Map_Scale.z; var vert_xyz_shift = Vector3 ( UVC_r, UVC_g, UVC_b); Load_Diff_Map.Add( vert_xyz_shift ); Load_Diff_Map_L.Add( vert); } } Report("Object "+name+": Diff Map '"+Diff_Map_Image.name+"' changes " + Load_Diff_Map_L.length + " out of " + Base_Mesh.length + " verts...", 2); // This part stores not only the mesh modifications for this shape, but also the indexes of the array that are being changes in the mesh. // This data allows us to cycle through only the mesh points that will be changed, instead of running though all of points of the mesh. // Massive speed increase: You only pay for the points you morph. Morph_Shapes_Data.Add (Load_Diff_Map); // We're storing an array into an array here. Morph_Shapes_Links.Add (Load_Diff_Map_L); // We're storing an array into an array here. } } function Load_Animation_Recordings() { Report("Loading Animation Recordings", 1); var fileloop : int; for ( fileloop = 0 ; fileloop < Animation_Recordings.length ; fileloop++) { var My_Animation_Recording : Animation_Recording_class = Animation_Recordings[fileloop]; var Animation_Array : Array = ReadAnimationFile(My_Animation_Recording.AR_Text); // Okay, we have the data for this animation kit... // Let's store it! Morph_Animation_Data.Add(Animation_Array); // Now it's stored in the format: Morph_Sequence_Data[animationset][frame1-xxx][name/amountmorph] } } function ReadAnimationFile(datafile : TextAsset) : Array { // This read blender 3d ShapeKeys that have been exported with the diffmap. // It's a good idea for each animation to contained in it's own file under it's own name. Report("Loading Animation Recording: " + datafile.name, 2); var Animation_Array = new Array(); //var Total_String = datafile.text; var Total_Array = new Array(); Total_Array = datafile.text.Split("\n"[0]); var line : int; for ( line = 0 ; line<Total_Array.length ; line=line+1 ) { var Line_String : String = Total_Array[line]; // parse out all the crap. var boo = Regex.Match(Line_String,"(\\[|\\])"); if (boo.Success) { Line_String = Regex.Replace(Line_String,"(\n|\r|\f)",""); Line_String = Regex.Replace(Line_String,"(\\[|\\])",""); Line_String = Regex.Replace(Line_String,"\\s*(,)\\s*","|"); Line_String = Regex.Replace(Line_String,"'",""); var Line_Array = new Array(); Line_Array = Line_String.Split("|"[0]); var item : int; // We really want the floating point numbers to be stored as floating points, and not strings... if (Animation_Array.length == 0) { Animation_Array.Add(Line_Array); var Line_Array2 = new Array(); for ( item = 0 ; item<Animation_Array[0].length ; item=item+1 ) { var Found : int = FindName( Diff_Maps, [Animation_Array[0][item]] ); if ( Found != -1) { Line_Array2.Add(Found); // Writing line two, the diff map indexes. Faster than name lookups per frame. } else { Report("ERROR: Morph not found" + Animation_Array[0][item], 0); Debug.Break(); } } Animation_Array.Add(Line_Array2); } else { for ( item = 0 ; item<Line_Array.length ; item=item+1 ) { Line_Array[item] = parseFloat(Line_Array[item]); var Found2 : int = FindName( Diff_Maps, [Animation_Array[0][item]] ); if ( Found2 != -1) { if (Animation_Array.length == 2 && Diff_Maps[Found2].DM_Multiplier == 0) { Diff_Maps[Found2].DM_Multiplier = parseFloat(Line_Array[item]); } } } Animation_Array.Add(Line_Array); } } } return Animation_Array; } // ----------------------------------------------------------------------- // Update Mesh Functions (These are called by Update) // ----------------------------------------------------------------------- function Apply_Morphs() { // This is where the magic happens. All of the morphs and animations ar added together, and then applied to the mesh. var Morph_Array = new Array (); Morph_Array = Group_Morphs(Morph_Array); Morph_Array = Group_Animations(Morph_Array); // And if the mesh has changed since the last frame, we apply it. if ( MeshChanged > 0 && Is_Visible == true ) { // We have mesh changes! var Work_Mesh : Vector3[] = Mod_Mesh.ToBuiltin(Vector3); for (var Morph_Item_loop = 0 ; Morph_Item_loop < Morph_Array.length ; Morph_Item_loop++ ) { // okay, we are now going to apply each animation at the proper precentage to the model. var Shape_Morph : Vector3[] = Morph_Array[Morph_Item_loop][0].ToBuiltin(Vector3); var Shape_Link : int[] = Morph_Array[Morph_Item_loop][1].ToBuiltin(int); var Shape_Power : float = Morph_Array[Morph_Item_loop][2]; for (var Morph_Verts=0;Morph_Verts<Shape_Link.length;Morph_Verts++) { // In this case, we're only looping the vertices that MOVE. All the rest are ignored, and this runs faster that way. // You only pay for the parts you morph. Work_Mesh[Shape_Link[Morph_Verts]] += Shape_Morph[Morph_Verts] * Shape_Power; } } // but you know what? We have verts that need to be stiched back together along the UV seams. // Actually, we just re-overlap any overlapping vert positions from the initial mesh shape, but that's good enough! var SeamVerts_BIA : int[] = Seam_Verts.ToBuiltin(int); var NextSameVert_BIA : int[] = Seam_NextSameVert.ToBuiltin(int); for ( var h=0 ; h<SeamVerts_BIA.length ; h++ ) { Work_Mesh[NextSameVert_BIA[SeamVerts_BIA[h]]] = Work_Mesh[SeamVerts_BIA[h]]; } mesh.vertices = Work_Mesh; // And recald the normals if needed. // Trust me, you want to leave this off. It rarely works well. // Try it and see! RecalcNorms(); // And the mesh is ready for the next frame. MeshChanged = MeshChanged - 1; if (MeshChanged < 0) { MeshChanged = 0; } } } // We group all the arrays into function Group_Morphs(Morph_Array : Array) : Array { // Here is where we make the list of morphs to apply to the mesh from the Morphs currently active. for(var CAM_Loop: int ; CAM_Loop < Currently_Active_Morphs.length ; CAM_Loop++) { var Morph_Number : int = Currently_Active_Morphs[CAM_Loop].Link; // How much should we morph it? var Time_Spot :float = Mathf.InverseLerp( Currently_Active_Morphs[CAM_Loop].CAM_Start_Time, Currently_Active_Morphs[CAM_Loop].CAM_Start_Time + Currently_Active_Morphs[CAM_Loop].CAM_TimeFrame, Time.realtimeSinceStartup ); var Morph_Shapes_Power = Mathf.Lerp( Currently_Active_Morphs[CAM_Loop].CAM_Start_Level, Currently_Active_Morphs[CAM_Loop].CAM_End_Level, Time_Spot ); if ( Mathf.Approximately( Morph_Shapes_Power, 0.0 ) ) { if (Currently_Active_Morphs[CAM_Loop].CAM_End == true) { Currently_Active_Morphs.RemoveAt(CAM_Loop); // Watch this! Make sure the for loop is actually looking at the length attribute or you could wander straight into null territory. CAM_Loop--; // Oh, and back it up one, we just deleted an entry, so we need to look at this slot number again. MeshChanged = 2; } } else { Morph_Shapes_Power = Morph_Shapes_Power * Diff_Maps[Morph_Number].DM_Multiplier; // group up the data for the morph into an morph item array. var Morph_Item = new Array (); Morph_Item.Add(Morph_Shapes_Data[Morph_Number]); // section 0 Morph_Item.Add(Morph_Shapes_Links[Morph_Number]); // section 1 Morph_Item.Add(Morph_Shapes_Power); // section 2 Morph_Array.Add(Morph_Item); MeshChanged = 2; } } return Morph_Array; } function Group_Animations(Morph_Array : Array) : Array { // Here is where we make the list of morphs to apply to the mesh from the Animations currently active. for(var CAA_Loop: int = 0; CAA_Loop < Currently_Active_Animations.length ; CAA_Loop++) { var removeanimation : boolean = false; var Animation_Recording_class_Index : int = Currently_Active_Animations[CAA_Loop].Link; var Frame : int = Time2Frame( Time.realtimeSinceStartup - Currently_Active_Animations[CAA_Loop].CAA_Start_Time, Currently_Active_Animations[CAA_Loop].CAA_Speed ); var End_Frame = Morph_Animation_Data[Animation_Recording_class_Index].length - 4; // Remember Animation styles? This is where we process them. if (Frame > End_Frame ) { var Style = Currently_Active_Animations[CAA_Loop].CAA_Style; if (Style == Animation_Style_End) { Currently_Active_Animations[CAA_Loop].CAA_End_Time = Time.realtimeSinceStartup - 0.002; Currently_Active_Animations[CAA_Loop].CAA_Fade_Time = Time.realtimeSinceStartup - 0.001; Frame = End_Frame; } else if (Style == Animation_Style_Freeze) { Frame = End_Frame; } else if (Style == Animation_Style_Loop) { Frame = 0; Currently_Active_Animations[CAA_Loop].CAA_Start_Time = Time.realtimeSinceStartup; } else if (Style == Animation_Style_PingPong) { if (Frame > End_Frame * 2) { Frame = 0; Currently_Active_Animations[CAA_Loop].CAA_Start_Time = Time.realtimeSinceStartup; } Frame = Mathf.Round(Mathf.PingPong (Frame, End_Frame) ); } } // And the code for stopping an animatio and fading out over time while doing so. var Fade_out = 1.0; if (Currently_Active_Animations[CAA_Loop].CAA_End_Time > 0) { Fade_out = Mathf.InverseLerp (Currently_Active_Animations[CAA_Loop].CAA_Fade_Time, Currently_Active_Animations[CAA_Loop].CAA_End_Time, Time.realtimeSinceStartup); if(Time.realtimeSinceStartup>Currently_Active_Animations[CAA_Loop].CAA_Fade_Time) { removeanimation = true; } } // Grabbing the data for adding to the morph list... var Morph_Animation_Data_Indexes : Array = Morph_Animation_Data[Animation_Recording_class_Index][1]; // Indexes of the Diffmaps we're using. var Morph_Animation_Data_Powers : Array = Morph_Animation_Data[Animation_Recording_class_Index][2]; // frames start on line 3 (from line 0)... var Morph_Animation_Data_Levels : Array = Morph_Animation_Data[Animation_Recording_class_Index][Frame+3]; // frames start on line 3 (from line 0)... for(var MAD_Loop: int ; MAD_Loop < Morph_Animation_Data_Indexes.length ; MAD_Loop++) { var Morph_Power : float = Morph_Animation_Data_Powers[MAD_Loop] * Morph_Animation_Data_Levels[MAD_Loop] * Fade_out; if ( !Mathf.Approximately( Morph_Power, 0.0 ) ) { var Morph_Item = new Array (); Morph_Item.Add(Morph_Shapes_Data[Morph_Animation_Data_Indexes[MAD_Loop]]); // section 0 Morph_Item.Add(Morph_Shapes_Links[Morph_Animation_Data_Indexes[MAD_Loop]]); // section 1 Morph_Item.Add(Morph_Power); // section 2 Morph_Array.Add(Morph_Item); MeshChanged = 2; } } // Oh, if an animation is done, we take care of it here... if(removeanimation == true) { Currently_Active_Animations.RemoveAt(CAA_Loop); // Watch this! Make sure the for loop is actually looking at the length attribute or you could wander straight into null territory. CAA_Loop--; MeshChanged = 2; Frame = 0; } } // Well, were done with the array. return it. return Morph_Array; } // ----------------------------------------------------------------------- // Morph Global Datastores and Functions that can be called from outside // ----------------------------------------------------------------------- // Variables... // All Morphs that are currently running. private var Currently_Active_Morphs = new Array (); // array [Animation_Recording#] [line] [single-entry] class Currently_Active_Morphs_class { var Name : String; // relates directly to Diff_Map_class.AR_Name var Link : int; // link to array Diff_Map_class[] (speed up loops) var CAM_Start_Time : float; var CAM_TimeFrame : float; var CAM_Start_Level : float; // The time of the animation being started, using Time.realtimeSinceStartup var CAM_End_Level : float; var CAM_End : boolean; } // Functions... function mm_Morph_Add( Morph_Name : String, Start_Level : float, End_Level : float, TimeFrame : float ) { // Morph_Name: this is the name of the morph, as designated in Diff_Maps.Name // Start_Level: sets the starting morph level. normally, you would use zero to start // End_Level: The morph level you want to end up at. // TimeFrame: How long to take to fade from start to end. // Keep in mind, even when the morph has finished timeframe, it's still morphing the mesh every frame until stopped by mm_Morph_Remove. // If you want to have a morph be added 'permanenty' to the mesh, use mm_SetShape_Set. // These work with mm_Animate_Play, allowing you to use morphs while animations are running. // This is good for things like randomized blinking, for example. // morph effects are additive, meaning that two morphs with overlapping effects do not average, they add to each other. var Found_morph : int = FindName( Diff_Maps, [Morph_Name] ); if ( Found_morph != -1) { if (TimeFrame < 0.001) { // No such thing as zero time. zero does not give useful data. TimeFrame = 0.001; } var This_Morph = new Currently_Active_Morphs_class(); This_Morph.Name = Morph_Name; This_Morph.Link = Found_morph; This_Morph.CAM_Start_Time = Time.realtimeSinceStartup; This_Morph.CAM_TimeFrame = TimeFrame; This_Morph.CAM_Start_Level = Start_Level; This_Morph.CAM_End_Level = End_Level; This_Morph.CAM_End = false; // Find the morph. var Found : int = FindName( Currently_Active_Morphs, [Morph_Name] ); if ( Found != -1) { // Found it. Replace it! Currently_Active_Morphs[Found] = This_Morph; } else { //The morph does not exist. Make it! Currently_Active_Morphs.Add(This_Morph); } } else { Report("ERROR: Morph not found" + Morph_Name, 0); } } function mm_Morph_Remove(Morph_Name : String, TimeFrame : float) { // Morph_Name: this is the name of the morph to stop effecting the mesh. // TimeFrame: is how long it takes for the morph to fade out. var Found : int = FindName( Currently_Active_Morphs, [Morph_Name] ); if ( Found != -1) { // Found it. Set it to fade and die. if (TimeFrame < 0.001) { // No such thing as zero time. zero does not give useful data. TimeFrame = 0.001; } var Time_Spot :float = Mathf.InverseLerp( Currently_Active_Morphs[Found].CAM_Start_Time, Currently_Active_Morphs[Found].CAM_Start_Time + Currently_Active_Morphs[Found].CAM_TimeFrame, Time.realtimeSinceStartup ); var New_Start_Level : float = (Mathf.Lerp( Currently_Active_Morphs[Found].CAM_Start_Level, Currently_Active_Morphs[Found].CAM_End_Level, Time_Spot )); // This line is checking data that later lines change. DO THIS FIRST! Currently_Active_Morphs[Found].CAM_Start_Level = New_Start_Level; // what is the current morph level at this moment? No need for error checking, since we know it exists... Currently_Active_Morphs[Found].CAM_Start_Time = Time.realtimeSinceStartup; Currently_Active_Morphs[Found].CAM_TimeFrame = TimeFrame; Currently_Active_Morphs[Found].CAM_End_Level = 0.0; Currently_Active_Morphs[Found].CAM_End = true; } } function mm_Morph_Level( Morph_Name : String ) : Array // [float] { // Morph_Name: this is the name of the morph you are questing information on. // If the returned array is null, then the morph is not active. Otherwise, array[0] is a float of how much the morph is effecting the mesh. var Current_Morph_Level = new Array (); var Found : int = FindName( Currently_Active_Morphs, [Morph_Name] ); if ( Found != -1) { var Time_Spot :float = Mathf.InverseLerp( Currently_Active_Morphs[Found].CAM_Start_Time, Currently_Active_Morphs[Found].CAM_Start_Time + Currently_Active_Morphs[Found].CAM_TimeFrame, Time.realtimeSinceStartup ); Current_Morph_Level.Add(Mathf.Lerp( Currently_Active_Morphs[Found].CAM_Start_Level, Currently_Active_Morphs[Found].CAM_End_Level, Time_Spot )); return Current_Morph_Level; } else { return null; } } function mm_Morph_Playing( ) : Array // strings { // Morph_Name: this is the name of the morph you are questing information on. // returns an array of all the morphs (not animations or Setshapes) effecting the mesh. var listing = new Array (); var listrange : int = Currently_Active_Morphs.length; for (var listitem = 0 ; listitem < listrange ; listitem++) { listing.Add(Currently_Active_Morphs[listitem].Name); } return listing; } // ----------------------------------------------------------------------- // Animation Global Datastores and Functions that can be called from outside // ----------------------------------------------------------------------- // Variables... // All animations that are currently running... private var Currently_Active_Animations = new Array (); // array [Animation_Recording#] [line] [single-entry] class Currently_Active_Animations_class { var Name : String; // relates directly to Animation_Recording_class.AR_Name var Link : int; // link to array Animation_Recording_class[] (speed up loops) var CAA_Start_Time : float; // The time of the animation being started, using Time.realtimeSinceStartup var CAA_End_Time : float; var CAA_Fade_Time : float; var CAA_Speed : float; var CAA_Effect_Level : float; var CAA_Style : int; } // Functions... function mm_Animate_Play( Morph_Animation_Name : String, Speed_Multiple : float, Style : int ) { // Morph_Animation_Name: The name of the animation you are starting from Animation_Recordings.Name // Speed_Multiple: This allows you to speed up and slow down an animation. 1.0 is normal. Higher is faster. Lower is slower. // Style: Animation_Style_End = 0, Animation_Style_Freeze = 1, Animation_Style_Loop 2, Animation_Style_PingPong = 3 // These are NOT morphs, though they use Morph data. They are datastreams of morph levels stored by frame. // They are use to play back complex animation from Blender 3d made with shapekeys. // Starts playing an animation. var Found_animation : int = FindName( Animation_Recordings, [Morph_Animation_Name] ); if ( Found_animation != -1) { var This_Animation = new Currently_Active_Animations_class(); This_Animation.Name = Morph_Animation_Name; This_Animation.Link = Found_animation; This_Animation.CAA_Start_Time = Time.realtimeSinceStartup; This_Animation.CAA_End_Time = -1; This_Animation.CAA_Fade_Time = -1; This_Animation.CAA_Speed = Speed_Multiple; This_Animation.CAA_Style = Style; // Find the morph. var Found : int = FindName( Currently_Active_Animations, [Morph_Animation_Name] ); if ( Found != -1) { // Found it. Replace it! Currently_Active_Animations[Found] = This_Animation; } else { //The morph does not exist. Make it! Currently_Active_Animations.Add(This_Animation); } } else { Report("ERROR: Morph Animation not found" + Morph_Animation_Name, 0); } } function mm_Animate_Stop( Morph_Animation_Name : String, Ease_Out : float ) { // Morph_Animation_Name: Name of the animation to stop. // Ease_Out: How long to take easing out of the animation running. // stops an animation by fading it out. To fade it out instantly, use and ease_out of zero. var Found : int = FindName( Currently_Active_Animations, [Morph_Animation_Name] ); if ( Found != -1) { if (Ease_Out < 0.001) { // No such thing as zero time. zero does not give useful data. Ease_Out = 0.001; } // Found it. Set it to fade and die. Currently_Active_Animations[Found].CAA_End_Time = Time.realtimeSinceStartup; // start fading from now... Currently_Active_Animations[Found].CAA_Fade_Time = Time.realtimeSinceStartup + Ease_Out; // when we reach this time, remove the morph. } } function mm_Animate_Frame( Morph_Animation_Name : String ) : Array // [int] { // Morph_Animation_Name: Name of the animation to get the current frame from. // returns the current frame of the animation. // returns the current frame being played of the named animation. var Current_Animation_Frame = new Array (); var Found : int = FindName( Currently_Active_Animations, [Morph_Animation_Name] ); if ( Found != -1) { var frame : int = Time2Frame( Time.realtimeSinceStartup - Currently_Active_Animations[Found].CAA_Start_Time , Currently_Active_Animations[Found].CAA_Speed ); return [frame]; } else { return null; } } function mm_Animate_Playing( ) : Array // strings { // returns a list of the names of currently playing animations. var listing = new Array (); var listrange : int = Currently_Active_Animations.length; for (var listitem = 0 ; listitem < listrange ; listitem++) { listing.Add(Currently_Active_Animations[listitem].Name); } return listing; } // ----------------------------------------------------------------------- // SetShape Functions (These can be called from outside) // ----------------------------------------------------------------------- function mm_SetShape_Set( Morph_Name : String, Morph_Level : float ) { // Morph_Name: Name of the morph to apply. // Morph_Level: How much to apply it. 1.0 is fully. // With this, you can set a morph shape into the default mesh. // This means no FPS cost for it to be visible, but a large cost to set it. // Do NOT call this per frame. Use the mm_Morph set of functions to animate getting to a shape, and then kill the morph while setting the shape. // It stacks, so each new shape added is added to all the previous ones. var Found : int = FindName( Diff_Maps, [Morph_Name] ); if ( Found != -1) { // group up the data for the morph into an morph item array. var Morph_Item = new Array (); Morph_Item.Add(Morph_Shapes_Data[Found]); // section 0 Morph_Item.Add(Morph_Shapes_Links[Found]); // section 1 Morph_Item.Add(Morph_Level); // section 2 // And drop it into slot zero... var Morph_Array = new Array (); Morph_Array.Add(Morph_Item); // slot 0 mesh.vertices = Morph(Mod_Mesh, Morph_Array); RecalcNorms(); } } function mm_SetShape_Reset( ) { // This function resets the modded mesh back to the default. // Again, this is for SetShape, and does not effect morphs or animations. Mod_Mesh = Base_Mesh; mesh.vertices = Base_Mesh.ToBuiltin(Vector3); RecalcNorms(); } // ----------------------------------------------------------------------- // Tool Values // ----------------------------------------------------------------------- // Style variables to easier set Animation Style options. private var Animation_Style_End : int = 0; private var Animation_Style_Freeze : int = 1; private var Animation_Style_Loop : int = 2; private var Animation_Style_PingPong : int = 3; // ----------------------------------------------------------------------- // Tool Functions // ----------------------------------------------------------------------- // This function does not actually change the mesh, it just edits the arrays and returns what can be USED as a new mesh. // We don't use this for live fps animation, since is slows down rendering heavily. function Morph(Starting_Mesh : Array, Morph_Array : Array) : Vector3[] { // The incoming variable is a special array, containing a lot of data. // Morph_Array [grouping number] [0] = morph array // [1] = link array // [2] = power level applied. var Work_Mesh : Vector3[] = Starting_Mesh.ToBuiltin(Vector3); for (var Morph_Item = 0 ;Morph_Item < Morph_Array.length ; Morph_Item++ ) { // okay, we are now going to apply each animation at the proper precentage to the model. var Shape_Morph : Vector3[] = Morph_Array[Morph_Item][0].ToBuiltin(Vector3); var Shape_Link : int[] = Morph_Array[Morph_Item][1].ToBuiltin(int); var Shape_Power : float = Morph_Array[Morph_Item][2]; for (var Morph_Verts=0;Morph_Verts<Shape_Link.length;Morph_Verts++) { // In this case, we're only looping the vertices that MOVE. All the rest are ignored, and this runs faster that way. // You only pay for the parts you morph. Work_Mesh[Shape_Link[Morph_Verts]] += Shape_Morph[Morph_Verts] * Shape_Power; } } // And here we have the final builtin array with the mesh shape we want! return Work_Mesh; } // If true, then recalc the norms. // Avoid this unless you REALLY need it for reflections and shines. function RecalcNorms() { // The below recalulates the normal faces, but is not needed for most morphs. if (MetaMorph_Settings.MM_Recalculate_Normals == true) { mesh.RecalculateNormals(); } } // simple function to translate seconds of animation to frames assuming 30 fps function Time2Frame( timefromzero : float, speedmultiplier : float ) : int { return Mathf.Round( (timefromzero * speedmultiplier) * 30.0 ); // All Unity animations need to be at 30 fps. bones, morphs, everything. } // Error checking function. // Avoid it in fps loops, even when the level of the debug is low. Still takes time to check. function Report(message : String, level : int) { if (level <= MetaMorph_Settings.MM_Verbose) { Debug.Log (message); } } // Simple way to find the name in arrays. // For the love of god, DON'T use this in fps functions. You'll slow to a crawl. // If you need this data, presave it in an array or something. function FindName( searchabledata : Array, requesteddata : Array ) : int { // This does need the searchabledata array to be a class with .Name attached. var found : int = -1; var searchrange : int = searchabledata.length; for (var search = 0 ; search < searchrange ; search++) { if (requesteddata[0] == searchabledata[search].Name) { found = search; search = searchrange; } } return found; } <file_sep>/Assets/Standard Assets/Character Controllers/scripts/LimbsGoesAfterCamera.js var cam : GameObject; var arm : GameObject; private var angle; private var r = 20; private var angleX; private var z; private var y; private var positionZ; positionZ = cam.transform.localPosition.z; private var positionY; positionY = cam.transform.localPosition.y; function LateUpdate () { if (LavaTrigger.lavaDeath==false) { angle = cam.transform.localEulerAngles.x; if (angle < 270) angle += 360; if (angle >270*3/4) angle = angle *3/4; arm.transform.eulerAngles.x -= angle+160; } } <file_sep>/Assets/Standard Assets/Character Controllers/Sources/Scripts/CameraShake.js private static var angle; private static var x; private static var y; private static var moveDirection; static function CameraShake (r) { if (r>0) { angle = Random.Range(0.0,360.0)* Mathf.PI/180; x = Mathf.Cos(angle)*r; y = Mathf.Sin(angle)*r; return Vector3(x,y,0); } else { return Vector3(0,0,0); } }<file_sep>/Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.js enum RotationAxes {MouseX, MouseY, MouseXandY}; var axes : RotationAxes; private var MouseX = RotationAxes.MouseX; private var MouseY = RotationAxes.MouseY; private var MouseXandY = RotationAxes.MouseXandY; private var angleX; private var y; private var x; private var positionY; private var positionX; private var rotationX; var sensitivityX : float = 15F; var sensitivityY : float = 15F; var minimumX : float = -360F; var maximumX : float = 360F; var minimumY : float= -60F; var maximumY : float = 60F; var rotationY : float = 0F; var spineLength : float = 0F; function Update () { if (SpecjalBehaviour.movement == true) { if (axes == MouseXandY) { var rotationX : float = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = Vector3(-rotationY, rotationX, 0); } else if (axes == MouseX) { transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0); } else { if (transform.localEulerAngles.y!=90) transform.localEulerAngles.y = 90; // if (transform.localEulerAngles.z!=90) // transform.localEulerAngles.z = 90; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0); angleX = rotationX - transform.eulerAngles.x * Mathf.PI/180; y = -spineLength*Mathf.Cos(angleX); x = spineLength*Mathf.Sin(angleX); transform.localPosition.x = positionX + x; transform.localPosition.y = positionY + y; } } // transform.localEulerAngles.z+=90; } function Start () { positionY = transform.localPosition.y; positionX = transform.localPosition.x; rotationX = transform.eulerAngles.x * Mathf.PI/180; // Make the rigid body not change rotation if (rigidbody) rigidbody.freezeRotation = true; } <file_sep>/Assets/MetaMorph/Blender Plugin/io_export_diffmap.py bl_info = { "name": "Export MetaMorph Diff Map Animation", "author": "<NAME> / <NAME>", "version": (1, 1, 1), "blender": (2, 5, 7), "api": 36079, "location": "Mesh-data section in property-window", "description": "Creates Diff Maps for each Shapekey", "warning": "", "url": "http://www.rezzable.com", "category": "Import-Export"} import bpy from mathutils import Vector, Color import time from bpy.props import * from io_utils import ImportHelper import os __version__ = '1.1.1' # ------------------------------------ core functions ------------------------------------ # Global variables original_materials = [] mat = None original_face_mat_indices = [] ShapeKeyName = [] MaxDiffStore = [] # Find faces that use the given vertex # Returns: tuple with face_index and vertex_index def vertex_find_connections( mesh, vert_index): list = [] for n in mesh.faces: for i in range( len(n.vertices) ): if n.vertices[i] == vert_index: list.append( (n.index, i ) ) return list # Remember and set up things # Deselect all verts # Remember materials # Create temp vertex color layer def pre(ob): print("Prep work started...") mesh = ob.data uvtex = mesh.uv_textures.active vcol = mesh.vertex_colors.active global original_materials, mat global original_face_mat_indices # Deselect all vertices (to avoid odd artefacts, some bug?) for n in mesh.vertices: n.select = False # Store face material indices original_face_mat_indices = [] for n in mesh.faces: original_face_mat_indices.append( n.material_index ) n.material_index = 0 # Remember and remove materials original_materials = [] for n in mesh.materials: print("Saving Material: " + n.name) original_materials.append(n) for n in mesh.materials: mesh.materials.pop(index=0) # Create new temp material for baking mat = bpy.data.materials.new(name="DiffMap_Bake") mat.use_vertex_color_paint = True mat.diffuse_color = Color([1,1,1]) mat.diffuse_intensity = 1.0 mat.use_shadeless = True mesh.materials.append(mat) # Add new vertex color layer for baking if len(mesh.vertex_colors) < 8-1: vcol = mesh.vertex_colors.new(name="DiffMap_Bake") mesh.vertex_colors.active = vcol vcol.active_render = True else: print("Amount limit of vertex color layers exceeded") # Restore things # Remove temp materials and restore originals # Remove temp vertex color layer def post(ob): print("Post work started...") global original_materials, mat global original_face_mat_indices mesh = ob.data uvtex = mesh.uv_textures.active vcol = mesh.vertex_colors.active original_face_images = [] # Remove temp material mesh.materials.pop(index=0) mat.user_clear() bpy.data.materials.remove( mat ) # Restore original materials for n in original_materials: mesh.materials.append(n) # Restore face material indices for n in range(len(original_face_mat_indices)-1): mesh.faces[n].material_index = original_face_mat_indices[n] # Remove temp vertex color layer bpy.ops.mesh.vertex_color_remove() # Refresh UI bpy.context.scene.frame_current = bpy.context.scene.frame_current # Free some memory original_materials = [] original_face_mat_indices = [] def generate_diffmap_from_shape(ob, filepath, name, shape, shapeson, width=128, height=128, margin=10 ): global ShapeKeyName global MaxDiffStore mesh = ob.data uvtex = mesh.uv_textures.active vcol = mesh.vertex_colors.active # Find biggest distance offset in shape maxdiff = 0.0 for n in mesh.vertices: diff = n.co.copy() - shape.data[n.index].co.copy() for i in diff: if abs(i) > maxdiff: maxdiff = abs(i) if maxdiff > 0: ShapeKeyName = ShapeKeyName + [shape.name] MaxDiffStore = MaxDiffStore + [maxdiff] if shapeson == True: # Generate vertex color from shape key offset for n in mesh.vertices: faces = vertex_find_connections( mesh, n.index) color = Color( [0,0,0] ) diff = n.co.copy() - shape.data[n.index].co.copy() if maxdiff > 0: color[0] = 1.0 - (((diff[0] / maxdiff) + 1.0) *0.5) color[1] = 1.0 - (((diff[1] / maxdiff) + 1.0) *0.5) color[2] = 1.0 - (((diff[2] / maxdiff) + 1.0) *0.5) # Apply vertex color to all connected face corners (vertcolors have same structure as uvs) for i in faces: if i[1] == 0: vcol.data[i[0]].color1 = color if i[1] == 1: vcol.data[i[0]].color2 = color if i[1] == 2: vcol.data[i[0]].color3 = color if i[1] == 3: vcol.data[i[0]].color4 = color # Create new image to bake to image = bpy.data.images.new(name="DiffMap_Bake", width=width, height=height) image.generated_width = width image.generated_height = height # Construct complete filepath if bpy.app.build_platform.find("Windows") != -1: path = filepath + '\\' + name + '-' + shape.name + '.tga' elif bpy.app.build_platform.find("Linux") != -1: path = filepath + '/' + name + '-' + shape.name + '.tga' else: path = filepath + '/' + name + '-' + shape.name + '.tga' image.filepath = path # assign image to mesh (all uv faces) original_image = uvtex.data[0].image # Simply taking the image from the first face original_face_images = [] for n in uvtex.data: if n.image == None: original_face_images.append( None ) else: original_face_images.append( n.image.name ) n.image = image # Bake render = bpy.context.scene.render tempcmv = render.use_color_management; render.bake_type = 'TEXTURE' render.bake_margin = margin render.use_bake_clear = True render.use_bake_selected_to_active = False render.bake_quad_split = 'AUTO' render.use_color_management = False bpy.ops.object.bake_image() image.save() # re-assign images to mesh faces for n in range( len(original_face_images) ): tmp = original_face_images[n] if original_face_images[n] != None: tmp = bpy.data.images[ original_face_images[n] ] else: tmp = None uvtex.data[n].image = tmp # Remove image from memory image.user_clear() bpy.data.images.remove(image) render.use_color_management = tempcmv # Tell user what was exported print( " exported %s" % path ) # General error checking def found_error(self, context): ob = context.active_object scene = context.scene filepath = self.filepath if ob.type != 'MESH': self.report({'ERROR'}, "Object is not a mesh") print("Object is not a mesh") return True if ob.data.shape_keys == None: self.report({'ERROR'}, "Mesh has no shape keys") print("Mesh has no shape keys") return True if len(ob.data.uv_textures) <= 0: self.report({'ERROR'}, "Mesh has no UVs") print("Mesh has no UVs") return True if not os.path.exists( filepath ): self.report({'ERROR'}, "Invalid filepath: %s" % filepath) print("Invalid filepath: %s" % filepath) return True if len( ob.data.faces ) <= 0: self.report({'ERROR'}, "Mesh contains no faces") print("Mesh contains no faces") return True return False def main(self, context): global ShapeKeyName global MaxDiffStore ob = context.active_object scene = context.scene print("-----------------------------------------------------") print("Starting Diff-Map export for object %s ..." % ob.name ) # Error checking if found_error(self, context): print(found_error(self, context)) return pre(ob) shape = ob.active_shape_key filepath = self.filepath name = self.name width = self.width height = self.height margin = self.margin animationson = self.animationson shapeson = self.shapeson ShapeKeyName = [] MaxDiffStore = [] #for n in ob.data.shape_keys.key_blocks: for n in ob.data.shape_keys.key_blocks: if n.name != 'Basis': # Skip the 'Basis' shape generate_diffmap_from_shape(ob, filepath, name, n, shapeson, width, height, margin ) post(ob) if animationson == True: Write_Animation(filepath, name, self) print(" Finished.") print("-----------------------------------------------------") def Write_Animation(Afilepath, Afilename, self): global ShapeKeyName global MaxDiffStore ShapeKeyName2 = [] ShapeKeyName3 = [] MaxDiffStore2 = [] print("-------------------------------") print("Starting writing Animation List") #print("-------------------------------") Afileset = Afilepath + '/' + Afilename + '-DiffMapAnimation.TXT' # Okay, let's get the base data. MyObject = bpy.context.active_object MyShapekeys = MyObject.data.shape_keys.key_blocks AnimationStart = bpy.context.scene.frame_start AnimationEnd = bpy.context.scene.frame_end name = self.name framestring = str(AnimationStart) + 'to' + str(AnimationEnd) Afileset = Afilepath + '/' + Afilename + '-' + framestring + '-DiffMapAnimation.TXT' # open the file... Animation_Output = open(Afileset,"w") for AnimationShapes in range(0, len(ShapeKeyName)): hasvalue = False for AnimationFrame in range(AnimationStart, AnimationEnd + 1): bpy.context.scene.frame_set(AnimationFrame) if MyShapekeys[ShapeKeyName[AnimationShapes]].value > 0.0005: hasvalue = True if hasvalue == True: ShapeKeyName2 = ShapeKeyName2 + [ShapeKeyName[AnimationShapes]] ShapeKeyName3 = ShapeKeyName3 + [name+"-"+ShapeKeyName[AnimationShapes]] MaxDiffStore2 = MaxDiffStore2 + [MaxDiffStore[AnimationShapes]] Animation_Output.write(str(list(ShapeKeyName3)) + "\n") Animation_Output.write(str(list(MaxDiffStore2)) + "\n") # And loop for every frame of the animation! for AnimationFrame in range(AnimationStart, AnimationEnd + 1): # Set the current animation frame bpy.context.scene.frame_set(AnimationFrame) #print("Now working with animation frame: " + str(AnimationFrame)) # And loop for all but the Basis shapekey. row = [] for AnimationShapes in range(0, len(ShapeKeyName2)): MyData = MyShapekeys[ShapeKeyName2[AnimationShapes]].value row = row + [float("%0.4f" % (MyData))] Animation_Output.write(str(list(row)) + "\n") #print (list(row)) Animation_Output.close() #print("---------------------------") print("Done writing Animation List") print("---------------------------") # ------------------------------------ UI area ------------------------------------ class EXPORT_OT_tools_diffmap_exporter(bpy.types.Operator): '''Import from DXF file format (.dxf)''' bl_idname = "object.export_diffmaps_from_shapes" bl_description = 'Export to MetaMorph file format' bl_label = "Export Diff" +' v.'+ __version__ bl_space_type = "PROPERTIES" bl_region_type = "WINDOW" bl_context = "data" bl_context = "data" filename_ext = ".tga" filter_glob = StringProperty(default="*.tga", options={'HIDDEN'}) filepath = StringProperty(name="File Path", description="Filepath used for exporting diffmap files", maxlen= 1024, default= "", subtype='FILE_PATH') filename = bpy.props.StringProperty(name="File Name", description="Name of the file",) #name = StringProperty( name="Name", description="Name for the file (without tga extension please)", maxlen = 512, default = "Name") name = StringProperty( name="Name", description="Name for the file (without tga extension please)", maxlen = 512, default = bpy.context.active_object.name) width = IntProperty( name="Width", description="Width of image to export", default = 256, min= 1, max=65535) height = IntProperty( name="Height", description="Height of image to export", default = 256, min= 1, max=65535) shapeson = BoolProperty( name="Export ShapeKeys", description="Save shapekeys as TGA images", default = True) animationson = BoolProperty( name="Export Animation", description="Save shapekeys animation", default = True) margin = IntProperty( name="Edge Margin", description="sets outside margin around UV edges", default = 10, min= 0, max=64) ##### DRAW ##### def draw(self, context): layout = self.layout filepath = os.path.dirname( self.filepath ) #self.name = bpy.context.active_object.name #name = os.path.basename( self.filepath ) #name = os.path.splitext( name ) #if len(name[0]) > 0: # scene.DiffMapSettings.name = name[0] os.path.join(filepath) row = layout.row() row = layout.row() row.prop(self, "name") col = layout.column(align=True) col.prop(self, "width") col.prop(self, "height") col.prop(self, "margin") me = context.active_object.data col = layout.column(align=False) col.template_list( me, "uv_textures", me.uv_textures, "active_index", rows=2) col = layout.column(align=False) col.prop(self, "shapeson") col.prop(self, "animationson") def execute(self, context): #name = context.active_object.name start = time.time() main(self, context) print ("Time elapsed:", time.time() - start, "seconds.") return {'FINISHED'} def invoke(self, context, event): wm = context.window_manager wm.fileselect_add(self) self.name = bpy.context.active_object.name return {'RUNNING_MODAL'} def menu_func(self, context): default_path = os.path.split(bpy.data.filepath)[0] + "/" self.layout.operator(EXPORT_OT_tools_diffmap_exporter.bl_idname, text="Export MetaMorph ShapeKeys to DiffMaps and Animations").filepath = default_path def register(): bpy.utils.register_module(__name__) bpy.types.INFO_MT_file_export.append(menu_func) def unregister(): bpy.utils.unregister_module(__name__) bpy.types.INFO_MT_file_export.remove(menu_func) if __name__ == "__main__": register()<file_sep>/Assets/Standard Assets/Character Controllers/Sources/Scripts/FPSFlyer.js //need as child to character controler: //camera //wings //object with glide sound //object with air dash sound var cam : GameObject; var glideSound : GameObject; var screamSound : GameObject; var dashSound : GameObject; static var gliding : boolean = false; var speed = 100.0; //movment speed var gravity = 1.5; // more mean faster diving var dashSpeed = 1000; //how long and fast supposed be dash; var allowDash = true; //if dash is allowed var doubleTab =0.3; var dashProtector = 50; //Time needed before next dash var maxHeight = 1000; var minHeight = 3; private var screamSoundFlag = false; private var cameraShake; private var gravityAddonalSpeed = 0.0; //cam = transform.Find("Main Camera").gameObject.GetComponent(Camera); private var ButtonCooler : float = doubleTab; private var ButtonCount : int = 0; static var ForwardDash=0; static var BackwardDash=0; static var LeftDash=0; static var RightDash=0; private var dashFlag = false; private var dashProtectorTemp = dashProtector; private var moveDirection : Vector3; //glideSound = GameObject.Find("glide sound"); private var glideSoundFlag = false; glideSound.audio.volume = 0; function FixedUpdate() { //dash support if (allowDash) { if (ForwardDash>0) //mean also that forward dash is activated { ForwardDash -= dashSpeed/20; //more in denominator mean shorter dash; if (ForwardDash<0) //reset { ForwardDash = 0; } } if (BackwardDash>0) //mean also that backward dash is activated { BackwardDash -= dashSpeed/20; //more in denominator mean shorter dash; if (BackwardDash<0) //reset { BackwardDash = 0; } } if (LeftDash>0) //mean also that backward dash is activated { LeftDash -= dashSpeed/20; //more in denominator mean shorter dash; if (LeftDash<0) //reset { LeftDash = 0; } } if (RightDash>0) //mean also that backward dash is activated { RightDash -= dashSpeed/20; //more in denominator mean shorter dash; if (RightDash<0) //reset { RightDash = 0; } } } //Camera Shake if (cam.transform.eulerAngles.x<=270 && cam.transform.eulerAngles.x>=20) cameraShake = CameraShake.CameraShake(gravityAddonalSpeed); else cameraShake = Vector3(0,0,0); //act of move //sinking in lava Debug.Log(LavaTrigger.lavaDeath); if (LavaTrigger.lavaDeath == true) { if (screamSoundFlag==false) { screamSound.audio.Play(); screamSoundFlag = true; } if (transform.position.y>22) transform.position.y -= 0.1; screamSound.audio.volume -=0.005; } if (SpecjalBehaviour.movement == true) { //compute some glide if (glideSoundFlag == false && glideSound.audio.volume > 0) { glideSound.audio.Play(); glideSoundFlag = true; } if (glideSound.audio.volume <= 0) { glideSoundFlag = false; } if (Input.GetAxis("Vertical")>0) { if (gravityAddonalSpeed < Mathf.Sin(cam.transform.eulerAngles.x* Mathf.PI/180)*speed && Input.GetAxis("UpDown")<=0) { // audio glide support gravityAddonalSpeed += gravity; glideSound.audio.volume = gravityAddonalSpeed/speed; gliding = true; } else { if (gravityAddonalSpeed>0) gravityAddonalSpeed -= gravity*Mathf.Abs(Mathf.Sin(cam.transform.eulerAngles.x* Mathf.PI/180)); else gliding = false; glideSound.audio.volume = gravityAddonalSpeed/speed; } } else { gravityAddonalSpeed = 0; glideSound.audio.volume = 0; gliding = false; } moveDirection = cam.transform.TransformDirection(Vector3.forward); //forward and backward moveDirection.z =Input.GetAxis("Vertical")*(speed+gravityAddonalSpeed)+ForwardDash/2-BackwardDash/2; //left and right moveDirection.x =Input.GetAxis("Horizontal")*(speed+gravityAddonalSpeed)+RightDash-LeftDash; moveDirection.x += cameraShake.x; //up and down if(transform.position.y<=maxHeight && transform.position.y>=minHeight) { moveDirection.y *=Input.GetAxis("Vertical")*(speed+gravityAddonalSpeed)+ForwardDash/2-BackwardDash/2; moveDirection.y +=Input.GetAxis("UpDown")*speed; moveDirection.y += cameraShake.y; //tu gdzies opadaie w lavie } else { moveDirection.y = -50; } moveDirection = transform.TransformDirection(moveDirection); } else //disabling movement { moveDirection.y =0; if (moveDirection.x >=-5 && moveDirection.x <=5) moveDirection.x = 0; else if (moveDirection.x>5) moveDirection.x -=5; else if (moveDirection.x <-5 ) moveDirection.x +=5; if (moveDirection.z >=-5 && moveDirection.z <=5) moveDirection.z = 0; else if (moveDirection.z>5) moveDirection.z -=5; else if (moveDirection.z <-5 ) moveDirection.z +=5; cam.transform.eulerAngles.x = cam.transform.eulerAngles.x; //disabling cam glideSound.audio.Stop(); } var controller : CharacterController = GetComponent(CharacterController); var flags = controller.Move(moveDirection * Time.deltaTime); //dash detector //protection from to fast dashing after last dash if (dashProtectorTemp>0) dashProtectorTemp -= 1 * Time.deltaTime ; //protection from uncontrol dash if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.D)) { dashFlag = true; } if (allowDash && dashProtectorTemp<=0) { //forward dash if (Input.GetKeyDown(KeyCode.W)) { if (dashFlag && ButtonCooler > 0 && ButtonCount == 1/*Number of Taps you want Minus One*/) { //forward dash is activated dashProtectorTemp = dashProtector; ForwardDash=dashSpeed; dashSound.audio.Play(); dashFlag = false; } else { ButtonCooler = doubleTab; ButtonCount += 1 ; } } //backward dash if (Input.GetKeyDown(KeyCode.S)) { if (dashFlag && ButtonCooler > 0 && ButtonCount == 1/*Number of Taps you want Minus One*/) { //backward dash is activated dashProtectorTemp = dashProtector; BackwardDash=dashSpeed; dashSound.audio.Play(); dashFlag = false; } else { ButtonCooler = doubleTab ; ButtonCount += 1 ; } } //left dash if (Input.GetKeyDown(KeyCode.A)) { if (dashFlag && ButtonCooler > 0 && ButtonCount == 1/*Number of Taps you want Minus One*/) { //backward dash is activated dashProtectorTemp = dashProtector; LeftDash=dashSpeed; dashSound.audio.Play(); dashFlag = false; } else { ButtonCooler = doubleTab ; ButtonCount += 1 ; } } //right dash if (Input.GetKeyDown(KeyCode.D)) { if (dashFlag && ButtonCooler > 0 && ButtonCount == 1/*Number of Taps you want Minus One*/) { //backward dash is activated dashProtectorTemp = dashProtector; RightDash=dashSpeed; dashSound.audio.Play(); dashFlag = false; } else { ButtonCooler = doubleTab ; ButtonCount += 1 ; } } if (ButtonCooler>0) //double tab reset ButtonCooler -= 1 * Time.deltaTime ; else { dashFlag = false; ButtonCount = 0 ; } } } @script RequireComponent(CharacterController)<file_sep>/Assets/Standard Assets/Character Controllers/scripts/smoothLookAtForward.js var target1 : Transform; var target2 : Transform; var damping1 = 6.0; var damping2 = 6.0; var smooth = true; var waitTime = 10.0; private var rotation; private var timer : float = 0; function LateUpdate () { if (LavaTrigger.lavaDeath==true) { if (target1 && target2) { if (timer < waitTime) { if (smooth) { // Look at and dampen the rotation rotation = Quaternion.LookRotation(target1.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping1); } else { // Just lookat transform.LookAt(target1); } } else { if (smooth) { // Look at and dampen the rotation rotation = Quaternion.LookRotation(target2.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping2); } else { // Just lookat transform.LookAt(target2); } } Debug.Log(timer); timer += Time.deltaTime; } } } function Start () { // Make the rigid body not change rotation if (rigidbody) rigidbody.freezeRotation = true; }
b460d749bb1f02290a1fff91f9c8187f697a3a7f
[ "JavaScript", "C#", "Python" ]
16
JavaScript
Polak149/Unity
aff7ca4109d1d643f9a6fb73207d1f582a2cbe02
bba1c9a4ac5382888b430adbf3655e9083c4d264
refs/heads/master
<repo_name>dzheng533/ehangsoft.cn<file_sep>/lib/DBProvider.js var mysql = require("mysql"); var defaultOptions = { "host":"127.0.0.1", "port":3306, "database":"ehangsoft", "user":"vincent", "password":"<PASSWORD>" } exports.connect = function(options){ console.log("Connection test."); var connpara = options?options:defaultOptions; var connStr = connpara.user+":"+connpara.password +"@"+connpara.host; console.log(connStr); var conn = mysql.createConnection(connpara); return conn; }; exports.close = function(conn){ if(conn){ conn.end(); } }; <file_sep>/README.md ehangsoft.cn ============ ehangsoft.cn <file_sep>/deploy.sh #!/bin/bash server_root=$NODE_HOME function print_log(){ echo "$1" } function errot_exit(){ print_log "$1" exit 1 } print_log "Start Deploy" cp -r "./" "$server_root" print_log "Deploy Sucessful."
7180c41f5a7fcca6cd0253b46ad4faf62c32d67e
[ "JavaScript", "Markdown", "Shell" ]
3
JavaScript
dzheng533/ehangsoft.cn
06e25661b9d974635b39ed755c9c2b0a16c91bf6
0a88612d467780e0c7748dca6509514c01679c8b
refs/heads/master
<file_sep>from http.server import HTTPServer from http.server import BaseHTTPRequestHandler import psutil import os import sys PORT = 13340 class WorkerHandler(BaseHTTPRequestHandler): #Fungsi ini figunakan untuk merespon get request #jika command yang didapat adalah reqcpuloads #fungsi akan mengembalikan CPU usage dari cpu komputer def do_GET(self): try: args = self.path.split('/') if len(args) != 2: raise Exception() command = args[1] if command == 'reqcpuloads': self.send_response(200) self.end_headers() self.wfile.write(str(self.cpu_usage()).encode('utf-8')) except Exception as ex: self.send_response(500) self.end_headers() print(ex) #Fungsi untuk mengambil CPU usage #Library yang kami gunakan adalah psutil def cpu_usage(self): return psutil.cpu_percent() server = HTTPServer(("", PORT), WorkerHandler) server.serve_forever()<file_sep>#!/usr/bin/env python from threading import Thread from http.server import HTTPServer from http.server import BaseHTTPRequestHandler from aiohttp import ClientSession from random import randint from time import sleep from asyncio import coroutine import urllib.request import operator import sys PORTS = [13320, 13321, 13322, 13323, 13324] # bagian ini yang harus disimpan adalah IP address karena yang # digunakan beda komputer WORKERS = ['http://192.168.43.142', 'http://localhost'] DAEMONS = ['http://192.168.43.142', 'http://localhost'] timeout = randint(3, 5) receive_heartbeat = 'N' cpu_loads = [] role = "FOLLOWER" forward = 0 leader_port = None leader_before = 0 count_leader = 0 term = 0 append_entries = [] class WorkerCpuLoads: def __init__(self, ip, worker_cpu_load): self.ip = ip self.cpu_load = worker_cpu_load class Server(BaseHTTPRequestHandler): def do_GET(self): global timeout, cpu_loads, role, leader_port, term, receive_heartbeat, count_leader, leader_before try: args = self.path.split('/') if len(args) < 2: raise Exception() req = args[1] if req == 'vote' and len(args) > 2: new_term = int(args[2]) if role == 'LEADER': role = 'FOLLOWER' # jika node menerima heartbeat dari leader, yang # menandakan leader belum crash if (req == 'heartbeat'): if role == 'CANDIDATE': role = 'FOLLOWER' print("Leader still alive") self.response("Y") timeout = randint(3, 5) receive_heartbeat = 'Y' if count_leader==0: fileHandle = open (str(PORT)+".txt","r" ) lineList = fileHandle.readlines() fileHandle.close() if len(lineList)!=0: count_leader = int(lineList[-1]) leader_before = int(lineList[len(lineList)-2]) if leader_before != leader_port and leader_port!=None: count_leader=int(args[3]) leader_before=leader_port file = open(str(PORT)+".txt","a") file.write("%s\n" % str(leader_port)) file.write("%s\n" % str(count_leader)) file.close() leader_port = int(args[2]) # Jika leader crash, maka setiap node yang telah # habis waktu timeoutnya, otomatis akan menjadi # candidate. Setiap candidate, harus mengirim # request vote kesemua node agar mendapat mayoritas # suara. Suara yang didapat akan digunakan sebagai # perhitungan agar menjadi leader. elif req == 'vote' and new_term != term and new_term > term: # if role == 'FOLLOWER': if count_leader <= int(args[3]): self.response("voteyou") term = new_term else: self.response("notvote") elif req == 'appendentries': file = open(str(PORT)+"-cpuloads.txt","a") file.write(args[4]+"\n") file.write(args[3]+"\n") file.close() # Bagian ini adalah request dari client yang berisi # angka yang ingin dicari angka primanya # Jika yang mendapat request adalah leader, maka # load balancer akan langsung mengirim data ke worker, # tetapi jika yang menerima adalah follower, maka # request akan di forward ke leader. else: data = args[1] if role == 'LEADER': url = "http://localhost:"+str(cpu_loads[0].port)+"/"+data #url = "http://localhost:"+"13337"+"/"+data response = urllib.request.urlopen(url).read() prime_number = response.decode('utf-8') self.response(prime_number) elif role == 'FOLLOWER': url = "http://localhost:"+str(leader_port)+"/"+data response = urllib.request.urlopen(url).read() prime_number = response.decode('utf-8') self.response(prime_number) except Exception as ex: self.send_response(500) self.end_headers() print(ex) def response(self, message): if message == 'vote': try: self.send_response(200) self.end_headers() self.wfile.write('voteyou'.encode('utf-8')) except: pass elif message == 'notvote': try: self.send_response(200) self.end_headers() # self.wfile.write(message.encode('utf-8')) except: pass else: try: self.send_response(200) self.end_headers() self.wfile.write(message.encode('utf-8')) except: pass class Client: def __init__(self): self.count = 0 self.daemon_count = len(DAEMONS) self.leader_timeout = 1 # thread def run(self): Thread(target=self.timeout).start() Thread(target=self.leader_timeout_counter).start() Thread(target=self.request_cpu_loads).start() # kalau suatu node menjadi leader, maka setiap periode # tertentu, node ini akan mengirimkan hearbeat kesemua # node yang menjadi follower, untuk memberitahu bahwa # dirinya belum crash def broadcast_heartbeat(self): print("send heartbeat") global cpu_loads, term, count_leader for port in PORTS: if port != PORT: url = "http://localhost:"+str(port)+"/heartbeat/"+str(PORT)+"/"+str(count_leader) try: urllib.request.urlopen(url).read() except: pass # apabila pada waktu tertentu leader tidak mengirimkan # heartbeat, maka diasumsikan leader telah crash, sehingga # harus ada leader baru. Untuk itu node sebagai follower # dapat mencalonkan diri sebagai leader yang baru dan # mengirimkan pesan vote. Setelah node menerima 1/2n + 1 # suara dari jumlah server yang tersedia, maka node dapat # menjadi leader. def do_Campaign(self): print("do campaign") global role, term, count_leader term += 1 self.count = 1 role = "CANDIDATE" print(count_leader) for port in PORTS: if port != PORT: url = "http://localhost:"+str(port)+"/vote/"+str(term)+"/"+str(count_leader) try: response = urllib.request.urlopen(url).read() data = response.decode('utf-8') # print(self.count) if data == 'voteyou': self.count += 1 except Exception as ex: # print(ex) pass if self.count > 1/2 * len(PORTS): self.become_leader() else: self.count = 0 # Jika candidate berhasil mendapat vote mayoritas # maka node yang berstatus candidate akan menjadi # leader def become_leader(self): print("become leader") global role, count_leader count_leader += 1 role = "LEADER" self.broadcast_heartbeat() # timeout node, tapi bukan milik leader def timeout(self): global timeout, receive_heartbeat, role while True: timeout -= 1 # print("gg") if timeout == 0 : if role == 'FOLLOWER': print(role) if receive_heartbeat == 'N': # print("ff") self.do_Campaign() timeout = randint(3, 5) self.count = 0 elif role == 'CANDIDATE': role = 'FOLLOWER' timeout = randint(3, 5) # if role == 'LEADER': # role = 'FOLLOWER' if receive_heartbeat == 'Y': receive_heartbeat = 'N' sleep(1) # timeout counter yang digunakan sebagai penghitung mundur # untuk mengirim heartbeat ke follower def leader_timeout_counter(self): global role while True: if role == 'LEADER': print("hhh") self.leader_timeout -= 1 if self.leader_timeout == 0: self.broadcast_heartbeat() self.leader_timeout = 1 sleep(1) def request_cpu_loads(self): global append_entries, cpu_loads, role, count_leader, leader_before self.timeout = 5 while True: self.timeout -= 1 self.majority_consistent = 0 commited = False if self.timeout == 0: if role == 'LEADER': print("ggg") if count_leader==0: fileHandle = open (str(PORT)+".txt","r" ) lineList = fileHandle.readlines() fileHandle.close() if len(lineList)!=0: count_leader = int(lineList[-1]) leader_before = int(lineList[len(lineList)-2]) if leader_before!=PORT and PORT!=None: leader_before=PORT file = open(str(PORT)+".txt","a") file.write("%s\n" % str(PORT)) file.write("%s\n" % str(count_leader)) file.close() cpu_loads = [] daemon_count = 0 for ip in DAEMONS: url = ip+":"+str(DAEMONS)+"/reqcpuloads" try: response = urllib.request.urlopen(url).read() cpu_load = float(response.decode('utf-8')) worker = WorkerCpuLoads(ip, cpu_load) # worker = WorkerCpuLoads(WORKERS[DAEMONS.index(port)], cpu_load) cpu_loads.append(worker) except: daemon_count += 1 if daemon_count == self.daemon_count: self.get_cpu_loads_from_file() cpu_loads.sort(key=operator.attrgetter('cpu_load'), reverse=True) for port in PORTS: for item in cpu_loads: url = "http://localhost:"+str(port)+"/appendentries/"+str(port)+"/"+str(item.cpu_load)+"/"+item.ip try: response = urllib.request.urlopen(url).read() print("append") except: pass # ketika leader menerima cpu loads dari daemon, maka entries akan # ditambahkan kedalam log leader, namun belum di commit, yang artinya # entries belum di tulis kedalam file. file = open(str(PORT)+"-cpuloads.txt","w") for item in cpu_loads: file.write("%s\n" % str(item.ip)) file.write("%s\n" % str(item.cpu_load)) file.close() # Simpan siapa ketua dan log cpu load self.timeout = 5 self.cpu_loads_received = 'Y' sleep(1) def get_cpu_loads_from_file(): global cpu_loads fileHandle = open (str(PORT)+"-cpuloads.txt","r" ) lineList = fileHandle.readlines() fileHandle.close() return lineList def readFile(): global count_leader fileHandle = open (str(PORT)+".txt","r" ) lineList = fileHandle.readlines() fileHandle.close() if len(lineList)!=0: count_leader = int(lineList[-1]) leader_before = int(lineList[len(lineList)-2]) PORT = int(sys.argv[1]) if __name__ == '__main__': readFile() thread = Client() thread.run() server = HTTPServer(("", PORT), Server) server.serve_forever()
a45f3c9f0305a3827186c9837e7b7065d52ff59f
[ "Python" ]
2
Python
anwarramadha/SISTAH
0a8ab36247c97b66fb938aefcf54f056e65af322
e5539bb2e5b187dc5b0105da7bfb7d21fac5e960
refs/heads/master
<repo_name>Torrencem/pretty_dtoa<file_sep>/README.md # Pretty dtoa Configurable float and double printing. ``pretty_dtoa`` Comes with lots of options for configuring different aspects of displaying floats, and has only 1 dependency total (including dependencies of dependencies), for very fast compile times. This crate uses the [ryu-floating-decimal crate](https://github.com/Torrencem/ryu-floating-decimal) (itself a fork of the [ryu crate](https://github.com/dtolnay/ryu)) to generate a "floating decimal", or a floating point with radix 10, and then it uses formatting rules particular to the configuration to create a formatted string. This module is only slightly slow (usually between 1x and 2x slower than the default Display implementation for f64). Benchmarks can be run with ``cargo bench``. Consider using ``pretty_dtoa`` if the default behavior of ``Display`` and alternative float printing libraries like ``ryu`` is not ideal for one reason or another ## Example ```rust use pretty_dtoa::{dtoa, FmtFloatConfig}; let config = FmtFloatConfig::default() .force_no_e_notation() // Don't use scientific notation .add_point_zero(true) // Add .0 to the end of integers .max_significant_digits(4) // Stop after the first 4 non-zero digits .radix_point(',') // Use a ',' instead of a '.' .round(); // Round after removing non-significant digits assert_eq!(dtoa(12459000.0, config), "12460000,0"); ``` See the tests in ``src/lib.rs`` for examples of each feature, and [the documentation](https://docs.rs/pretty_dtoa) to see all configurable features. <file_sep>/benches/dtoa_benchmark.rs use criterion::{black_box, criterion_group, criterion_main, Criterion}; use pretty_dtoa::*; pub fn criterion_benchmark(c: &mut Criterion) { c.bench_function("3.14159 -> string (builtin Display)", |b| { b.iter(|| format!("{}", black_box(3.14159f64))) }); c.bench_function( "3.14159 -> string (display_float dtoa default config)", |b| b.iter(|| dtoa(black_box(3.14159f64), FmtFloatConfig::default())), ); c.bench_function("3.14e10 -> string (builtin Display)", |b| { b.iter(|| format!("{}", black_box(3.14e10f64))) }); c.bench_function( "3.14e10 -> string (display_float dtoa default config)", |b| b.iter(|| dtoa(black_box(3.14e10), FmtFloatConfig::default())), ); c.bench_function("13124014 -> string (builtin Display)", |b| { b.iter(|| format!("{}", black_box(13124014f64))) }); c.bench_function( "13124014 -> string (display_float dtoa default config)", |b| b.iter(|| dtoa(black_box(13124014f64), FmtFloatConfig::default())), ); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); <file_sep>/src/lib.rs //! Print floats with many options: //! //! ``` //! use pretty_dtoa::{dtoa, FmtFloatConfig}; //! //! let config = FmtFloatConfig::default() //! .max_decimal_digits(-3) // cut off at 3 decimals left of the decimal point //! .truncate() // don't round //! .force_no_e_notation() // don't use exponential notation //! .add_point_zero(true); // add a .0 to the end of integer values //! //! assert_eq!(dtoa(123123.0, config), "123000.0"); //! assert_eq!(dtoa(99999.0, config), "99000.0"); //! ``` // Testing macros, to make sure edge cases are hit #[cfg(not(test))] macro_rules! hit { ($ident:ident) => {}; } // Mark a code condition as hit #[cfg(test)] macro_rules! hit { ($ident:ident) => {{ extern "C" { #[no_mangle] static $ident: $crate::__rt::AtomicUsize; } unsafe { $ident.fetch_add(1, $crate::__rt::Ordering::Relaxed); } }}; } #[cfg(test)] mod __rt { pub use std::sync::atomic::{AtomicUsize, Ordering}; pub struct Guard { mark: &'static AtomicUsize, name: &'static str, value_on_entry: usize, } impl Guard { pub fn new(mark: &'static AtomicUsize, name: &'static str) -> Guard { let value_on_entry = mark.load(Ordering::Relaxed); Guard { mark, name, value_on_entry, } } } impl Drop for Guard { fn drop(&mut self) { if std::thread::panicking() { return; } let value_on_exit = self.mark.load(Ordering::Relaxed); assert!( value_on_exit > self.value_on_entry, format!("mark was not hit: {}", self.name) ) } } } use ryu_floating_decimal::{d2d, f2d}; use std::char; #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum RoundMode { Round, Truncate, } /// Configuration for formatting floats into strings. Look at the associated methods for this type /// to see default values and specific examples. /// /// # Example /// /// ``` /// use pretty_dtoa::{dtoa, FmtFloatConfig}; /// /// let config = FmtFloatConfig::default() /// .round() /// .max_significant_digits(5); /// /// assert_eq!(dtoa(123.4567, config), "123.46"); /// ``` #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct FmtFloatConfig { /// A max number of significant digits to include /// in the formatted string (after the first non-zero digit). /// None means include all digits pub max_sig_digits: Option<u8>, /// A min number of significant digits to include /// in the formatted string (after the first non-zero digit). /// None means no minimum pub min_sig_digits: Option<u8>, /// A max number of digits after the decimal point to include. pub max_decimal_digits: Option<i8>, /// A min number of digits after the decimal point to include. pub min_decimal_digits: Option<i8>, /// How many digits left of the decimal point there can be /// using scientific notation pub upper_e_break: i8, /// Lower equivelent of upper_e_break pub lower_e_break: i8, /// Ignore digits after (and including) a certain number of /// consecutive 9's or 0's pub ignore_extremes: Option<u8>, /// Round or truncate pub round_mode: RoundMode, /// Force scientific e notation pub force_e_notation: bool, /// Force no scientific e notation. Overrides force_e_notation pub force_no_e_notation: bool, /// Capitalize the e in scientific notation pub capitalize_e: bool, /// Add a .0 at the end of integers pub add_point_zero: bool, /// The maximum number of characters in the string. This /// should be greater than or equal to 7 to guarantee all floats /// will print correctly, but can be smaller for certain floats pub max_width: Option<u8>, /// The seperator between the integer and non-integer part pub radix_point: char, } impl FmtFloatConfig { /// A default configuration. This will always round-trip, so /// using ``str::parse::<f64>`` or ``str::parse:<f32>`` will /// give the exact same float. pub const fn default() -> Self { FmtFloatConfig { max_sig_digits: None, min_sig_digits: None, max_decimal_digits: None, min_decimal_digits: None, upper_e_break: 4, lower_e_break: -4, ignore_extremes: None, round_mode: RoundMode::Round, force_e_notation: false, force_no_e_notation: false, capitalize_e: false, add_point_zero: true, max_width: None, radix_point: '.', } } /// The maximum number of non-zero digits to include in the string pub const fn max_significant_digits(mut self, val: u8) -> Self { self.max_sig_digits = Some(val); self } /// The minimum number of non-zero digits to include in the string pub const fn min_significant_digits(mut self, val: u8) -> Self { self.min_sig_digits = Some(val); self } /// The maximum number of digits past the decimal point to include in the string pub const fn max_decimal_digits(mut self, val: i8) -> Self { self.max_decimal_digits = Some(val); self } /// The minimum number of digits past the decimal point to include in the string pub const fn min_decimal_digits(mut self, val: i8) -> Self { self.min_decimal_digits = Some(val); self } /// The upper exponent value that will force using exponent notation /// (default: 4) pub const fn upper_e_break(mut self, val: i8) -> Self { self.upper_e_break = val; self } /// The lower exponent value that will force using exponent notation /// (default: -4) pub const fn lower_e_break(mut self, val: i8) -> Self { self.lower_e_break = val; self } /// Ignore digits after and including a certain number of /// consecutive 9's or 0's. This is useful for printing /// numbers with floating point errors to humans, even /// if the numbers are technically slightly adjusted. /// (example: 3.5999951 -> 3.6) pub const fn ignore_extremes(mut self, limit: u8) -> Self { self.ignore_extremes = Some(limit); self } /// When cutting off after a certain number of /// significant digits, ignore any further digits. /// Opposite of ``round(self)``. pub const fn truncate(mut self) -> Self { self.round_mode = RoundMode::Truncate; self } /// When cutting off after a certain number of /// significant digits / decimal digits, read /// the next digit and round up / down. This is /// the default, but it doesn't matter in the /// default config, since no rounding happens. pub const fn round(mut self) -> Self { self.round_mode = RoundMode::Round; self } /// Force all floats to be in scientific notation. /// (example: 31 -> 3.1e1) pub const fn force_e_notation(mut self) -> Self { self.force_e_notation = true; self.force_no_e_notation = false; self } /// Force all floats to not be in scientific notation. /// (example: 3e10 -> 30000000000) pub const fn force_no_e_notation(mut self) -> Self { self.force_no_e_notation = true; self.force_e_notation = false; self } /// Capitalize the e in e notation. /// (example: 3.1e10 -> 3.1E10) /// (default: false) pub const fn capitalize_e(mut self, val: bool) -> Self { self.capitalize_e = val; self } /// Add a ".0" at the end of integers. /// (example: 31 -> 31.0) /// (default: true) pub const fn add_point_zero(mut self, val: bool) -> Self { self.add_point_zero = val; self } /// The maximum width of all the characters in the string. This /// should be greater than or equal to 7 to guarantee all floats /// will print correctly, but can be smaller for certain floats. /// Floats that are impossible to represent in a certain width will /// be represented by pound signs. pub const fn max_width(mut self, val: u8) -> Self { self.max_width = Some(val); self } /// Allows any width of strings. This is set by default pub const fn no_max_width(mut self) -> Self { self.max_width = None; self } /// The seperator between the integer and non-integer part /// of the float string /// (default: `'.'`) pub const fn radix_point(mut self, val: char) -> Self { self.radix_point = val; self } } const fn digit_to_u8(val: u8) -> u8 { val + '0' as u8 } fn digits_to_a(sign: bool, mut digits: Vec<u8>, mut e: i32, config: FmtFloatConfig) -> String { // The main string formatting function. digits is a vector of the digits // found using the ryu backend function. The value of the float is // <- if sign>0.<digits> * 10^<e> // NOTE: digits is ascii, so the digit "5" would be represented as "digit_to_u8(5)" if let Some(limit) = config.max_sig_digits { // Remove extra significant digits let limit = limit as usize; if digits.len() > limit { let removed = digits.drain(limit..).next().unwrap(); if config.round_mode == RoundMode::Round && removed >= digit_to_u8(5) { // round up let mut l = digits.len() - 1; digits[l] += 1; while digits[l] == digit_to_u8(10) { if l == 0 { digits[0] = digit_to_u8(1); e += 1; break; } digits.pop(); l -= 1; digits[l] += 1; } } } } if let Some(limit) = config.max_decimal_digits { // Remove extra decimal digits let adjusted_limit_position = limit as i32 + e; if (0 <= adjusted_limit_position) && (adjusted_limit_position < digits.len() as i32) { let final_char = digits .drain(adjusted_limit_position as usize..) .nth(0) .unwrap(); if config.round_mode == RoundMode::Round && final_char >= digit_to_u8(5) { // round up let mut l = digits.len() - 1; digits[l] += 1; while digits[l] == digit_to_u8(10) { if l == 0 { digits[0] = digit_to_u8(1); e += 1; break; } digits.pop(); l -= 1; digits[l] += 1; } } } } if let Some(limit) = config.ignore_extremes { // Ignore <limit> consecutive 9's or 0's. A copy of digits is made let mut stripped_string: Vec<u8> = Vec::with_capacity(30); let mut nine_counter = 0; let mut zero_counter = 0; for digit in digits.iter() { if *digit != digit_to_u8(9) { nine_counter = 0; } else { nine_counter += 1; if nine_counter >= limit { // 14999... stripped_string.drain((stripped_string.len() + 1 - nine_counter as usize)..); // -> 14 let l = stripped_string.len(); if l == 0 { // for strings like 999 // 999e3 -> 1e4 stripped_string.push(digit_to_u8(1)); e += 1; } else { // Rounding doesn't have to happen here, because what was removed // was exactly limit 9's // 15 stripped_string[l - 1] += 1; } break; } } if *digit != digit_to_u8(0) { zero_counter = 0; } else { zero_counter += 1; if zero_counter >= limit { // 14000... stripped_string.drain((stripped_string.len() + 1 - zero_counter as usize)..); // 14 break; } } stripped_string.push(*digit); } digits = stripped_string; } if let Some(limit) = config.min_sig_digits { // Pad 0's to get enough significant digits let mut curr = digits.len() as u8; while curr < limit { digits.push(digit_to_u8(0)); curr += 1; } } if let Some(limit) = config.min_decimal_digits { // Pad 0's to get enough decimal digits let adjusted_limit_position = limit as i32 + e; while (digits.len() as i32) < adjusted_limit_position { digits.push(digit_to_u8(0)); } } let mut use_e_notation = (e > config.upper_e_break as i32 || e <= config.lower_e_break as i32 || config.force_e_notation) && !config.force_no_e_notation; if let Some(max_width) = config.max_width { // Check if it is needed to force using e notation for max width let max_width = if sign { max_width - 1 } else { max_width }; // Is it impossible to represent the value without e notation? if e > 0 && e + if config.add_point_zero { 2 } else { 0 } > max_width as i32 { hit!(e_width_case_a); use_e_notation = true; } else if -e + 3 > max_width as i32 { hit!(e_width_case_b); use_e_notation = true; } else if !use_e_notation { hit!(e_width_case_c); // Otherwise, prepare to not use e notation let is_integer = e > digits.len() as i32; let extra_length = if config.add_point_zero && is_integer { 2 } else { 0 } + if !is_integer && !(e > 0 && e as u8 == max_width) { 1 } else { 0 } + if e > 0 && digits.len() < e as usize { e - digits.len() as i32 } else { 0 } + if e <= 0 { -e + 1 } else { 0 }; let total_length = digits.len() + extra_length as usize; if total_length > max_width as usize { let final_char = digits .drain((max_width as usize - extra_length as usize)..) .nth(0) .unwrap(); if config.round_mode == RoundMode::Round && final_char >= digit_to_u8(5) { // round up let mut l = digits.len() - 1; digits[l] += 1; while digits[l] == digit_to_u8(10) { if l == 0 { digits[0] = digit_to_u8(1); e += 1; break; } digits.pop(); l -= 1; digits[l] += 1; } } } } } // Final formatting stage if use_e_notation { let mut add_zero_after_radix_point = config.max_width.is_none(); if let Some(max_width) = config.max_width { let mut tail_as_str: String = digits.drain(1..).map(|val| val as char).collect(); let e_length = format!("{}", e - 1).len(); let extra_length = 3 + e_length + if sign { 1 } else { 0 }; if extra_length >= max_width as usize { tail_as_str.drain(..); } else { tail_as_str.truncate(max_width as usize - extra_length); } if tail_as_str.len() + extra_length + 1 <= max_width as usize { add_zero_after_radix_point = true; } // Very special case: can't include a decimal point // within max_width if tail_as_str.len() == 0 && max_width == 7 && sign { return format!( "-{}{}{}", digits[0] as char, if config.capitalize_e { "E" } else { "e" }, e - 1 ); } // Defer to the generic e-notation case for c in tail_as_str.chars() { digits.push(c as u8); } } // Generic e-notation case let mut res = String::with_capacity(digits.len() + 5); if sign { res.push('-'); } res.push(digits[0] as char); res.push(config.radix_point); if digits.len() == 1 { if add_zero_after_radix_point { res.push('0'); } } else { for c in &digits[1..] { res.push(*c as char); } } if config.capitalize_e { res.push('E'); } else { res.push('e'); } res.push_str(format!("{}", e - 1).as_ref()); return res; } // Non-e-notation case let mut as_str = String::with_capacity(digits.len() + 3); if sign { as_str.push('-'); } let mut curr = 0; if e <= 0 { as_str.push('0'); as_str.push(config.radix_point); for _ in 0..-e { as_str.push('0'); } } for digit in digits { if e > 0 && curr == e { as_str.push(config.radix_point); } as_str.push(digit as char); curr += 1; } let is_integer = curr <= e; while e > 0 && curr < e { as_str.push('0'); curr += 1; } if is_integer && config.add_point_zero { as_str.push(config.radix_point); as_str.push('0'); } as_str } /// Convert a double-precision floating point value (``f64``) to a string /// using a given configuration /// /// # Example /// /// ``` /// use pretty_dtoa::{dtoa, FmtFloatConfig}; /// /// let config = FmtFloatConfig::default() /// .force_no_e_notation() // Don't use scientific notation /// .add_point_zero(true) // Add .0 to the end of integers /// .max_significant_digits(4) // Stop after the first 4 non-zero digits /// .radix_point(',') // Use a ',' instead of a '.' /// .round(); // Round after removing non-significant digits /// /// assert_eq!(dtoa(12459000.0, config), "12460000,0"); /// ``` pub fn dtoa(value: f64, config: FmtFloatConfig) -> String { if value.is_nan() { return "NaN".to_string(); } else if value.is_infinite() { if value.is_sign_positive() { return "inf".to_string(); } else { return "-inf".to_string(); } } let sign = value.is_sign_negative(); let (s, exp) = if value == 0.0 { (String::from("0"), 1) } else { let rad_10 = d2d(value); let s = format!("{}", rad_10.mantissa); let exp = rad_10.exponent + s.len() as i32; (s, exp) }; let s = digits_to_a(sign, s.into_bytes(), exp, config); if let Some(limit) = config.max_width { if s.len() > limit as usize { return std::iter::repeat('#').take(limit as usize).collect(); } } s } /// Convert a single-precision floating point value (``f32``) to a string /// using a given configuration pub fn ftoa(value: f32, config: FmtFloatConfig) -> String { if value.is_nan() { return "NaN".to_string(); } else if value.is_infinite() { if value.is_sign_positive() { return "inf".to_string(); } else { return "-inf".to_string(); } } let (s, exp) = if value == 0.0 { (String::from("0"), 1) } else { let rad_10 = f2d(value); let s = format!("{}", rad_10.mantissa); let exp = rad_10.exponent + s.len() as i32; (s, exp) }; let sign = value.is_sign_negative(); let s = digits_to_a(sign, s.into_bytes(), exp, config); if let Some(limit) = config.max_width { if s.len() > limit as usize { return std::iter::repeat('#').take(limit as usize).collect(); } } s } #[cfg(test)] mod tests { // Macro for checking coverage marks macro_rules! check { ($ident:ident) => { #[no_mangle] static $ident: $crate::__rt::AtomicUsize = $crate::__rt::AtomicUsize::new(0); let _guard = $crate::__rt::Guard::new(&$ident, stringify!($ident)); }; } use super::*; use rand; use rand::Rng; #[test] fn test_widths() { check!(test_widths_internal); // Test random floats with several configurations, and // make sure that .max_width(_) does its job let mut rng = rand::thread_rng(); let configs = &[ FmtFloatConfig::default(), FmtFloatConfig::default().force_no_e_notation(), FmtFloatConfig::default().add_point_zero(true), FmtFloatConfig::default() .truncate() .force_e_notation() .min_significant_digits(5), ]; for width in 5..=13 { for i in 0..20000 { let config = configs[i % configs.len()].max_width(width); let val = f64::from_bits(rng.gen::<u64>()); if val.is_nan() { continue; } let as_string = dtoa(val, config); assert!( as_string.len() <= width as usize, "Found bad example for string width: '{}' at width {} gives {}", val, width, as_string ); if as_string.chars().nth(0) == Some('#') { assert!(width <= 6, "Found example of a too-wide float: {}", val); hit!(test_widths_internal); } } } } #[test] fn test_round_trip_dtoa() { // Make sure random floats with several configurations // round trip perfectly let mut rng = rand::thread_rng(); let configs = &[ FmtFloatConfig::default(), FmtFloatConfig::default() .force_no_e_notation() .add_point_zero(true), FmtFloatConfig::default().force_e_notation(), ]; for _ in 0..20000 { for config in configs.iter().cloned() { let val = f64::from_bits(rng.gen::<u64>()); if val.is_nan() { continue; } let as_string = dtoa(val, config); let round = as_string.parse::<f64>().unwrap(); assert!(round == val, "Found bad example for round trip: value '{}' gives string '{}' which turns into value '{}'", val, as_string, round); } } } #[test] fn test_round_trip_ftoa() { // Test round tripping for random f32's let mut rng = rand::thread_rng(); let configs = &[ FmtFloatConfig::default(), FmtFloatConfig::default() .force_no_e_notation() .add_point_zero(true), FmtFloatConfig::default().force_e_notation(), ]; for _ in 0..20000 { for config in configs.iter().cloned() { let val = f32::from_bits(rng.gen::<u32>()); if val.is_nan() { continue; } let as_string = ftoa(val, config); let round = as_string.parse::<f32>().unwrap(); assert!(round == val, "Found bad example for round trip: value '{}' gives string '{}' which turns into value '{}'", val, as_string, round); } } } #[test] fn test_max_sig_digits() { let config = FmtFloatConfig::default().round().max_significant_digits(5); assert_eq!(dtoa(3.111111, config), "3.1111"); assert_eq!(dtoa(123.4567, config), "123.46"); assert_eq!(dtoa(0.0001234567, config), "0.00012346"); assert_eq!(dtoa(22.29999, config), "22.3"); assert_eq!(dtoa(4.1, config), "4.1"); let config = FmtFloatConfig::default() .truncate() .max_significant_digits(4); assert_eq!(dtoa(3.999999, config), "3.999"); assert_eq!(dtoa(555.5555, config), "555.5"); assert_eq!(dtoa(923.1, config), "923.1"); } #[test] fn test_min_sig_digits() { let config = FmtFloatConfig::default().min_significant_digits(5); assert_eq!(dtoa(3.111111, config), "3.111111"); assert_eq!(dtoa(12.0, config), "12.000"); assert_eq!(dtoa(340.0, config), "340.00"); assert_eq!(dtoa(123.4567, config), "123.4567"); assert_eq!(dtoa(0.00123, config), "0.0012300"); } #[test] fn test_max_decimal_digits() { let config = FmtFloatConfig::default().max_decimal_digits(3).round(); assert_eq!(dtoa(3.41214, config), "3.412"); assert_eq!(dtoa(3.4129, config), "3.413"); assert_eq!(dtoa(3.4999, config), "3.5"); assert_eq!(dtoa(1293.4129, config), "1293.413"); assert_eq!(dtoa(203.4999, config), "203.5"); assert_eq!(dtoa(0.002911, config), "0.003"); let config = FmtFloatConfig::default().max_decimal_digits(3).truncate(); assert_eq!(dtoa(3.41214, config), "3.412"); assert_eq!(dtoa(3.4129, config), "3.412"); assert_eq!(dtoa(3.4999, config), "3.499"); assert_eq!(dtoa(393.4129, config), "393.412"); let config = FmtFloatConfig::default() .max_decimal_digits(-3) .truncate() .force_no_e_notation() .add_point_zero(true); assert_eq!(dtoa(123123.0, config), "123000.0"); assert_eq!(dtoa(99999.0, config), "99000.0"); let config = FmtFloatConfig::default() .max_decimal_digits(-3) .round() .force_no_e_notation() .add_point_zero(true); assert_eq!(dtoa(123123.0, config), "123000.0"); assert_eq!(dtoa(123923.0, config), "124000.0"); assert_eq!(dtoa(99999.0, config), "100000.0"); } #[test] fn test_min_decimal_digits() { let config = FmtFloatConfig::default().min_decimal_digits(3); assert_eq!(dtoa(3.4, config), "3.400"); assert_eq!(dtoa(10.0, config), "10.000"); assert_eq!(dtoa(100.0, config), "100.000"); let config = FmtFloatConfig::default().min_decimal_digits(5); assert_eq!(dtoa(0.023, config), "0.02300"); assert_eq!(dtoa(0.123, config), "0.12300"); assert_eq!(dtoa(0.12345678, config), "0.12345678"); } #[test] fn test_upper_e_break() { let config = FmtFloatConfig::default().upper_e_break(3); assert_eq!(dtoa(23.4, config), "23.4"); assert_eq!(dtoa(892.3, config), "892.3"); assert_eq!(dtoa(1892.3, config), "1.8923e3"); assert_eq!(dtoa(71892.3, config), "7.18923e4"); } #[test] fn test_lower_e_break() { let config = FmtFloatConfig::default().lower_e_break(-3); assert_eq!(dtoa(0.123, config), "0.123"); assert_eq!(dtoa(0.0123, config), "0.0123"); assert_eq!(dtoa(0.00123, config), "0.00123"); assert_eq!(dtoa(0.000123, config), "1.23e-4"); assert_eq!(dtoa(0.0000123, config), "1.23e-5"); } #[test] fn test_ignore_extremes() { let config = FmtFloatConfig::default().ignore_extremes(3); assert_eq!(dtoa(12.1992, config), "12.1992"); assert_eq!(dtoa(12.199921, config), "12.2"); assert_eq!(dtoa(12.1002, config), "12.1002"); assert_eq!(dtoa(12.10002, config), "12.1"); let config = FmtFloatConfig::default() .ignore_extremes(3) .add_point_zero(true); assert_eq!(dtoa(99.99, config), "100.0"); } #[test] fn test_force_e_notation() { let config = FmtFloatConfig::default().force_e_notation(); assert_eq!(dtoa(1.0, config), "1.0e0"); assert_eq!(dtoa(15.0, config), "1.5e1"); assert_eq!(dtoa(0.150, config), "1.5e-1"); } #[test] fn test_force_no_e_notation() { let config = FmtFloatConfig::default() .force_no_e_notation() .add_point_zero(false); let s = format!("{}", 1.123e20); assert_eq!(dtoa(1.123e20, config), s); let s = format!("{}", 1.123e-20); assert_eq!(dtoa(1.123e-20, config), s); } #[test] fn test_capitalize_e() { let config = FmtFloatConfig::default().capitalize_e(true); assert_eq!(dtoa(1.2e8, config), "1.2E8"); } #[test] fn test_add_point_zero() { let config = FmtFloatConfig::default().add_point_zero(true); assert_eq!(dtoa(1230.0, config), "1230.0"); assert_eq!(dtoa(129.0, config), "129.0"); assert_eq!(dtoa(12.2, config), "12.2"); let config = FmtFloatConfig::default().add_point_zero(false); assert_eq!(dtoa(1230.0, config), "1230"); assert_eq!(dtoa(129.0, config), "129"); assert_eq!(dtoa(12.2, config), "12.2"); } #[test] fn test_max_width_specifics() { check!(e_width_case_a); check!(e_width_case_b); check!(e_width_case_c); let config = FmtFloatConfig::default().max_width(6).force_no_e_notation(); assert_eq!(dtoa(123.4533, config), "123.45"); assert_eq!(dtoa(0.00324, config), "0.0032"); assert_eq!(dtoa(-0.0324, config), "-0.032"); assert_eq!(dtoa(3e10, config), "3.0e10"); assert_eq!(dtoa(3.1e10, config), "3.1e10"); let config = FmtFloatConfig::default().max_width(5).force_no_e_notation(); assert_eq!(dtoa(3e10, config), "3.e10"); assert_eq!(dtoa(3.1e10, config), "3.e10"); let config = FmtFloatConfig::default().max_width(8).force_no_e_notation(); assert_eq!(dtoa(3.24e-10, config), "3.24e-10"); assert_eq!(dtoa(3.24e10, config), "3.24e10"); let config = FmtFloatConfig::default().max_width(5); assert_eq!(dtoa(-3e100, config), "#####"); } #[test] fn test_radix_point() { let config = FmtFloatConfig::default() .radix_point(',') .add_point_zero(true); assert_eq!(dtoa(123.4, config), "123,4"); assert_eq!(dtoa(1.3e10, config), "1,3e10"); assert_eq!(dtoa(123.0, config), "123,0"); } #[test] fn test_issue_i() { let config = FmtFloatConfig::default() .max_decimal_digits(2) .add_point_zero(true); assert_eq!(dtoa(0., config), "0.0"); let config = FmtFloatConfig::default() .max_decimal_digits(2) .add_point_zero(false); assert_eq!(dtoa(0., config), "0"); } } <file_sep>/Cargo.toml [package] name = "pretty_dtoa" version = "0.3.0" authors = ["<NAME> <<EMAIL>>"] edition = "2018" description = "Configurable floating point number to string conversions, with many options for controlling various aspects of displaying floats." readme = "README.md" license = "MIT OR Apache-2.0" documentation = "https://docs.rs/pretty_dtoa" homepage = "https://github.com/torrencem/pretty_dtoa" repository = "https://github.com/torrencem/pretty_dtoa" keywords = ["float", "double", "display", "dtoa"] categories = ["value-formatting"] [dev-dependencies] criterion = "0.3" rand = "0.7.3" [[bench]] name = "dtoa_benchmark" harness = false [dependencies] ryu_floating_decimal = "0.1.0"
7e4f3658188888bfbd99ae4b75a5d478819a685b
[ "Markdown", "Rust", "TOML" ]
4
Markdown
Torrencem/pretty_dtoa
25286ff50ca81ed7e6bc4782581c4e835c4493da
f721aa46e50f176f265d60fc5465ead9bf92cffa
refs/heads/master
<repo_name>Lucassion/exercicios<file_sep>/exercicio-02/script.js /* Crie um programa que exiba o resultado da tabuada de um número digitado pelo usuário. O programa deve: - Receber um input numérico do usuário; - Questionar se o usuário quer ver o resultado de uma multiplicação específica: - Se OK (quer ver a multiplicação específica): - Receber um segundo input numérico do usuário; - Mostrar ao usuário o resultado da multiplicação do primeiro e do segundo valor; Exemplo: valor1 X valor2 = resultado - Se Cancelar (não quer ver a multiplicação específica): - Mostrar ao usuário o resultado de todas as multiplicações, do 0 ao 10; Exemplo: valor X 1 = resultado valor X 2 = resultado valor X 3 = resultado ... - Bônus: Garantir que o usuário digite números nos inputs, repetindo a pergunta caso ele digite qualquer outra coisa que não números; */<file_sep>/exercicio-03/script.js /* DESAFIO Crie um programa que reordene vetores. Esse programa deve: - Receber 10 valores de mesmo tipo (numéricos ou texto) e coloque-os em um vetor; - Ordene o vetor em ordem crescente e mostre o resultado ao usuário; */<file_sep>/exercicio-01/script.js /* Crie um programa que receba dois inputs numéricos do usuário. Esse programa deve: - Retornar para o usuário o resultado da soma dos dois valores, somente quando este for maior que 100; - Garantir que o usuário digite números nos dois inputs, repetindo a pergunta caso ele digite qualquer outra coisa que não números; */
2d95cf9da0187b45c5c0e966d2f41cd653a01207
[ "JavaScript" ]
3
JavaScript
Lucassion/exercicios
af6b2506c109a1401a9b0435d5133af17917e47a
fe4019495bbc0ac4e34875d2dc4f50fa09e30232
refs/heads/master
<repo_name>jakeaglass/SwiftScripting<file_sep>/sbsc.py #!/usr/bin/env python2.7 # Copyright (c) 2015 <NAME>. # # 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. # # Creates a Swift source file containing an enum encompassing the scripting # class names for the SDEF file specified on the command line. # # Sample usage: # # sbsc.py App.sdef # import os import string import sys from sbhc import enum_case def transform(name_string): name_string = string.replace(name_string, '"', '') name_string = string.replace(name_string, '-', ' ') name_string = string.replace(string.capwords(name_string), ' ', '') return enum_case('', name_string) def name_from_path(path): last_part = path.split("/")[-1] return last_part.split('.')[0] command_template = "xmllint --xpath '//suite/class/@name' {}" pipe = os.popen(command_template.format(sys.argv[1])) raw_names = pipe.read() pipe.close() enum_name = '{}Scripting'.format(name_from_path(sys.argv[1])) out_file = open('{}.swift'.format(enum_name), 'w') out_file.write('public enum {}: String {{\n'.format(enum_name)) for raw_name in raw_names.strip().split("name="): if len(raw_name.strip()): out_file.write(' case {} = {}\n'.format(transform(raw_name), raw_name.strip())) out_file.write('}\n') out_file.close()
91e4fc0400218814a82ec4e55e025ed18b21d59f
[ "Python" ]
1
Python
jakeaglass/SwiftScripting
0e66879bca8b623ab369d4dfab0529eab511ca57
599f12f340ce434c42cab5a611f049f9a2da3b6d
refs/heads/main
<file_sep># sensitive-words-filter-service 一个简单的基于DFA算法和Http的敏感词过滤服务; TODO - [ ] 词库文件发生变更后能自动加载 - [ ] 支持从数据库加载词库 - [ ] 支持客户端自定义需要检测哪个词库 - [ ] 更加丰富的API接口 ## Usage ```bash go mod tidy && go build ``` 启动 ```bash ./sensitive-words-match -p 8088 -d ./data/ ``` 启动参数说明: -p 指定http服务的端口; -d 敏感词存储的路径,路径下所有的文件会自动遍历加载到内存,不支持二级目录; http api /words/filter client post 请求: ```json { "text": "xdcvdfdsf fuck" } ``` 正常请求返回: ```json { "code":200, "msg":"success", "data":{ "suggestion":"pass", "desensitization":"Hello world, 世界你好" } } ``` curl Request demo ```bash curl --location --request POST 'http://127.0.0.1:8088/words/filter' --header 'Content-Type: application/json' --data-raw '{ "text": "GOODO fxxk," }' ``` 包含敏感词的请求返回 ```json { "code": 200, "msg": "success", "data": { "suggestion": "block", "sensitiveWords": [ "fuck" ], "desensitization": "GOODO ****,。" } } ``` 执行显示 ![image](https://user-images.githubusercontent.com/90187291/133043656-3a75fdc2-5193-438d-937e-b37f235662c1.png) <file_sep>module sensitive-words-match go 1.16 require ( github.com/gin-gonic/gin v1.7.4 github.com/golang/protobuf v1.5.2 // indirect github.com/sirupsen/logrus v1.8.1 github.com/stretchr/testify v1.5.1 // indirect golang.org/x/sys v0.0.0-20210423082822-04245dca01da // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) <file_sep>package main import ( log "github.com/sirupsen/logrus" "os" "path/filepath" ) type Matcher interface { //Build build Matcher Build(words []string) //Match return match sensitive words Match(text string) ([]string, string) } var ( GMatchService = NewMatchService(NewDFAMather()) ) type MatchService struct { dictDir string matcher Matcher } func NewMatchService(matcher Matcher) *MatchService { return &MatchService{ matcher: matcher, } } func (m *MatchService) Init(dictPath string) error { m.dictDir = dictPath var files []string //只关注rootDir下面的文件,暂时不支持子文件夹的形式 err := filepath.Walk(m.dictDir, func(path string, info os.FileInfo, err error) error { if err != nil { log.Warnf("load %s fail %s", m.dictDir, err.Error()) return nil } if !info.IsDir() { files = append(files, info.Name()) } return nil }) if err != nil { return err } var words []string for _, file := range files { if w, err := readWordsFromFile(m.dictDir + "/" + file); err == nil { log.Infof("load senvitive files %s words size %d", m.dictDir+"/"+file, len(w)) words = append(words, w...) } else { return err } } m.matcher.Build(words) return nil } func (m *MatchService) Match(text string) ([]string, string) { return m.matcher.Match(text) } <file_sep>package main type DFAMatcher struct { replaceChar rune root *Node } //最长匹配: 你好,你好啊,优先匹配你好啊,如果没有你好啊,那么匹配你好 type Node struct { End bool Next map[rune]*Node } func (n *Node) AddWord(word string) { node := n chars := []rune(word) for index, _ := range chars { node = node.AddChild(chars[index]) } node.End = true } func (n *Node) AddChild(c rune) *Node { if n.Next == nil { n.Next = make(map[rune]*Node) } //如果已经存在了,就不再往里面添加了; if next, ok := n.Next[c]; ok { return next } else { n.Next[c] = &Node{ End: false, Next: nil, } return n.Next[c] } } func (n *Node) FindChild(c rune) *Node { if n.Next == nil { return nil } if _, ok := n.Next[c]; ok { return n.Next[c] } return nil } func NewDFAMather() *DFAMatcher { return &DFAMatcher{ root: &Node{ End: false, }, } } func (d *DFAMatcher) Build(words []string) { for _, item := range words { d.root.AddWord(item) } } //Match 查找替换发现的敏感词 func (d *DFAMatcher) Match(text string) (sensitiveWords []string, replaceText string) { if d.root == nil { return nil, text } textChars := []rune(text) textCharsCopy := make([]rune, len(textChars)) copy(textCharsCopy, textChars) length := len(textChars) for i := 0; i < length; i++ { //root本身是没有key的,root的下面一个节点,才算是第一个; temp := d.root.FindChild(textChars[i]) if temp == nil { continue } j := i + 1 for ; j < length && temp != nil; j++ { if temp.End { sensitiveWords = append(sensitiveWords, string(textChars[i:j])) replaceRune(textCharsCopy, '*', i, j) } temp = temp.FindChild(textChars[j]) } if j == length && temp != nil && temp.End { sensitiveWords = append(sensitiveWords, string(textChars[i:length])) replaceRune(textCharsCopy, '*', i, length) } } return sensitiveWords, string(textCharsCopy) } func replaceRune(chars []rune, replaceChar rune, begin int, end int) { for i := begin; i < end; i++ { chars[i] = replaceChar } } <file_sep>package main import ( "flag" "fmt" "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" "os" ) var ( VERSION = 0.1 port = flag.Int("p", 8088, "http server port") dictDir = flag.String("d", "./data", "sensitive words file path") ) func main() { if len(os.Args) > 1 { if os.Args[1] == "-v" || os.Args[1] == "--version" { fmt.Println("version: ", VERSION) os.Exit(0) } if os.Args[1] == "-h" || os.Args[1] == "--help" { flag.Usage() os.Exit(0) } } log.SetOutput(os.Stdout) gin.SetMode(gin.ReleaseMode) log.Info("Use sensitive words DIR ", *dictDir) if err := GMatchService.Init(*dictDir); err != nil { log.Warningf("Service start fail %s", err.Error()) return } httpServerRun(*port) }
59330ae5a64284ac05f9935da7d5a28c8ac8bc13
[ "Markdown", "Go Module", "Go" ]
5
Markdown
xwinie/sensitive-words-filter-service
292104c429892acd49efd590232659eb78dc4737
8101d8be2c82d8e54ceb465ad4bf2d11fb15c50e
HEAD
<file_sep>#include <string> #include <vector> #include <iostream> #include <codecvt> #include <fstream> #include <set> #include <locale> #include <boost/filesystem.hpp> #include <util/filesystem.hpp> #include "notebook.hpp" #include "util/stream_operations.hpp" #include "global.hpp" namespace { using utf_converter = std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>; data::notebook_data load(const boost::filesystem::path&); uint32_t load_id(const boost::filesystem::path&); inline data::notebook_data load(const boost::filesystem::path& p) { std::ifstream in{p.string().c_str(), std::ios::binary}; data::notebook_data notebook; if(in.good()) in>> notebook; in.close(); return notebook; } inline uint32_t load_id(const boost::filesystem::path& p) { using utility::in_mem; std::ifstream in{p.string().c_str(), std::ios::binary}; uint32_t id{data::notebook_data::NO_ID}; if(in.good()) { in_mem(in, id); } in.close(); return id; } /** * Filters a string for use as a filename */ inline std::wstring filter_name(const std::wstring& s) { std::wstring news{s}; for(std::wstring::iterator it{news.begin()}; it != news.end(); ++it) { if(std::string{global::letters}.find(*it) == std::string::npos) { *it = '_'; } } return news; } } //note_data member functions: namespace data { bool note_data::operator==(const note_data& n) const { return ((this->name == n.name) && (this->note == n.note) && (this->timestamp == n.timestamp)); } bool note_data::operator!=(const note_data& n) const { return ((this->name != n.name) || (this->note != n.note) || (this->timestamp != n.timestamp)); } //a less-than operator for sorting bool note_data::operator<(const note_data& n) const { return (n.timestamp < this->timestamp); } } //notebook_data member functions: namespace data { bool notebook_data::operator==(const notebook_data& n) const { return ((this->name == n.name) && (this->notes == n.notes)); } bool notebook_data::operator!=(const notebook_data& n) const { return ((this->name != n.name) || (this->notes != n.notes)); } } namespace data { std::istream& operator>>(std::istream& in, note_data& note) { using utility::read_string; note = note_data{L"", L"", tdata::time_class{tdata::current_time()}}; utf_converter convert; std::string temps; in.peek(); if(in.good()) { in>> note.timestamp; read_string(in, temps); note.name = convert.from_bytes(temps); read_string(in, temps); note.note = convert.from_bytes(temps); } return in; } std::ostream& operator<<(std::ostream& out, const note_data& note) { using utility::write_string; utf_converter convert; if(out.good()) { out<< note.timestamp; write_string(write_string(out, convert.to_bytes(note.name)), convert.to_bytes(note.note)); } return out; } std::istream& operator>>(std::istream& in, notebook_data& notebook) { using utility::read_string; using utility::read_vector; using utility::in_mem; notebook = notebook_data{}; utf_converter convert; std::string temps; in.peek(); if(in.good()) { in_mem(in, notebook.id); read_vector<note_data>(in, notebook.notes); read_string(in, temps); notebook.name = convert.from_bytes(temps); } return in; } std::ostream& operator<<(std::ostream& out, const notebook_data& notebook) { using utility::write_string; using utility::write_vector; using utility::out_mem; utf_converter convert; if(out.good()) { out_mem(out, notebook.id); write_vector<note_data>(out, notebook.notes); write_string(out, convert.to_bytes(notebook.name)); } return out; } } namespace data { //file loading functions: namespace file { using boost::filesystem::path; /** * @brief load_notebooks Simply loads notebooks from a folder. * @param folder The folder to search for notebook files in. * @return A list of notebooks that were loaded. */ std::vector<notebook_data> load_notebooks(const path& folder) { using boost::filesystem::is_regular_file; using boost::filesystem::is_directory; using boost::filesystem::is_symlink; using filesystem::glob; using boost::filesystem::path; std::vector<notebook_data> notebooks; if(!is_directory(folder) || is_symlink(folder)) return notebooks; for(glob it{folder, utf_converter{}.to_bytes(notebook_data::FILE_REGEX)}; !it.end(); ++it) { if(is_regular_file(it->path())) { notebooks.push_back(load(it->path())); if(notebooks.back().id == notebook_data::NO_ID) //notebooks HAVE to have an id! { throw std::runtime_error{"std::vector<notebook_d\ ata> load_notebooks(const std::string& folder): ERROR: could not load a notebook!\nfile: \"" + it->path().string() +"\""}; } } } return notebooks; } /** * @brief save Saves a notebook. It assigns a new id if one has not already been assigned. * This function does not create the folder it saves the notebook in. * @param folder The folder to save the notebook in. * @return True if successful. False is returned if the folder doesn't exist, * or the notebook couldn't be saved for some reason. */ bool save(notebook_data& notebook, const path& folder) { using filesystem::glob; using boost::filesystem::is_directory; using boost::filesystem::is_symlink; using boost::filesystem::is_regular_file; using boost::filesystem::exists; if(is_symlink(folder)) return false; std::string f; if(!is_directory(folder)) boost::filesystem::create_directories(folder); //assign a new id to the notebook if one has note been already. if(notebook.id == notebook_data::NO_ID) { auto ids = notebook_ids(folder); while(ids.find(++notebook.id) != ids.end()); } //find its file: for(glob it{folder, utf_converter{}.to_bytes(notebook_data::FILE_REGEX)}; (!it.end() && (f == "")); ++it) { if(is_regular_file(it->path()) && (load_id(it->path()) == notebook.id)) { f = it->path().string(); } } if(!exists(f)) { f = (folder / path{(std::to_string(notebook.id) + utf_converter{}.to_bytes(filter_name(notebook.name)) + utf_converter{}.to_bytes(notebook_data::FILE_EXTENSION))}).string(); } std::ofstream out{f, std::ios::binary}; out<< notebook; out.close(); return true; } /** * @brief remove_notebook removes a notebook of the specified id. * @param folder The folder to search in. * @param id The id of the notebook that is to be deleted. * @return true if no file exists with an id that matches the notebook's. */ bool remove_notebook(const uint32_t& id, const path& folder) { using filesystem::glob; using boost::filesystem::remove; using boost::filesystem::is_regular_file; using boost::filesystem::is_directory; using boost::filesystem::is_symlink; if(!is_directory(folder) || is_symlink(folder)) return true; for(glob it{folder, utf_converter{}.to_bytes(notebook_data::FILE_REGEX)}; !it.end(); ++it) { if(is_regular_file(it->path())) { if(load_id(it->path()) == id) { remove(it->path()); return !exists(it->path()); } } } return true; } /** * @brief notebook_ids efficiently loads the notebook ids. * @param folder the folder to search in. * @return a set that can be referenced for notebook ids. */ std::set<uint32_t> notebook_ids(const path& folder) { using filesystem::glob; using boost::filesystem::is_regular_file; using boost::filesystem::is_directory; using boost::filesystem::is_symlink; std::set<uint32_t> ids; if(!is_directory(folder) || is_symlink(folder)) return ids; for(glob it{folder, utf_converter{}.to_bytes(notebook_data::FILE_REGEX)}; !it.end(); ++it) { if(is_regular_file(it->path())) { ids.insert(load_id(it->path())); } } return ids; } } } <file_sep>#include <boost/filesystem.hpp> #include <QDir> #include "global.hpp" #include "mainwindow.h" #include "build.hpp" namespace global { MainWindow *main_window{nullptr}; //root directory: "~/.notebook program" const boost::filesystem::path root{ boost::filesystem::path{QDir::homePath().toStdWString()} / boost::filesystem::path{".notebook program"}}; } <file_sep>#include <vector> #include <memory> #include <QWidget> #include <QString> #include <string> #include <codecvt> #include <locale> #include <boost/filesystem.hpp> #include <QMessageBox> #include <iostream> #include "managenotebooks.h" #include "ui_managenotebooks.h" #include "widgets/notebooktab.h" #include "data/notebook.hpp" #include "data/global.hpp" namespace { using utf_converter = std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>; } ManageNotebooks::ManageNotebooks(QWidget *parent) : QWidget{parent}, ui{new Ui::ManageNotebooks}, tabs{} { this->init(); } /** * @brief ManageNotebooks::ManageNotebooks Constructs the widget and shows * the tab of the specified notebook. * @param par parent widget * @param id the id of the notebook that is to be shown. */ ManageNotebooks::ManageNotebooks(const uint32_t& id, QWidget *par) : QWidget{par}, ui{new Ui::ManageNotebooks}, tabs{} { using std::cout; using std::endl; this->init(); for(std::size_t x{0}; x < (unsigned)this->ui->notebook_tab->count(); ++x) { if(this->tabs[x]->notebook.id == id) { this->ui->notebook_tab->setCurrentWidget(this->tabs[x].get()); } } } ManageNotebooks::~ManageNotebooks() { if(global::main_window) global::main_window->enable_menu_bar(false); delete ui; } void ManageNotebooks::createNewNotebook() { if(!this->ui->notebook_tab->isEnabled()) { this->ui->notebook_tab->setEnabled(true); } std::shared_ptr<NotebookTab> tab{std::make_shared<NotebookTab>(this->ui->notebook_tab)}; this->set_tab_functors(*tab); this->tabs.push_back(tab); this->ui->notebook_tab->addTab(tab.get(), QString::fromStdWString(tab->notebook.name)); this->ui->notebook_tab->setCurrentIndex(this->ui->notebook_tab->count() - 1); } void ManageNotebooks::set_tab_functors(NotebookTab& tab) { tab.change_tabname = [=](const std::wstring& name)->void{ this->ui->notebook_tab->setTabText(this->ui->notebook_tab->currentIndex(), QString::fromStdWString(name)); }; tab.remove_notebook = [=]()->void{ unsigned int index{(unsigned)this->ui->notebook_tab->currentIndex()}; if(data::file::remove_notebook(this->tabs[index]->notebook.id)) { this->ui->notebook_tab->removeTab(index); this->tabs.erase((this->tabs.begin() + index)); if(this->ui->notebook_tab->count() == 0) { this->ui->notebook_tab->setEnabled(false); } } else { QMessageBox::information(this, "ERROR", "Failed to remove notebook."); } }; } void ManageNotebooks::init() { std::shared_ptr<NotebookTab> temptab; std::vector<data::notebook_data> notebooks{data::file::load_notebooks()}; this->ui->setupUi(this); global::main_window->showMaximized(); this->ui->notebook_tab->setEnabled(false); this->ui->notebook_tab->clear(); this->tabs.erase(this->tabs.begin(), this->tabs.end()); if(!notebooks.empty()) { this->ui->notebook_tab->setEnabled(true); for(std::size_t x{0}; x< notebooks.size(); ++x) { temptab = std::make_shared<NotebookTab>(this->ui->notebook_tab, notebooks[x]); this->set_tab_functors(*temptab); this->tabs.push_back(temptab); this->ui->notebook_tab->addTab(temptab.get(), QString::fromStdWString(temptab->notebook.name)); } } global::main_window->enable_menu_bar(true); } <file_sep>#include <QMenu> #include <QMessageBox> #include <QKeySequence> #include "mainwindow.h" #include "ui_mainwindow.h" #include "widgets/main_window_widgets/managenotebooks.h" #include "data/global.hpp" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui{new Ui::MainWindow}, allow_menubar_change{true} { this->ui->setupUi(this); global::main_window = this; this->setCentralWidget(new ManageNotebooks{this}); } MainWindow::~MainWindow() { this->allow_menubar_change = false; delete ui; } void MainWindow::enable_menu_bar(const bool& b) { if(!this->allow_menubar_change) return; if(b) { QMenuBar *bar{new QMenuBar}; { QMenu *menu{new QMenu{"File"}}; menu->addAction("Exit", this, &MainWindow::exit, QKeySequence{Qt::Key_Escape}); bar->addMenu(menu); } this->setMenuBar(bar); } else { this->setMenuBar(nullptr); } } void MainWindow::exit() { this->setEnabled(false); auto answer = QMessageBox::question(this, "Are you sure?", "Do you really want to exit?"); this->setEnabled(true); if(answer == QMessageBox::Yes) { this->close(); } } <file_sep>#ifndef MANAGENOTEBOOKS_H #define MANAGENOTEBOOKS_H #include <QWidget> #include <vector> #include <memory> #include "widgets/notebooktab.h" namespace Ui { class ManageNotebooks; } class ManageNotebooks : public QWidget { Q_OBJECT public: explicit ManageNotebooks(QWidget *parent = 0); explicit ManageNotebooks( const uint32_t&, QWidget* = nullptr); ~ManageNotebooks(); public slots: void createNewNotebook(); private: Ui::ManageNotebooks *ui; std::vector<std::shared_ptr<NotebookTab> > tabs; void set_tab_functors(NotebookTab&); void init(); }; #endif // MANAGENOTEBOOKS_H <file_sep>#include <ctime> #include <chrono> #include <iostream> #include <cstring> #include <string> #include <utility> #include <vector> #include "time_class.hpp" namespace { std::vector<unsigned short> month_days(const unsigned int&); unsigned int total_days_in_m(const int&, const int&); std::vector<std::string> day_names(); std::vector<std::string> month_names(); int find_month_of_yday(const int&, const int&); inline std::vector<unsigned short> month_days(const unsigned int& year) { return std::vector<unsigned short>({ 31, (__isleap(year) ? (unsigned short)29 : (unsigned short)28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}); } inline unsigned int total_days_in_m(const int& m, const int& year) { unsigned int days(0); for(int x = 0, month = 0; x < (m + 1); x++, (month = ((month + 1) % 12))) { days += month_days(year)[month]; } return days; } inline std::vector<std::string> day_names() { return std::vector<std::string>({ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}); } inline std::vector<std::string> month_names() { return std::vector<std::string>({ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}); } inline int find_month_of_yday(const int& day, const int& year) { int month(0); for(month = 0; ((month < 12) && ((signed)total_days_in_m(month, year) <= day)); month++); return month; } } namespace tdata { namespace util { /** * @return a structure that uses fixed-width data types * that will be the same size across operating systems; */ struct fixed_size_tm to_fixed_tm(const struct tm& t) { return fixed_size_tm{ t.tm_sec, t.tm_min, t.tm_hour, t.tm_mday, t.tm_mon, t.tm_year, t.tm_wday, t.tm_yday, t.tm_isdst}; } struct tm from_fixed_tm(const struct fixed_size_tm& t) { struct tm tempt{current_time()}; return tm{ t.sec, t.min, t.hour, t.mday, t.mon, t.year, t.wday, t.yday, t.isdst, tempt.tm_gmtoff, tempt.tm_zone }; } } } /** Stream operators: */ namespace tdata { const time_point& tmtotp(struct tm& t, time_point& tempt) { tempt = std::chrono::system_clock::from_time_t(mktime(&t)); return tempt; } const struct tm& tptotm(time_point& t, struct tm& tempt) { time_t lvalue_timet(std::chrono::system_clock::to_time_t(t)); tempt = (*localtime(&lvalue_timet)); return tempt; } std::istream& operator>>(std::istream& in, time_class& t) { using tdata::util::fixed_size_tm; using tdata::util::from_fixed_tm; char *ch(new char[sizeof(struct fixed_size_tm)]); in.peek(); if(in.good()) { for(unsigned int x = 0; ((x < sizeof(struct fixed_size_tm)) && in.good()); x++) ch[x] = in.get(); if(in.good()) { fixed_size_tm ftm; std::memcpy(&ftm, ch, sizeof(struct fixed_size_tm)); t.cur_time = from_fixed_tm(ftm); } in.peek(); } delete[] ch; return in; } std::ostream& operator<<(std::ostream& out, const time_class& t) { using tdata::util::fixed_size_tm; using tdata::util::to_fixed_tm; char *ch(new char[sizeof(struct fixed_size_tm)]); if(out.good()) { fixed_size_tm ftm{to_fixed_tm(t.cur_time)}; std::memcpy(ch, &ftm, sizeof(struct fixed_size_tm)); for(unsigned int x = 0; x < sizeof(struct fixed_size_tm); x++) out<< ch[x]; } delete[] ch; return out; } } /** Time_class member functions: */ namespace tdata { time_class::time_class(const time_class& t) noexcept : cur_time(t.cur_time) { } time_class::time_class(time_class&& t) noexcept : cur_time(std::move(t.cur_time)) { } time_class::time_class(const struct tm& t) : cur_time(t) { } time_class::time_class() : cur_time(current_time()) { } time_class::~time_class() { } const struct tm& time_class::value() const { return this->cur_time; } time_class& time_class::operator=(const time_class& t) { if(this != &t) { std::memcpy(&(this->cur_time), &t, sizeof(t)); } return *this; } time_class& time_class::operator=(time_class&& t) noexcept { this->cur_time = std::move(t.cur_time); return *this; } time_class& time_class::operator=(const struct tm& t) { if(&(this->cur_time) != (&t)) { std::memcpy(&(this->cur_time), &t, sizeof(t)); } return *this; } bool time_class::operator==(const time_class& t) const { return ((this->cur_time.tm_sec == t.cur_time.tm_sec) && (this->cur_time.tm_min == t.cur_time.tm_min) && (this->cur_time.tm_hour == t.cur_time.tm_hour) && (this->cur_time.tm_mday == t.cur_time.tm_mday) && (this->cur_time.tm_wday == t.cur_time.tm_wday) && (this->cur_time.tm_yday == t.cur_time.tm_yday) && (this->cur_time.tm_mon == t.cur_time.tm_mon) && (this->cur_time.tm_year == t.cur_time.tm_year) && (std::strcmp(this->cur_time.tm_zone, t.cur_time.tm_zone) == 0) && (this->cur_time.tm_isdst == t.cur_time.tm_isdst)); } bool time_class::operator!=(const time_class& t) const { return ((this->cur_time.tm_sec != t.cur_time.tm_sec) || (this->cur_time.tm_min != t.cur_time.tm_min) || (this->cur_time.tm_hour != t.cur_time.tm_hour) || (this->cur_time.tm_mday != t.cur_time.tm_mday) || (this->cur_time.tm_wday != t.cur_time.tm_wday) || (this->cur_time.tm_yday != t.cur_time.tm_yday) || (this->cur_time.tm_mon != t.cur_time.tm_mon) || (this->cur_time.tm_year != t.cur_time.tm_year) || (std::strcmp(this->cur_time.tm_zone, t.cur_time.tm_zone) != 0) || (this->cur_time.tm_isdst != t.cur_time.tm_isdst)); } bool time_class::operator<(const time_class& t) const { if(this->cur_time.tm_year < t.cur_time.tm_year) return true; else if(this->cur_time.tm_year == t.cur_time.tm_year) { if(this->cur_time.tm_yday < t.cur_time.tm_yday) return true; else if(this->cur_time.tm_yday == t.cur_time.tm_yday) { if(this->cur_time.tm_hour < t.cur_time.tm_hour) return true; else if(this->cur_time.tm_hour == t.cur_time.tm_hour) { if(this->cur_time.tm_min < t.cur_time.tm_min) return true; else if(this->cur_time.tm_min == t.cur_time.tm_min) { if(this->cur_time.tm_sec < t.cur_time.tm_sec) return true; } } } } return false; } bool time_class::operator<=(const time_class& t) const { return (this->operator<(t) || this->operator==(t)); } bool time_class::operator>(const time_class& t) const { return !this->operator<=(t); } bool time_class::operator>=(const time_class& t) const { return !(this->operator<(t)); } /** Adds 1 second to the time. */ const time_class& time_class::operator++() { this->cur_time.tm_sec++; if(this->cur_time.tm_sec > 59) { this->cur_time.tm_sec = 0; this->cur_time.tm_min++; if(this->cur_time.tm_min > 59) { this->cur_time.tm_min = 0; this->cur_time.tm_hour++; if(this->cur_time.tm_hour > 23) { this->cur_time.tm_hour = 0; this->add_day(); } } } return *this; } /** Adds (i) seconds to the time. Optimizations are in place * so that if (i) represents a value that can be calculated in * days, there won't be any significant CPU Overhead. */ time_class time_class::operator+(int i) const { using namespace t_const; time_class tempt(*this); if(i >= (signed)day) { for(int x = 0; x < (i / (signed)day); x++) tempt.add_day(); i %= day; } if(i < 0) for(int x = 0; x < (i * (-1)); x++) --tempt; else if(i > 0) for(int x = 0; x < i; x++) ++tempt; return tempt; } const time_class& time_class::operator+=(int i) { (*this) = ((*this) + i); return *this; } const time_class& time_class::operator--() { if(this->cur_time.tm_sec == 0) { this->cur_time.tm_sec = 59; if(this->cur_time.tm_min == 0) { this->cur_time.tm_min = 59; if(this->cur_time.tm_hour == 0) { this->cur_time.tm_hour = 23; this->subtract_day(); } else if(this->cur_time.tm_hour > 0) this->cur_time.tm_hour--; } else if(this->cur_time.tm_min > 0) this->cur_time.tm_min--; } else if(this->cur_time.tm_sec > 0) this->cur_time.tm_sec--; return *this; } /** Subtracts (i) seconds to the time. Optimizations are in place * so that if (i) represents a value that can be calculated in * days, there won't be any significant CPU Overhead. */ time_class time_class::operator-(int i) const { using namespace t_const; time_class tempt(*this); if(i >= (signed)day) { for(int x = 0; x < (i / (signed)day); x++) tempt.subtract_day(); i %= day; } if(i < 0) for(int x = 0; x < (i * (-1)); x++) ++tempt; else if(i > 0) for(int x = 0; x < i; x++) --tempt; return tempt; } const time_class& time_class::operator-=(int i) { (*this) = ((*this) - i); return *this; } int& time_class::second() { return this->cur_time.tm_sec; } int& time_class::minute() { return this->cur_time.tm_min; } /* Hour in military format */ int& time_class::mhour() { return this->cur_time.tm_hour; } int& time_class::month() { return this->cur_time.tm_mon; } int& time_class::wday() { return this->cur_time.tm_wday; } /* Hour in 12-hour format */ int time_class::hour() const { int tempi(this->cur_time.tm_hour % 12); if(tempi == 0) tempi = 12; return tempi; } bool time_class::am() const { return (this->cur_time.tm_hour < 12); } int time_class::gyear() const { return (this->cur_time.tm_year + 1900); } void time_class::syear(const int& i) { using namespace t_const; int tempyday(this->cur_time.tm_yday), target(i - 1900); if(__isleap((this->cur_time.tm_year + 1900)) && (tempyday == 365)) { tempyday--; (*this) = this->operator-(day); } if(target < this->cur_time.tm_year) { while(target < this->cur_time.tm_year) (*this) = this->operator-(day); } else if(target > this->cur_time.tm_year) { while(target > this->cur_time.tm_year) (*this) = this->operator+(day); } while(this->cur_time.tm_yday != 0) (*this) = this->operator-(day); while(this->cur_time.tm_yday != tempyday) (*this) = this->operator+(day); } /* Syncs the month and month day to the day of the year. This allows * us to simply do math with yday, and then "sync" the month and day of * month to the yday. */ void time_class::sync_to_yday() { this->cur_time.tm_mon = find_month_of_yday(this->cur_time.tm_yday, (this->cur_time.tm_year + 1900)); if(this->cur_time.tm_mon == 0) { this->cur_time.tm_mday = (this->cur_time.tm_yday + 1); } else { this->cur_time.tm_mday = ((this->cur_time.tm_yday + 1) - total_days_in_m((this->cur_time.tm_mon - 1), (this->cur_time.tm_year + 1900))); } } std::string time_class::month_name() const { return month_names().at(this->cur_time.tm_mon); } std::string time_class::wday_name() const { return day_names().at(this->cur_time.tm_wday); } const int& time_class::second() const { return this->cur_time.tm_sec; } const int& time_class::mhour() const { return this->cur_time.tm_hour; } const int& time_class::minute() const { return this->cur_time.tm_min; } const int& time_class::month() const { return this->cur_time.tm_mon; } const int& time_class::wday() const { return this->cur_time.tm_wday; } int& time_class::mday() { return this->cur_time.tm_mday; } const int& time_class::mday() const { return this->cur_time.tm_mday; } void time_class::subtract_day() { if(this->cur_time.tm_wday == 0) this->cur_time.tm_wday = 6; else this->cur_time.tm_wday--; if(this->cur_time.tm_yday == 0) { this->cur_time.tm_year--; this->cur_time.tm_yday = (__isleap((this->cur_time.tm_year + 1900)) ? 365 : 364); } else if(this->cur_time.tm_yday > 0) this->cur_time.tm_yday--; this->sync_to_yday(); } void time_class::add_day() { this->cur_time.tm_wday++; this->cur_time.tm_wday %= 7; this->cur_time.tm_yday++; if(this->cur_time.tm_yday > (__isleap((this->cur_time.tm_year + 1900)) ? 365 : 364)) { this->cur_time.tm_yday = 0; this->cur_time.tm_year++; } this->sync_to_yday(); } int& time_class::yday() { return this->cur_time.tm_yday; } const int& time_class::yday() const { return this->cur_time.tm_yday; } void time_class::smonth(const int& x) { int tempi(x); auto add_month = [](time_class& t)->void { using namespace tdata::t_const; using tdata::days_in_month; int mday(t.mday()); if(mday > days_in_month(((t.month() + 1) % 12), t.gyear())) { mday %= days_in_month(((t.month() + 1) % 12), t.gyear()); } if(t.mday() == 1) t += day; while(t.mday() != 1) t += day; while(t.mday() != mday) t += day; }; auto subtract_month = [](time_class& t)->void { using namespace tdata::t_const; using tdata::days_in_month; int mday(t.mday()); if(mday > days_in_month(((t.month() + 11) % 12), t.gyear())) { mday %= days_in_month(((t.month() + 11) % 12), t.gyear()); } while(t.mday() != 1) t -= day; t -= day; while(t.mday() != mday) t -= day; }; if(tempi < 0) { this->syear(this->gyear() - 1); tempi = 11; } else if(tempi > 11) { this->syear(this->gyear() + 1); tempi = 0; } while(this->cur_time.tm_mon != 0) subtract_month(*this); while(this->cur_time.tm_mon != tempi) add_month(*this); } } /** misc functions: */ namespace tdata { struct tm current_time() { time_point now(std::chrono::system_clock::now()); struct tm temptm; tptotm(now, temptm); return temptm; } int days_in_month(const int& month, const int& year) { if((month < 0) || (month > 11)) return 0; return month_days(year).at(month); } } <file_sep>#ifndef DATA_GLOBAL_HPP_INCLUDED #define DATA_GLOBAL_HPP_INCLUDED #include <memory> #include <boost/filesystem.hpp> #include "mainwindow.h" namespace global { //some global constant literals: constexpr const char* const letters{"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"}; constexpr const char* const numbers{"1234567890"}; constexpr const char* const specials{"`~!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/? \t"}; constexpr const char* const chars{"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890`~!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/? \t"}; //some constant globals: extern const boost::filesystem::path root; //the root folder the program saves data in //some global variables: extern MainWindow *main_window; } #endif <file_sep>#ifndef NOTEBOOKTAB_H #define NOTEBOOKTAB_H #include <QWidget> #include <QModelIndex> #include <vector> #include <string> #include <functional> #include <QKeyEvent> #include "data/notebook.hpp" namespace Ui { class NotebookTab; } class NotebookTab : public QWidget { Q_OBJECT public: explicit NotebookTab(QWidget* = 0, const data::notebook_data& = data::notebook_data{}); ~NotebookTab(); data::notebook_data notebook; std::function<void(const std::wstring&)> change_tabname; std::function<void()> remove_notebook; public slots: void enableSaveButton(); void updateTabName(); void removeNotebook(); void save(); void newNote(); void editNote(QModelIndex); void deleteNote(); void updateDeleteButton(); private: Ui::NotebookTab *ui; }; #endif // NOTEBOOKTAB_H <file_sep>#ifndef EDITNOTE_H #define EDITNOTE_H #include <QWidget> #include <QMenu> #include <QString> #include "data/notebook.hpp" namespace Ui { class EditNote; } class EditNote : public QWidget { Q_OBJECT public: explicit EditNote(QWidget*, const data::notebook_data&, const unsigned int& = -1); ~EditNote(); public slots: void save(); void finished(); void setFontBold(bool); void userManualFontSize(QString); void updateStyleButtons(); private: Ui::EditNote *ui; data::notebook_data notebook; unsigned int note_index; QMenu menu; Qt::WindowFlags window_flags; }; #endif // EDITNOTE_H <file_sep>#ifndef UTILITY_STREAM_OPERATIONS_HPP_INCLUDED #define UTILITY_STREAM_OPERATIONS_HPP_INCLUDED #include <string> #include <iostream> #include <vector> #include <sstream> #include <cstdint> #include <cstring> namespace utility { std::string peek_string(std::istream&, const unsigned int&); std::ostream& write_string(std::ostream&, const std::string&); std::istream& read_string(std::istream&, std::string&); namespace { template<class type> bool safe_getline(std::istream&, type&, const char&); template<> bool safe_getline<std::string>(std::istream&, std::string&, const char&); template<typename type> std::istream& in_mem(std::istream&, type&); template<typename type> std::ostream& out_mem(std::ostream&, const type&); template<typename type> std::ostream& write_vector(std::ostream&, const std::vector<type>&); template<typename type> std::istream& read_vector(std::istream&, std::vector<type>&); /** * @brief Safely retrieves a line from a file given a specified delimiter. * In case of failure, it will leave the stream in the state it was in * before the function call. Returns true/false based on success. * @param in std::istream to read from * @param t object to read into * @param delimiter delimiter to read to * @return bool true if the read was a success, false otherwise. */ template<class type> bool safe_getline(std::istream& in, type& t, const char& delimiter) { std::string temps; bool success(false); std::istream::pos_type previous_position(in.tellg()); t = type(); if(in.good()) { std::getline(in, temps, delimiter); if(in.good()) { std::stringstream ss; ss<< temps; ss>> t; success = true; } else if(!in.eof() && in.fail()) { /* So, here we are: we didn't reach the end of the file, but somwhere there was a big mistake... the program will now attempt to salvage the situation: */ in.seekg(previous_position); success = false; } } return success; } /** * @brief A specialization of safe_getline for strings. * @param in std::istream to read from * @param s the string to read into * @param delimiter the delimiter to read up to. * @return a bool: true if the read was a success, false otherwise. */ template<> __attribute__((unused)) bool safe_getline<std::string>(std::istream& in, std::string& s, const char& delimiter) { bool success(false); std::istream::pos_type previous_position(in.tellg()); s.erase(); if(in.good()) { std::getline(in, s, delimiter); if(in.good()) success = true; else if(!in.eof() && in.fail()) { /* So, here we are: we didn't reach the end of the file, but somwhere there was a big mistake... the program will now attempt to salvage the situation: */ in.seekg(0, std::ios::beg); in.seekg(previous_position); success = false; } } return success; } /** * @brief reads memory of a type from a file. Fixed-width types are * strongly suggested for programs that need to be cross-compatible. */ template<typename type> std::istream& in_mem(std::istream& in, type& t) { t = type(); char *mem(new char[sizeof(type)]); in.peek(); if(in.good()) { unsigned int x(0); for(; ((x < sizeof(type)) && in.good()); ++x) { mem[x] = in.get(); } if(((x + 1) < sizeof(type)) && !in.fail()) { in.setstate(std::ios_base::failbit); } memcpy(&t, mem, sizeof(type)); } delete[] mem; return in; } /** * @brief Writes memory of a type to a file. Fixed-width types are * strongly suggested for programs that need to be cross-compatible. */ template<typename type> std::ostream& out_mem(std::ostream& out, const type& t) { char *mem(new char[sizeof(type)]); memcpy(mem, &t, sizeof(type)); if(out.good()) { unsigned int x(0); for(; ((x < sizeof(type)) && out.good()); ++x) { out<< mem[x]; } if(((x + 1) < sizeof(type)) && !out.fail()) out.setstate(std::ios_base::failbit); } delete[] mem; return out; } /** * @brief Writes a vector of type 'type' to a stream. Garunteed not to * cause delimiter collisions. Intended to use in operators. * @param out Stream to write to. * @param v The vector to write. * @return The stream. */ template<typename type> std::ostream& write_vector(std::ostream& out, const std::vector<type>& v) { if(out.good()) { { std::uint32_t sz((std::uint32_t)v.size()); out_mem<std::uint32_t>(out, sz); } for(unsigned int x(0); ((x < v.size()) && out.good()); ++x) { out<< v[x]; } } return out; } /** * @brief Reads a vector of type 'type' from a stream. Garunteed not to * cause delimiter collisions. Intended to use in operators. * @param in The stream to read from. * @param v The vector to store the data in. * @return The stream. */ template<typename type> std::istream& read_vector(std::istream& in, std::vector<type>& v) { v.erase(v.begin(), v.end()); in.peek(); if(in.good()) { std::uint32_t size(0); in_mem<std::uint32_t>(in, size); for(std::uint32_t x(0); ((x < size) && in.good() && (in.peek() != EOF)); ++x) { v.push_back(type()); in>> v.back(); if(in.fail() && !in.eof()) v.pop_back(); in.peek(); } in.peek(); } return in; } } } #endif<file_sep>#include <QMenu> #include <QMessageBox> #include <QTextDocument> #include <locale> #include <codecvt> #include <QString> #include <QKeySequence> #include <string> #include <sstream> #include "editnote.h" #include "ui_editnote.h" #include "data/notebook.hpp" #include "data/time_class.hpp" #include "data/global.hpp" #include "widgets/main_window_widgets/managenotebooks.h" namespace { using utf_converter = std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>; bool is_int(const std::string&); template<typename type> type from_string(const std::string&); inline bool is_int(const std::string& s) { if(s.empty()) return false; for(std::string::const_iterator it{s.begin()}; it != s.end(); ++it) { if(std::string{global::numbers}.find(*it) == std::string::npos) return false; } return true; } template<typename type> type from_string(const std::string& s) { std::stringstream ss; ss<< s; type t; ss>> t; return t; } } EditNote::EditNote(QWidget *parent, const data::notebook_data& nb, const unsigned int& ni) : QWidget{parent}, ui{new Ui::EditNote}, notebook{nb}, note_index{ni}, menu{}, window_flags{global::main_window->windowFlags()} { ui->setupUi(this); for(unsigned int x{0}; x < (unsigned)this->ui->fontsize_box->maxCount(); ++x) { this->ui->fontsize_box->addItem(QString::fromStdString(std::to_string(x))); } this->ui->fontsize_box->setCurrentIndex(12); this->menu.addAction("Save", this, &EditNote::save, QKeySequence{Qt::CTRL + Qt::Key_S}); this->menu.addAction("FINISHED", this, &EditNote::finished, Qt::Key_Escape); this->ui->menu_button->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); this->ui->menu_button->setMenu(&this->menu); global::main_window->setWindowFlags(Qt::Window | Qt::CustomizeWindowHint); global::main_window->showMaximized(); //the window disapears if this call isn't here... don't ask me why. if(this->note_index != (unsigned)-1) { this->ui->note_name->setText(QString::fromStdWString(this->notebook.notes[this->note_index].name)); this->ui->note_text->setHtml(QString::fromStdWString(this->notebook.notes[this->note_index].note)); } this->ui->bold_button->setShortcut(QKeySequence{Qt::CTRL + Qt::Key_B}); this->ui->italic_button->setShortcut(QKeySequence{Qt::CTRL + Qt::Key_I}); this->ui->underline_button->setShortcut(QKeySequence{Qt::CTRL + Qt::Key_U}); } EditNote::~EditNote() { delete ui; } void EditNote::save() { if(this->note_index == (unsigned)-1) { this->notebook.notes.push_back(data::note_data{L"", L"", tdata::time_class{tdata::current_time()}}); this->note_index = (this->notebook.notes.size() - 1); } data::note_data &note{this->notebook.notes[this->note_index]}; note.name = this->ui->note_name->text().toStdWString(); note.note = this->ui->note_text->toHtml().toStdWString(); if(!data::file::save(this->notebook)) { QMessageBox::information(this, "ERROR!", ("Failed to save the note named " + utf_converter{}.to_bytes(note.name) + "!").c_str()); } else { this->ui->note_name->setModified(false); this->ui->note_text->document()->setModified(false); } } void EditNote::finished() { if(this->ui->note_name->isModified() || this->ui->note_text->document()->isModified()) { global::main_window->setEnabled(false); auto answer = QMessageBox::question(this, "Save?", "You have modified the note since last you saved! \ Do you want to save before closing it?"); global::main_window->setEnabled(true); if(answer == QMessageBox::Yes) { this->save(); } } global::main_window->setWindowFlags(this->window_flags); global::main_window->setCentralWidget(new ManageNotebooks{this->notebook.id, global::main_window}); } void EditNote::setFontBold(bool b) { this->ui->note_text->setFontWeight((b ? QFont::Weight::Bold : QFont::Weight::Normal)); } void EditNote::userManualFontSize(QString s) { if(!is_int(s.toStdString())) { this->ui->fontsize_box->setEditText(this->ui->fontsize_box->itemText(this->ui->fontsize_box->currentIndex())); return; } this->ui->note_text->setFontPointSize(from_string<qreal>(s.toStdString())); } void EditNote::updateStyleButtons() { if(this->ui->note_text->textCursor().hasSelection()) return; if(this->ui->bold_button->isChecked() != (this->ui->note_text->fontWeight() == QFont::Bold)) { this->ui->bold_button->setChecked(this->ui->note_text->fontWeight() == QFont::Bold); } if(this->ui->italic_button->isChecked() != this->ui->note_text->fontItalic()) { this->ui->italic_button->setChecked(this->ui->note_text->fontItalic()); } if(this->ui->underline_button->isChecked() != this->ui->note_text->fontUnderline()) { this->ui->underline_button->setChecked(this->ui->note_text->fontUnderline()); } if(this->ui->note_text->currentFont() != this->ui->font_box->currentFont()) { this->ui->font_box->setCurrentFont(this->ui->note_text->currentFont()); } if(this->ui->note_text->fontPointSize() != from_string<qreal>(this->ui->fontsize_box->currentText().toStdString())) { this->ui->note_text->setFontPointSize(from_string<qreal>(this->ui->fontsize_box->currentText().toStdString())); } } <file_sep>#include <vector> #include <string> #include <QMessageBox> #include <QString> #include <codecvt> #include <locale> #include <QModelIndex> #include <stdexcept> #include <exception> #include <QKeyEvent> #include <algorithm> #include "notebooktab.h" #include "ui_notebooktab.h" #include "data/notebook.hpp" #include "data/global.hpp" #include "data/time_class.hpp" #include "widgets/main_window_widgets/editnote.h" namespace { using utf_converter = std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>; std::wstring note_label(const data::note_data&); std::wstring date_label(const tdata::time_class&); inline std::wstring date_label(const tdata::time_class& t) { return utf_converter{}.from_bytes(t.month_name() + " " + std::to_string(t.mday()) + ", " + std::to_string(t.gyear())); } inline std::wstring note_label(const data::note_data& note) { return (L"[" + date_label(note.timestamp) + L"]: " + note.name); } } NotebookTab::NotebookTab(QWidget* parent, const data::notebook_data& nb) : QWidget(parent), notebook{nb}, change_tabname{[](const std::wstring&)->void{}}, remove_notebook{[]()->void{}}, ui{new Ui::NotebookTab} { this->ui->setupUi(this); this->ui->notebook_name->setText(QString::fromStdWString(this->notebook.name)); std::sort(this->notebook.notes.begin(), this->notebook.notes.end()); for(std::size_t x{0}; x < this->notebook.notes.size(); ++x) { this->ui->note_list->addItem(QString::fromStdWString(note_label(this->notebook.notes[x]))); } this->ui->save_button->setEnabled(false); this->ui->delete_note_button->setShortcut(QKeySequence{Qt::Key_Delete}); this->ui->new_note_button->setShortcut(QKeySequence{Qt::CTRL + Qt::Key_N}); this->updateDeleteButton(); } NotebookTab::~NotebookTab() { delete ui; } void NotebookTab::enableSaveButton() { this->ui->save_button->setEnabled(true); } void NotebookTab::updateTabName() { this->change_tabname(this->ui->notebook_name->text().toStdWString()); } void NotebookTab::removeNotebook() { if(QMessageBox::question(this, "Delete?", QString::fromStdString("Do you want to delete " + utf_converter{}.to_bytes(this->notebook.name) + "?")) == QMessageBox::Yes) { this->remove_notebook(); } } void NotebookTab::save() { if(this->ui->save_button->isEnabled()) { this->ui->save_button->setEnabled(false); } this->notebook.name = this->ui->notebook_name->text().toStdWString(); if(!data::file::save(this->notebook)) { QMessageBox::information(this, "ERROR", QString::fromStdString("Failed to save notebook \"" + utf_converter{}.to_bytes(this->notebook.name) + "\"!")); } } void NotebookTab::newNote() { this->save(); global::main_window->setCentralWidget(new EditNote{global::main_window, this->notebook}); } void NotebookTab::editNote(QModelIndex x) { if(x.row() < 0) throw std::runtime_error{"editNote: index less than 0!"}; if((unsigned)x.row() < this->notebook.notes.size()) { global::main_window->setCentralWidget(new EditNote{global::main_window, this->notebook, (unsigned)x.row()}); } } void NotebookTab::deleteNote() { if(this->ui->note_list->count() > 0) { if(this->ui->note_list->selectedItems().size() == 1) { std::vector<data::note_data> &notes{this->notebook.notes}; if(QMessageBox::question(this, "ARE YOU SURE??", QString::fromStdWString(L"Do you really want to delete \"" + this->notebook.notes[this->ui->note_list->currentRow()].name + L"\"?")) == QMessageBox::Yes) { notes.erase(notes.begin() + this->ui->note_list->currentRow()); this->save(); delete this->ui->note_list->takeItem(this->ui->note_list->currentRow()); } } } } void NotebookTab::updateDeleteButton() { if(this->ui->delete_note_button->isEnabled() != (this->ui->note_list->selectedItems().size() == 1)) { this->ui->delete_note_button->setEnabled(this->ui->note_list->selectedItems().size() == 1); } } <file_sep>#ifndef TIME_CLASS_HPP_INCLUDED #define TIME_CLASS_HPP_INCLUDED #include <ctime> #include <iostream> #include <chrono> #include <unistd.h> namespace tdata { class time_class; //time constants: namespace t_const { constexpr long minute{60}; constexpr long hour{minute * 60}; constexpr long day{hour * 24}; constexpr long week{day * 7}; } namespace util { struct fixed_size_tm; struct fixed_size_tm to_fixed_tm(const struct tm&); struct tm from_fixed_tm(const struct fixed_size_tm&); struct fixed_size_tm { int32_t sec, min, hour, mday, mon, year, wday, yday, isdst; }; } using clock_type = std::chrono::system_clock; using time_point = std::chrono::time_point<clock_type>; struct tm current_time(); const time_point& tmtotp( struct tm&, time_point&); const struct tm& tptotm(time_point&, struct tm&); int days_in_month(const int&, const int&); std::istream& operator>>(std::istream&, time_class&); std::ostream& operator<<(std::ostream&, const time_class&); /** Time: The indefinite continued progress of existence and events in the past, * present, and future regarded as a whole. */ class time_class { public: time_class(const time_class&) noexcept; time_class(time_class&&) noexcept; explicit time_class(const struct tm&); explicit time_class(); ~time_class(); const struct tm& value() const; time_class& operator=(const time_class&); time_class& operator=(time_class&&) noexcept; time_class& operator=(const struct tm&); //comparisons bool operator==(const time_class&) const; bool operator!=(const time_class&) const; bool operator<(const time_class&) const; bool operator>(const time_class&) const; bool operator<=(const time_class&) const; bool operator>=(const time_class&) const; //mathematical ops: const time_class& operator++(); time_class operator+(int) const; const time_class& operator+=(int); const time_class& operator--(); time_class operator-(int) const; const time_class& operator-=(int); /* data retrieval. I hate to do this, but the information * must be modified before reads and after writes. */ int& second();//0-59 const int& second() const; int& mhour(); //0-23 const int& mhour() const; int& minute();//0-59 const int& minute() const; int& month(); //0-11 const int& month() const; int& wday(); //0-6 const int& wday() const; int& mday(); //1-31 const int& mday() const; int& yday(); const int& yday() const; int hour() const; bool am() const; int gyear() const; void syear(const int&); void smonth(const int&); std::string month_name() const; std::string wday_name() const; friend std::istream& operator>>(std::istream&, time_class&); friend std::ostream& operator<<(std::ostream&, const time_class&); private: struct tm cur_time; void sync_to_yday(); void subtract_day(); void add_day(); }; } #endif <file_sep>#ifndef NOTEBOOK_HPP_INCLUDED #define NOTEBOOK_HPP_INCLUDED #include <string> #include <vector> #include <iostream> #include <set> #include <boost/filesystem.hpp> #include "data/time_class.hpp" #include "data/global.hpp" namespace data { using boost::filesystem::path; struct note_data; struct notebook_data; std::istream& operator>>(std::istream&, note_data&); std::ostream& operator<<(std::ostream&, const note_data&); std::istream& operator>>(std::istream&, notebook_data&); std::ostream& operator<<(std::ostream&, const notebook_data&); struct note_data { bool operator==(const note_data&) const; bool operator!=(const note_data&) const; bool operator<(const note_data&) const; std::wstring note, name; tdata::time_class timestamp; }; struct notebook_data { bool operator==(const notebook_data&) const; bool operator!=(const notebook_data&) const; //some constants for notebooks: static constexpr const wchar_t* const FOLDER_NAME{L"notebooks"}; //the default name of the folder to stor notebooks in static constexpr uint32_t NO_ID{0}; //the value of notebook_data::id when it is invalid of default. static constexpr const wchar_t* const FILE_EXTENSION{L".nb"}; //the file extension for a notebook file static constexpr const wchar_t* const FILE_REGEX{L"**.nb$"}; //the regex to use when globbing the notebook file //data: std::vector<note_data> notes = std::vector<note_data>{}; std::wstring name = L""; uint32_t id = NO_ID; }; /* Functions to handle file loading, information retrieval, etc... */ namespace file { using boost::filesystem::path; using boost::filesystem::current_path; std::vector<notebook_data> load_notebooks(const path& = (global::root / path{std::wstring{data::notebook_data::FOLDER_NAME}})); bool save(notebook_data&, const path& = (global::root / path{std::wstring{data::notebook_data::FOLDER_NAME}})); bool remove_notebook(const uint32_t&, const path& = (global::root / path{std::wstring{data::notebook_data::FOLDER_NAME}})); std::set<uint32_t> notebook_ids(const path& = (global::root / path{std::wstring{data::notebook_data::FOLDER_NAME}})); } } #endif <file_sep>- add filter on filenames when saving notebooks <file_sep>Build requirements: - boost (latest) - Qt >= 5.6 (qmake, Qt library) - make or somthing like it - C++14 compliant compiler
f04621f497aec36c9efcf6c9efce40b531784fc2
[ "Markdown", "Text", "C++" ]
16
C++
BeenEncoded/notebook_program
54a4efe19392884c1c67dbe1cc87dda6d46df74a
56c2d5c10dfc15400462f1e83c770ee1281ea73a
refs/heads/master
<repo_name>alkimderin/InstaPy<file_sep>/instapy/database_engine.py import os import sqlite3 from .settings import Settings SELECT_FROM_PROFILE_WHERE_NAME = "SELECT * FROM profiles WHERE name = :name" INSERT_INTO_PROFILE = "INSERT INTO profiles (name) VALUES (?)" SQL_CREATE_PROFILE_TABLE = """CREATE TABLE IF NOT EXISTS `profiles` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL);""" SQL_CREATE_RECORD_ACTIVITY_TABLE = """CREATE TABLE IF NOT EXISTS `recordActivity` ( `profile_id` INTEGER REFERENCES `profiles` (id), `likes` SMALLINT UNSIGNED NOT NULL, `comments` SMALLINT UNSIGNED NOT NULL, `follows` SMALLINT UNSIGNED NOT NULL, `unfollows` SMALLINT UNSIGNED NOT NULL, `server_calls` INT UNSIGNED NOT NULL, `created` DATETIME NOT NULL);""" SQL_CREATE_FOLLOW_RESTRICTION_TABLE = """CREATE TABLE IF NOT EXISTS `followRestriction` ( `profile_id` INTEGER REFERENCES `profiles` (id), `username` TEXT NOT NULL, `times` TINYINT UNSIGNED NOT NULL);""" def get_database(): _id = Settings.profile["id"] address = Settings.database_location return address, _id def initialize_database(): logger = Settings.logger name = Settings.profile['name'] address = validate_database_file_address() create_database_directories(address) create_database(address, logger, name) update_profile_settings(name, address, logger) def create_database(address, logger, name): if not os.path.isfile(address): try: connection = sqlite3.connect(address) with connection: connection.row_factory = sqlite3.Row cursor = connection.cursor() create_profiles_table(cursor) create_record_activity_table(cursor) create_follow_restriction_table(cursor) connection.commit() except Exception as exc: logger.warning( "Wah! Error occured while getting a DB for '{}':\n\t{}".format(name, str(exc).encode("utf-8"))) finally: if connection: # close the open connection connection.close() def create_follow_restriction_table(cursor): cursor.execute(SQL_CREATE_FOLLOW_RESTRICTION_TABLE) def create_record_activity_table(cursor): cursor.execute(SQL_CREATE_RECORD_ACTIVITY_TABLE) def create_profiles_table(cursor): cursor.execute(SQL_CREATE_PROFILE_TABLE) def create_database_directories(address): db_dir = os.path.dirname(address) if not os.path.exists(db_dir): os.makedirs(db_dir) def validate_database_file_address(): address = Settings.database_location if not address.endswith(".db"): slash = "\\" if "\\" in address else "/" address = address if address.endswith(slash) else address + slash address += "instapy.db" Settings.database_location = address return address def update_profile_settings(name, address, logger): try: conn = sqlite3.connect(address) with conn: conn.row_factory = sqlite3.Row cursor = conn.cursor() profile = select_profile_by_username(cursor, name) if profile is None: profile = insert_profile(conn, cursor, name) Settings.update_settings_with_profile(dict(profile)) except Exception as exc: logger.warning("Heeh! Error occured while getting a DB profile for '{}':\n\t{}".format(name, str(exc).encode("utf-8"))) finally: if conn: # close the open connection conn.close() def insert_profile(conn, cursor, name): cursor.execute(INSERT_INTO_PROFILE, (name,)) # commit the latest changes conn.commit() # reselect the table after adding data to get the proper `id` profile = select_profile_by_username(cursor, name) return profile def select_profile_by_username(cursor, name): cursor.execute(SELECT_FROM_PROFILE_WHERE_NAME, {"name": name}) profile = cursor.fetchone() return profile
1b973183965fd03180ecc3149ad83734fc42d0c0
[ "Python" ]
1
Python
alkimderin/InstaPy
3b5482a7c9e602506a9e71829bf4070430bccf7d
735cd8152b18521b4fbc9d1e4e38e5725ad984af
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); } private Image _icon; private string _title; private string _subtitle; [Category("Custom Props")] public Image Icon { get { return _icon; } set { _icon = value; pictureBox1.Image = value; } } [Category("Custom Props")] public string Title { get { return _title; } set { _title = value; label1.Text = value; } } [Category("Custom Props")] public string SubTitle { get { return _subtitle; } set { _subtitle = value; label2.Text = value; } } private void ucRequest_MouseEnter(object sender, EventArgs e) { this.BackColor = Color.FromArgb(217, 229, 242); } private void ucRequest_MouseLeave(object sender, EventArgs e) { this.BackColor = Color.FromArgb(255, 255, 255); } private void label1_Click(object sender, EventArgs e) { } } } <file_sep>using System.Data.SqlClient; namespace WindowsFormsApplication1.DataLayer { class Connection { public SqlConnection connect = new SqlConnection("Data Source=DESKTOP-0G5OTMF\\SQLEXPRESS;Initial Catalog=DBTest;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WindowsFormsApplication1.ActionLayer; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void GenerateDynamcUserControl() { flowLayoutPanel1.Controls.Clear(); ClassActionLayer obj = new ClassActionLayer(); DataTable table = obj.GetItems(); if (table != null) { if (table.Rows.Count > 0) { MyUserControl[] listItems = new MyUserControl[table.Rows.Count]; for (int i = 0; i < 1; i++) { foreach (DataRow row in table.Rows) { listItems[i] = new MyUserControl(); MemoryStream stream = new MemoryStream((byte[]) row["Image"]); listItems[i].Icon = new Bitmap(stream); listItems[i].Title = row["Title"].ToString(); listItems[i].SubTitle = row["SubTitle"].ToString(); flowLayoutPanel1.Controls.Add(listItems[i]); listItems[i].Click += new EventHandler(this.UserControl_Click); } } } } } void UserControl_Click(object sender, EventArgs e) { MyUserControl obj = (MyUserControl) sender; pictureBox1.Image = obj.Icon; label1.Text = obj.Title; label2.Text = obj.SubTitle; if (panel1.Visible == false) panel1.Visible = true; } public void refresh_Click(object sender, EventArgs e) { GenerateDynamcUserControl(); } public void add_Click(object sender, EventArgs e) { new Form2().Show(); } private void Form1_Load(object sender, EventArgs e) { GenerateDynamcUserControl(); } private void panel1_Paint(object sender, PaintEventArgs e) { } } } <file_sep>using System; using System.Data; using System.Drawing; using System.Windows.Forms; using WindowsFormsApplication1.DataLayer; namespace WindowsFormsApplication1.ActionLayer { class ClassActionLayer { public bool SaveItems(Image image, string title, string subtitle) { try { ClassDataLayer obj = new ClassDataLayer(); return obj.AddItemsToTable(image, title, subtitle); } catch (Exception e) { DialogResult result = MessageBox.Show(e.Message.ToString()); return false; } } public DataTable GetItems() { try { ClassDataLayer obj = new ClassDataLayer(); return obj.ReadItemsTable(); } catch (Exception e) { DialogResult result = MessageBox.Show(e.Message.ToString()); return null; } } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApplication1.DataLayer { class ClassDataLayer { public bool AddItemsToTable(Image image, string title, string subtitle) { Connection connection = new Connection(); if (ConnectionState.Closed == connection.connect.State) { connection.connect.Open(); } string query = "INSERT INTO table_test (Title, SubTitle, Image) values (@Title, @Subtitle, @Image)"; try { using (SqlCommand sql = new SqlCommand(query, connection.connect)) { sql.Parameters.AddWithValue("@Title", title.Trim()); sql.Parameters.AddWithValue("@SubTitle", subtitle.Trim()); MemoryStream stream = new MemoryStream(); image.Save(stream, image.RawFormat); sql.Parameters.AddWithValue("@Image", stream.ToArray()); sql.ExecuteNonQuery(); } return true; } catch { throw; } } public DataTable ReadItemsTable() { Connection connection = new Connection(); if (ConnectionState.Closed == connection.connect.State) { connection.connect.Open(); } string query = "SELECT * FROM table_test;"; SqlCommand sql = new SqlCommand(query, connection.connect); try { using (SqlDataAdapter adapter = new SqlDataAdapter(sql)) { DataTable table = new DataTable(); adapter.Fill(table); return table; } } catch { throw; } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using WindowsFormsApplication1.ActionLayer; namespace WindowsFormsApplication1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } public void save_Click(object sender, EventArgs e) { ClassActionLayer obj = new ClassActionLayer(); if (obj.SaveItems(pictureBox1.Image, textBox1.Text, textBox2.Text)) { MessageBox.Show("Success"); } else { MessageBox.Show("Failed."); } } private void upload_Click(object server, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog() == DialogResult.OK) { Image image = Image.FromFile(dialog.FileName); pictureBox1.Image = image; } } } }
c47bc7d63c7527109269ac0e14d55d9f6f4483ee
[ "C#" ]
6
C#
herikaniugu/windows-forms-example
ff90e909e109b92dae2c3ea166aaba1b990d5f95
b003debf5ec25b37c131f2a886f944af5e62d946
refs/heads/master
<repo_name>wesley-qiu/Editor<file_sep>/src/Wesley/Editor/EditorServiceProvider.php <?php namespace Wesley\Editor; use Illuminate\Support\ServiceProvider; class EditorServiceProvider extends ServiceProvider { public function boot() { $this->package('wesley-qiu/Editor'); include __DIR__ . '/../../routes.php'; } public function register() { /*$this->app->bindShared('Editor', function($app){ $editor = new Editor(); $config = $app['config']['editor']; foreach($config as $k=>$v){ if( is_array($v) ){ $editor->$k = array_merge($editor->$k, $v); }else{ $editor->$k = $v; } } return $editor; });*/ $this->app['command.wesley.publish'] = $this->app->share(function($app) { //Make sure the asset publisher is registered. $app->register('Illuminate\Foundation\Providers\PublisherServiceProvider'); return new Console\PublishCommand($app['asset.publisher']); }); $this->commands('command.wesley.publish'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('command.wesley.publish',); } }<file_sep>/autoload.php <?php //require __DIR__.'/src/Wesley/Editor/Editor.php'; //require __DIR__.'/src/Wesley/Editor/EditorServiceProvider.php'; //$loader = require __DIR__.'/../../../../vender/autoload.php'; $loader = require 'vendor/autoload.php'; $loader->add('Wesley\\Editor', __DIR__.'/src/');<file_sep>/src/routes.php <?php Route::any('editor/browse','EditorController@browse'); Route::any('editor/upload','EditorController@upload');<file_sep>/src/config/editor.php <?php return array( 'basePath' => '/editor/', 'textareaAttributes' => array('cols'=>80,'rows'=>10), 'config' => array( 'filebrowserBrowseUrl' => 'admin/browse?type=image', 'filebrowserUploadUrl' => 'admin/upload?type=image', ), );
cbd3e9c316799a0f0745b8b05a5c3983ae5bfda7
[ "PHP" ]
4
PHP
wesley-qiu/Editor
7a15fe93b2d68f44cec3947adef8a7791f5e5c19
60be1e1bc7740ce99162ec97df62525ed83b4b22
refs/heads/master
<file_sep>import React from 'react' import TodoListItems from './TodoListItems' function TodoList({todos, onDelete, onSelect, onToggle}) { return ( <ul style ={listStyle}> {todos.map(todo => (<TodoListItems key={todo.id} todo={todo} onSelect={onSelect} onDelete={onDelete} onToggle={onToggle} />))} </ul> ); } export default TodoList const listStyle = { listStyle: 'none', margin: '0', padding: '0', } <file_sep>import React from 'react' import { connect } from 'react-redux'; import { closeModal, saveTodo, todoTitleChange } from '../store/actions'; function Modal({onChange, closeModal, saveTodo, todo}) { function onValueChange(e){ const changes = {[e.target.name]:e.target.value} console.log(changes) onChange(changes); } return ( <form style = {modalTodoContainerStyle}> <div style = {modalTodoStyle}> <label>Title</label> <input type = 'text' name = 'title' value = {todo.title} onChange={onValueChange}></input> <div > <button style={{...btnStyle, left: '48%'}} onClick={()=>saveTodo(todo)}>Save</button> <button style={{...btnStyle, backgroundColor: '#ff8c7a'}} onClick={closeModal}>Cancel</button> </div> </div> <div style = {modalTodoBkgStyle}> </div> </form> ) } function mapStateToProps(state){ return { todo: state.modalVisible } } const mapDispatchToProps = { onChange: todoTitleChange, closeModal: closeModal, saveTodo: saveTodo } export default connect(mapStateToProps, mapDispatchToProps) (Modal) const modalTodoBkgStyle ={ opacity: '0.60', backgroundColor: '#A7A7A2', height: '100%', width: '100%', } const modalTodoContainerStyle = { position: 'fixed', height: '100%', width: '100%', } const modalTodoStyle ={ color: '#ffffff', width: '200px', height: '80px', backgroundColor: '#272726', padding: '20px', opacity: '1', position: 'absolute', top: '30%', left: '40%', zIndex: '10000', borderRadius: '8px' } const btnStyle = { width: '30%', backgroundColor: 'lightblue', padding: '7px', borderRadius: '8px', marginLeft: '20px', color: '#272726', fontWeight: 'bold', position: 'absolute', top:'60%', left: '5%' }<file_sep>import React, {useState, useEffect} from 'react' import Sticker from './sticker/Sticker' function StickersBoard() { const [stickers, setStickers] = useState([]) useEffect(() => { const sticker = localStorage.getItem('sticker') setStickers(JSON.parse(sticker) || []) }, []) useEffect(() => { localStorage.setItem('sticker', JSON.stringify(stickers)) }, [stickers]) function renderStickers(){ return stickers.map((sticker) => { return <Sticker key = {sticker.id} onClick = {onDeleteStickerBtn} sticker = {sticker} onChangeText = {onChangeText}/> }) } function onChangeText(value, id){ const newStickers = stickers.map(sticker => { return sticker.id === id ? {...sticker, task: value } : sticker;}) setStickers(newStickers); } function onDeleteStickerBtn (id){ const newStickers = stickers.filter(item =>{ return item.id !== id; }) setStickers(newStickers); } function addNewStikerOnBoard(){ setStickers([...stickers, creatNewStiker()]) } function creatNewStiker(){ return { id: Date.now(), task: "" } } return ( <div style ={{...containerStyle}}> <div> Do you need add new sticker? <button onClick = {addNewStikerOnBoard}> Add</button> </div> <div style = {{...boardStyle}}> {renderStickers()} </div> </div> ) } export default StickersBoard const boardStyle = { display: 'inline-block', width: '80%', height: '80%', border: 'solid 1px black', background: 'lightblue' } const containerStyle = { background: 'grey', width: '100%', height: '680px' }<file_sep>import React from 'react' import TodoListItems from './TodoListItems' import { connect } from 'react-redux'; import { todoDelete, openModal, toggleTodoItem } from '../store/actions'; function TodoList({todos, onDelete, onSelect, onToggle}) { return ( <ul style ={listStyle}> {todos.map(todo => (<TodoListItems key={todo.id} todo={todo} onDelete={onDelete} onSelect={onSelect} onToggle={onToggle} />))} </ul> ); } function mapStateToProps(state){ return { todos: state.todos } } const mapDispatchToProps = { onDelete: todoDelete, onSelect: openModal, onToggle: toggleTodoItem } export default connect(mapStateToProps, mapDispatchToProps) (TodoList) const listStyle = { listStyle: 'none', margin: '0', padding: '0', } <file_sep>import React from 'react' function Modal({onChange, onCancel, onSave, todo}) { function onValueChange(e){ onChange({ [e.target.name]:e.target.value }); } function onModalSubmit(e){ console.log('modal submit') e.preventDefault(); onSave(todo); } return ( <form style = {modalTodoContainerStyle}> <div style = {modalTodoStyle}> <label>Title</label> <input type = 'text' name = 'title' value = {todo.title} onChange={onValueChange}></input> <div > <button style={{...btnStyle, left: '48%'}} onClick={onModalSubmit}>Save</button> <button style={{...btnStyle, backgroundColor: '#ff8c7a'}} onClick={onCancel}>Cancel</button> </div> </div> <div style = {modalTodoBkgStyle}> </div> </form> ) } export default Modal const modalTodoBkgStyle ={ opacity: '0.60', backgroundColor: '#A7A7A2', height: '100%', width: '100%', } const modalTodoContainerStyle = { position: 'fixed', height: '100%', width: '100%', } const modalTodoStyle ={ color: '#ffffff', width: '200px', height: '80px', backgroundColor: '#272726', padding: '20px', opacity: '1', position: 'absolute', top: '30%', left: '40%', zIndex: '10000', borderRadius: '8px' } const btnStyle = { width: '30%', backgroundColor: 'lightblue', padding: '7px', borderRadius: '8px', marginLeft: '20px', color: '#272726', fontWeight: 'bold', position: 'absolute', top:'60%', left: '5%' }<file_sep>import React from 'react' function Header({onClick}) { return ( <div>Todo List <button style={addBtnStyle} onClick = {onClick}>Add Todo</button> </div> ) } export default Header const addBtnStyle = { backgroundColor: 'lightblue', padding: '7px', borderRadius: '8px', marginLeft: '20px', color: '#272726', fontWeight: 'bold' } <file_sep>import React from 'react' function Sticker(props) { return ( <div style = {{...stickerStyle}} > <div > <button style = {{...stickerBtnDelStyle}} className = "stickerBtnDel" onClick = {() => props.onClick(props.sticker.id)}>del </button> </div> <textarea rows = "4" cols = "18" style = {{...textareaStyle}} value = {props.sticker.task} onChange = {(e) => props.onChangeText(e.target.value, props.sticker.id)}> </textarea> </div> ) } export default Sticker const stickerBtnDelStyle = { float: 'right' } const textareaStyle = { width: '144px', height: '61px', background: 'lightyellow' } const stickerStyle = { float: 'none', display: 'inline-block', width: '150px', height: '88px', margin: '5px', border: 'solid 1px black', background: 'lightyellow' } <file_sep>import React, { Component } from 'react' import './ContactList.css' import ContactListItem from './contactListItem/ContactListItem' import propTypes from '../propTypes'; export default class ContactList extends Component { render() { const {contacts, onDelete, onSelectContact} = this.props; return ( <div className = "contactsList"> <div> {contacts.map(contact => ( <ContactListItem key={contact.id} contact={contact} onDelete={onDelete} onSelectContact ={onSelectContact}/>))} </div> </div> ) } } ContactList.propTypes = { contacts: propTypes.contacts.isRequired, onDelete: propTypes.func.isRequired, onSelectContact: propTypes.func.isRequired } <file_sep>import React, { Component } from 'react' import './ContactForm.css' import propTypes from '../propTypes'; export default class ContactForm extends Component { onInputChange = (e) => { this.props.onChange({ [e.target.name]: e.target.value }); } onContactFormSubmit = (e) => { e.preventDefault(); this.props.onSaveContactBtnClick(this.props.contact); } render() { return ( <form className = "contactForm" onSubmit = {this.onContactFormSubmit}> <label>Name</label> <input name = "name" type = "text" value = {this.props.contact.name} onChange = {this.onInputChange}/> <label>Surname</label> <input name = "surname" type = "text" value = {this.props.contact.surname} onChange = {this.onInputChange}/> <label>Age</label> <input name = "age" type = "text" value = {this.props.contact.age} onChange = {this.onInputChange}/> <label>Phone</label> <input name = "phone" type = "text" value = {this.props.contact.phone} onChange = {this.onInputChange}/> <div> <button className = "submitFormBtn" type="submit">Save Contact</button> </div> </form> ) } } ContactForm.propTypes = { onChange: propTypes.func.isRequired, onSaveContactBtnClick: propTypes.func.isRequired }<file_sep>import React from 'react'; import './App.css'; import StickersBoard from './components/sticketsBoard/StickersBoard'; function App() { return ( <div className="App"> <StickersBoard/> </div> ); } export default App; <file_sep>import { ACTION_DELETE, ACTION_TOGGLE_TODO, ACTION_OPEN_MODAL, ACTION_SAVE_TODO, ACTION_TITLE_CHANGE, ACTION_CLOSE_MODAL} from "./actions"; const initialState = { todos: [ { id: 1, title: "By feed the dog", isDone: false }, { id: 2, title: "Do homework", isDone: false }, { id: 3, title: "Buy train tickets", isDone: false }, { id: 4, title: "Walk the dog", isDone: false } ], modalVisible: false, } function getEmptyItem() { return { title: 'Todo', isDone: false }; } function createTodo(todos, todo){ todo.id = Date.now(); return [...todos, todo] } function updateTodo(todos, todo){ console.log(todo) return todos.map(item => (item.id === todo.id ? todo : item)); } export default function(state = initialState, {type, payload}){ switch (type){ case ACTION_DELETE: return { ...state, todos: state.todos.filter(todo=> todo.id !== payload), }; case ACTION_TOGGLE_TODO: return { ...state, todos: state.todos.map(todo => todo.id === payload ? { ...todo, isDone: !todo.isDone } : todo) } case ACTION_OPEN_MODAL: console.log('open modal', payload) return { ...state, modalVisible: payload ? state.todos.find(item => item.id === payload) : getEmptyItem() } case ACTION_TITLE_CHANGE: return { ...state, modalVisible:{...state.modalVisible, ...payload} } case ACTION_SAVE_TODO: return { ...state, todos: payload.id ? updateTodo(state.todos, payload) : createTodo(state.todos, payload), modalVisible: false } case ACTION_CLOSE_MODAL: return { ...state, modalVisible: false } default: return state; } }<file_sep> export const ACTION_DELETE = 'ACTION_DELETE'; export function todoDelete(id){ return { type: ACTION_DELETE, payload: id } } export const ACTION_TOGGLE_TODO = 'ACTION_TOGGLE_TODO'; export function toggleTodoItem(id){ return { type:ACTION_TOGGLE_TODO, payload:id } } export const ACTION_OPEN_MODAL = 'ACTION_OPEN_MODAL'; export function openModal(id){ return { type: ACTION_OPEN_MODAL, payload: id } } export const ACTION_TITLE_CHANGE = 'ACTION_TITLE_CHANGE'; export function todoTitleChange(changes){ return { type:ACTION_TITLE_CHANGE, payload: changes } } export const ACTION_CLOSE_MODAL = 'ACTION_CLOSE_MODAL'; export function closeModal(){ return{ type: ACTION_CLOSE_MODAL } } export const ACTION_SAVE_TODO = 'ACTION_SAVE_TODO'; export function saveTodo(id){ return { type: ACTION_SAVE_TODO, payload: id } }
ec51831a07dc71d484208a2fa0e2d322ddd10b84
[ "JavaScript" ]
12
JavaScript
Ohiiko/Hillel_React
205b045bc39dddf8833c3b7c219f931bea29b4a2
547d4ced0466d206898d84c16c250ada02ea3a3c
refs/heads/master
<repo_name>saurabh1294/python-extract-print-text-image<file_sep>/image-text-extractor.py from PIL import Image, ImageEnhance, ImageFilter import pytesseract path = 'example_03.png' # - > Your Image Location img = Image.open(path) img = img.convert('RGB') pix = img.load() for y in range(img.size[1]): for x in range(img.size[0]): if pix[x, y][0] < 102 or pix[x, y][1] < 102 or pix[x, y][2] < 102: pix[x, y] = (0, 0, 0, 255) else : pix[x, y] = (255, 255, 255, 255) img.save('temp.png') text = pytesseract.image_to_string(Image.open(path))# os.remove('temp.jpg') print(text)# print image_to_string(Image.open('find.jpg'))<file_sep>/image.py from PIL import Image from pytesseract import image_to_string print(image_to_string(Image.open('png-logo-text.png'))) print(image_to_string(Image.open('shadow.png'), lang='eng')) print(image_to_string(Image.open('download.png'))) print(image_to_string(Image.open('example_01.png'))) print(image_to_string(Image.open('example_02.png'))) print(image_to_string(Image.open('example_03.png')))<file_sep>/README.md # python-extract-print-text-image A python tesseract example to extract and print text from images
aa6984ca7e40111ab1638dcd7dcaf6b222dae3e6
[ "Markdown", "Python" ]
3
Python
saurabh1294/python-extract-print-text-image
d1a064fbd0eca2e52d6fcfd6502ecde7e1bff15f
64dcfc2e10b44c99b314be9ca3a9c263d57bcb6d
refs/heads/master
<file_sep>import React from "react"; import { connect } from "react-redux"; class Info extends React.Component { componentDidMount() {} render() { const user = this.props.userData.userProfile; console.log(user); const links = user.links ? ( user.links.map((item, i) => ( <li key={i}> <a href={item.url}>{item.title}</a> </li> )) ) : ( <p>No links</p> ); const socialLinks = user.social_links ? ( user.social_links.map((item, i) => ( <span key={i} href={item.url} className="uk-icon-button" uk-icon={item.service_name.toLowerCase()} /> )) ) : ( <p>No links</p> ); return ( <div className=""> <h3>This is the Info Component</h3> <p>{user.display_name}</p> <p>{user.location}</p> <p>{user.occupation}</p> <ul>{links}</ul> {socialLinks} </div> ); } } const mapStateToProps = state => { return { userData: state.userData }; }; const mapDispatchToProps = dispatch => { return {}; }; export default connect( mapStateToProps, mapDispatchToProps )(Info); <file_sep>import React from "react"; import { Link } from "react-router-dom"; const Navbar = props => { return ( <nav className="uk-navbar-container uk-margin-medium-top uk-margin-large-bottom uk-background-default uk-navbar-transparent" uk-navbar="mode: click" > <div className="uk-navbar-left "> <ul className="uk-navbar-nav"> <li> <Link to="/landing"> <span href="" className="uk-icon-button" uk-icon="home" /> </Link> </li> </ul> </div> <div className="uk-navbar-center "> <ul className="uk-navbar-nav" /> </div> <div className="uk-navbar-right "> <ul className="uk-navbar-nav"> <li> <Link to="/gallery"> <span href="" className="uk-icon-button" uk-icon="grid" /> </Link> </li> <li> <Link to="/info"> <span href="" className="uk-icon-button" uk-icon="info" /> </Link> </li> </ul> </div> </nav> ); }; export default Navbar; <file_sep>import React from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; class Gallery extends React.Component { componentDidMount() {} render() { const projects = this.props.userProjects.map((item, i) => ( <li key={i}> <Link to={`/project/${item.id}`}>{item.name}</Link> </li> )); return ( <div className=""> <h3>This is the Gallery Component</h3> <ul>{projects}</ul> </div> ); } } const mapStateToProps = state => { return { userProjects: state.userData.userProjects }; }; const mapDispatchToProps = dispatch => { return {}; }; export default connect( mapStateToProps, mapDispatchToProps )(Gallery); <file_sep>import axios from "axios"; const username = "matiascorea"; // const username = "natashabertram"; export function getUserProfile() { return { type: "GET_USERPROFILE", payload: axios .get( `https://cors-anywhere.herokuapp.com/http://www.behance.net/v2/users/${username}?api_key=<KEY>` ) .then(res => { return res.data.user; }) }; } export function getUserProjects() { return { type: "GET_USERPROJECTS", payload: axios .get( `https://cors-anywhere.herokuapp.com/http://www.behance.net/v2/users/${username}/projects?api_key=<KEY>` ) .then(res => { return res.data.projects; }) }; } <file_sep>import React from "react"; import { HashRouter, Route } from "react-router-dom"; import { connect } from "react-redux"; // import Navbar from "../components/Navbar.js"; import Landing from "./LandingPage.js"; import Gallery from "./Gallery.js"; import Info from "./Info.js"; import Project from "../components/Project.js"; import Navbar from "../components/Navbar.js"; import { getUserProfile } from "../actions/userActions"; import { getUserProjects } from "../actions/userActions"; class App extends React.Component { componentDidMount() { this.props.getUserProfile(); this.props.getUserProjects(); } render() { return ( <div className="App"> <HashRouter> <div> <Navbar /> <div> <Route path="/landing" component={Landing} /> <Route path="/info" component={Info} /> <Route path="/gallery" component={Gallery} /> <Route path="/project/:id" component={Project} /> </div> </div> </HashRouter> </div> ); } } const mapStateToProps = state => { return { userData: state.userData }; }; const mapDispatchToProps = dispatch => { return { getUserProfile: () => { dispatch(getUserProfile()); }, getUserProjects: () => { dispatch(getUserProjects()); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(App); <file_sep>const userReducer = ( state = { userProfile: {}, userProjects: [] }, action ) => { switch (action.type) { case "GET_USERPROFILE_FULFILLED": state = { ...state, userProfile: action.payload }; break; case "GET_USERPROJECTS_FULFILLED": state = { ...state, userProjects: action.payload }; break; default: break; } return state; }; export default userReducer; <file_sep>import React from "react"; class LandingPage extends React.Component { render() { return ( <div> <h3>This is the Landing Page Component</h3> </div> ); } } //END OF CLASS export default LandingPage;
26226256e18eac689cc24ed146f633acc05cb023
[ "JavaScript" ]
7
JavaScript
DannyRoberts95/Creative-portfolio_boilerplate
41d9120596c6e58b8416a191aacf201a5d50875d
74979aa91655f4b923792cb5ab0fd00ea76cf4e5
refs/heads/master
<file_sep>from flask import Flask, render_template, request import pandas as pd import json import requests import xml.etree.ElementTree as ElementTree import re from dashboard import routes from dashboard.routes import app<file_sep>from flask import Flask, render_template, request import pandas as pd import json import requests import xml.etree.ElementTree as ElementTree import re app = Flask(__name__) @app.route("/") def index(): return render_template("landing.html") @app.route("/dashboard", methods=['POST']) def dashboard(): query = request.form.get("query") print("got query of",query) #printed in the command window for tracking purposes key = "<KEY>" #secret = "<KEY>" url = "https://www.goodreads.com/book/title.xml?" params = { "key" : key, "title" : query } result = requests.get(url, params=params) res = ElementTree.fromstring(result.content) filtered = re.compile('<.*?>') book_description = re.sub(filtered, '', res[1][16].text) rating_distribution = str(res[1][17][13].text).split("|") rating_distribution = [i[2:] for i in rating_distribution] rating_distribution.pop() book_title = str(res[1][1].text) book_author = str(res[1][26][0][1].text) reviews_count = str(res[1][17][3].text) average_rating = str(res[1][18].text) num_pages = str(res[1][19].text) #data = {"book_ISBN" : str(res[1][2].text)} positive_counts = int(rating_distribution[0]) + int(rating_distribution[1]) + int(int(rating_distribution[0])/2) negative_counts = int(rating_distribution[3]) + int(rating_distribution[4]) + int(int(rating_distribution[0])/2) return render_template("dashboard.html", query=query, book_description = book_description, reviews_count=reviews_count, rating_distribution = rating_distribution, book_title = book_title, book_author = book_author, average_rating = average_rating, num_pages = num_pages, positive_counts=positive_counts, negative_counts = negative_counts)<file_sep># Books_dashboard ## A dashboard which has sentiment analysis, reviews and overall popularity of a book based on Goodreads API ![landing](res/landing.png) ![dashboard](res/dash.png) <file_sep>certifi==2019.11.28 chardet==3.0.4 Click==7.0 docopt==0.6.2 Flask==1.1.1 idna==2.9 itsdangerous==1.1.0 Jinja2==2.11.1 MarkupSafe==1.1.1 nltk==3.4.5 numpy==1.18.1 packaging==20.3 pandas==1.0.1 Pillow==7.0.0 pipreqs==0.4.10 pyparsing==2.4.6 python-dateutil==2.8.1 pytz==2019.3 PyYAML==5.3 requests==2.23.0 six==1.14.0 tornado==6.0.4 urllib3==1.25.8 Werkzeug==1.0.0 yarg==0.1.9 <file_sep>from dashboard import app if __name__ == "__main__": app.run(debug = True, threaded = True) #for multiple users set threaded = True #debug = true, allows the server to reload itself when changes are made
e7c300ac14d4d0c6152b07a2f8ea7533744dc8ab
[ "Markdown", "Python", "Text" ]
5
Python
Khadija-Khaled/Books_dashboard
442caccc62c0daa7ccb97a0996370b3558852391
1d570d4916d491fcec6388bbfe0b8852bbf32bf4
refs/heads/master
<file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import json from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Module, dsl from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path from external_sub_pipeline import external_sub_pipeline0 # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') # In[ ]: # Module execute_python_script_module = Module.load(ws, namespace='azureml', name='Execute Python Script') # TODO: Dataset blob_input_data = get_global_dataset_by_path(ws, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') # In[ ]: training_data_name = 'aml_module_training_data' if training_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') train_data = Dataset.File.from_files(path=['https://dprepdata.blob.core.windows.net/demo/Titanic.csv']) train_data.register(workspace=ws, name=training_data_name, description='Training data (just for illustrative purpose)') print('Registerd') else: train_data = ws.datasets[training_data_name] print('Training dataset found in workspace') # In[ ]: @dsl.pipeline(name='sub0 graph', description='sub0') def sub_pipeline0(input): module1 = execute_python_script_module( # should be pipeline input dataset1=input, ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, ) return module2.outputs @dsl.pipeline(name='sub1 graph', description='sub1') def sub_pipeline1(input): module1 = execute_python_script_module( dataset1=input ) sub0 = sub_pipeline0(module1.outputs.result_dataset) return sub0.outputs @dsl.pipeline(name='sub2 graph', description='sub1') def sub_pipeline2(input): module1 = execute_python_script_module( dataset1=input ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, dataset2=blob_input_data ) module3 = execute_python_script_module( dataset1=input, dataset2=module2.outputs.result_dataset ) module4 = execute_python_script_module( dataset1=train_data, dataset2=module3.outputs.result_dataset ) sub0 = sub_pipeline0(module4.outputs.result_dataset) return sub0.outputs @dsl.pipeline(name='parent graph', description='parent', default_compute_target="aml-compute") def parent_pipeline(): @dsl.pipeline(name='internal sub graph', description='internal sub') def sub_pipeline_internal(input): module1 = execute_python_script_module( # should be pipeline input dataset1=input, ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, ) return module2.outputs sub0 = sub_pipeline_internal(blob_input_data) sub1 = sub_pipeline1(sub0.outputs.result_dataset) sub2 = sub_pipeline2(sub1.outputs.result_dataset) module2 = execute_python_script_module( dataset1=sub2.outputs.result_dataset, dataset2=train_data, ) external = external_sub_pipeline0(sub1.outputs.result_dataset) return module2.outputs # In[ ]: pipeline1 = parent_pipeline() pipeline1.validate() run = pipeline1.submit( experiment_name='module_SDK_test' ) run.wait_for_completion() pipeline1.save( experiment_name='module_SDK_test' ) <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: from azureml.core import Workspace, Run, Dataset, Datastore from azureml.core.compute import AmlCompute from azureml.pipeline.wrapper import Module, dsl ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: join_data_module_func = Module.load(ws, namespace='azureml', name='Join Data') execute_python_script_module_func = Module.load(ws, namespace='azureml', name='Execute Python Script') remove_duplicate_rows_module_func = Module.load(ws, namespace='azureml', name='Remove Duplicate Rows') split_data_module_func = Module.load(ws, namespace='azureml', name='Split Data') train_svd_recommender_module_func = Module.load(ws, namespace='azureml', name='Train SVD Recommender') select_columns_module_func = Module.load(ws, namespace='azureml', name='Select Columns in Dataset') score_svd_recommender_module_func = Module.load(ws, namespace='azureml', name='Score SVD Recommender') evaluate_recommender_module_func = Module.load(ws, namespace='azureml', name='Evaluate Recommender') # In[ ]: global_datastore = Datastore(ws, name="azureml_globaldatasets") movie_ratings_data = Dataset.File.from_files(global_datastore.path('GenericCSV/Movie_Ratings')).as_named_input('Movie_Ratings') imdb_movie_titles_data = Dataset.File.from_files(global_datastore.path('GenericCSV/IMDB_Movie_Titles')).as_named_input('IMDB_Movie_Titles') # In[ ]: @dsl.pipeline(name='sample_pipeline', description='Sample 10: Recommendation - Movie Rating Tweets', default_compute_target='aml-compute') def sample_pipeline(): join_data = join_data_module_func( dataset1=movie_ratings_data, dataset2=imdb_movie_titles_data, comma_separated_case_sensitive_names_of_join_key_columns_for_l = "{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"MovieId\"]}]}", comma_separated_case_sensitive_names_of_join_key_columns_for_r = "{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"Movie ID\"]}]}", match_case="True", join_type="Inner Join", keep_right_key_columns_in_joined_table="True" ) execute_python_script = execute_python_script_module_func( dataset1=join_data.outputs.results_dataset, python_script="\n# The script MUST contain a function named azureml_main\n# which is the entry point for this module.\n\n# imports up here can be used to\n\n# The entry point function can contain up to two input arguments:\n# Param<dataframe1>: a pandas.DataFrame\n# Param<dataframe2>: a pandas.DataFrame\ndef azureml_main(dataframe1 = None, dataframe2 = None): return dataframe1[['UserId','Movie Name','Rating']]," ) remove_duplicate_rows = remove_duplicate_rows_module_func( dataset=execute_python_script.outputs.result_dataset, key_column_selection_filter_expression = "{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"Movie Name\",\"UserId\"]}]}", retain_first_duplicate_row = "True" ) split_data = split_data_module_func( dataset=remove_duplicate_rows.outputs.results_dataset, splitting_mode = "Split Rows", fraction_of_rows_in_the_first_output_dataset="0.5", randomized_split="True", random_seed="0", stratified_split="False", stratification_key_column="" # this should be optional ) train_svd = train_svd_recommender_module_func( training_dataset_of_user_item_rating_triples= split_data.outputs.results_dataset1, number_of_factors="200", number_of_recommendation_algorithm_iterations="30", learning_rate="0.005" ) select_columns = select_columns_module_func( dataset= split_data.outputs.results_dataset2, select_columns= "{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"UserId\",\"Movie Name\"]}]}" ) score_svd = score_svd_recommender_module_func( trained_svd_recommendation= train_svd.outputs.trained_svd_recommendation, dataset_to_score = select_columns.outputs.results_dataset, recommender_prediction_kind = "Rating Prediction", #Recommended_item_selection ="" #Minimum_size_of_the_recommendation_pool_for_a_single_user="", #Maximum_number_of_items_to_recommend_to_a_user= "", #Whether_to_return_the_predicted_ratings_of_the_items_along_with_the_labels= "" ) evaluate = evaluate_recommender_module_func( test_dataset=split_data.outputs.results_dataset2, scored_dataset= score_svd.outputs.scored_dataset ) # In[ ]: pipeline = sample_pipeline() pipeline.validate() # In[ ]: run = pipeline.submit( experiment_name='sample_builtin_module', tags = {"origin": "notebook"} ) # In[ ]: run.wait_for_completion() # In[ ]: run # In[ ]: draft = pipeline.save( experiment_name='sample_builtin_module' ) # default_compute_target='kubeflow-aks') draft <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import os from azureml.core import Workspace, Dataset, Datastore from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size="STANDARD_D2_V2", min_nodes=1, max_nodes=4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # modules try: ejoin_module_func = Module.load(ws, namespace='microsoft.com/bing', name='ejoin') eselect_module_func = Module.load(ws, namespace='microsoft.com/bing', name='eselect') except: ejoin_module_func = Module.register(ws, os.path.join('modules', 'ejoin', 'amlmodule.yaml')) eselect_module_func = Module.register(ws, os.path.join('modules', 'eselect', 'amlmodule.yaml')) join_data_module_func = Module.load(ws, namespace='azureml', name='Join Data') train_svd_recommender_module_func = Module.load(ws, namespace='azureml', name='Train SVD Recommender') # datasets input1 = Dataset.get_by_name(ws, 'query data (large)') input2 = Dataset.get_by_name(ws, 'query data (small)') global_datastore = Datastore(ws, name="azureml_globaldatasets") movie_ratings_data = Dataset.File.from_files(global_datastore.path('GenericCSV/Movie_Ratings')).as_named_input('Movie_Ratings') imdb_movie_titles_data = Dataset.File.from_files(global_datastore.path('GenericCSV/IMDB_Movie_Titles')).as_named_input('IMDB_Movie_Titles') # In[ ]: # steps ejoin = ejoin_module_func().set_parameters( leftcolumns='m:query;querId', # missing 'rightcolumns' parameter leftkeys='m:query', rightkeys='m:Query', jointype='HashInner' ).set_inputs( left_input=input1, right_input=input2 ) eselect = eselect_module_func( # missing 'columns' parameter input=ejoin.outputs.ejoin_output ) # pipeline pipeline = Pipeline(nodes=[ejoin, eselect], outputs=eselect.outputs, default_compute_target="aml-compute") # In[ ]: graph = pipeline.validate() graph # In[ ]: # Type mismatch & Invalid range join_data = join_data_module_func( dataset1=movie_ratings_data, dataset2=imdb_movie_titles_data, comma_separated_case_sensitive_names_of_join_key_columns_for_l="{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"MovieId\"]}]}", comma_separated_case_sensitive_names_of_join_key_columns_for_r="{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"ColumnNames\",\"columns\":[\"Movie ID\"]}]}", match_case="invalid", join_type="invalid", keep_right_key_columns_in_joined_table=101 ) train_svd = train_svd_recommender_module_func( training_dataset_of_user_item_rating_triples=movie_ratings_data, number_of_factors="0", number_of_recommendation_algorithm_iterations="0", learning_rate="10" ) pipeline = Pipeline(nodes=[join_data, train_svd], default_compute_target="aml-compute") graph = pipeline.validate() graph <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import os from azureml.core import Workspace from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path workspace = Workspace.from_config() print(workspace.name, workspace.resource_group, workspace.location, workspace.subscription_id, sep = '\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(workspace, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 0, max_nodes = 4) aml_compute = ComputeTarget.create(workspace, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # load modules local_module = Module.from_yaml(workspace, yaml_file=os.path.join('modules', 'hello_world', 'module_spec.yaml')) github_yaml = "https://github.com/sherry1989/sample_modules/blob/master/3_basic_module/basic_module.yaml" github_module = Module.from_yaml(workspace, yaml_file=github_yaml) # In[ ]: # load datasets blob_input_data = get_global_dataset_by_path(workspace, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') # In[ ]: module1 = local_module( input_path=blob_input_data, string_parameter= "hello", int_parameter= 1, boolean_parameter = True, enum_parameter="option1" ) module2 = github_module( input_port=module1.outputs.output_path ) test_pipeline = Pipeline(nodes=[module1, module2], outputs=module2.outputs, name="test local module", default_compute_target='aml-compute') # In[ ]: errors = test_pipeline.validate() # In[ ]: run = test_pipeline.submit( experiment_name='module_SDK_test', ) run.wait_for_completion() # In[ ]: pipeline_draft = test_pipeline.save( experiment_name='module_SDK_local_module_test', ) pipeline_draft <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import os from azureml.core import Workspace, Dataset from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, dsl ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size="STANDARD_D2_V2", min_nodes=1, max_nodes=4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: try: train_module_func = Module.load(ws, namespace='microsoft.com/aml/samples', name='Train') except: train_module_func = Module.register(ws, os.path.join('modules', 'train-score-eval', 'train.yaml')) try: score_module_func = Module.load(ws, namespace='microsoft.com/aml/samples', name='Score') except: score_module_func = Module.register(ws, os.path.join('modules', 'train-score-eval', 'score.yaml')) try: eval_module_func = Module.load(ws, namespace='microsoft.com/aml/samples', name='Evaluate') except: eval_module_func = Module.register(ws, os.path.join('modules', 'train-score-eval', 'eval.yaml')) try: compare_module_func = Module.load(ws, namespace='microsoft.com/aml/samples', name='Compare 2 Models') except: compare_module_func = Module.register(ws, os.path.join('modules', 'train-score-eval', 'compare2.yaml')) training_data_name = "Titanic" if training_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') train_data = Dataset.File.from_files(path=['https://dprepdata.blob.core.windows.net/demo/Titanic.csv']) train_data.register(workspace=ws, name=training_data_name, description='Training data (just for illustrative purpose)') print('Registerd') else: train_data = ws.datasets[training_data_name] print('Training dataset found in workspace') train_data = Dataset.get_by_name(ws, training_data_name) test_data = Dataset.get_by_name(ws, training_data_name) # In[ ]: @dsl.pipeline(name='training_pipeline', description='A sub pipeline including train/score/eval', default_compute_target='aml-compute') def training_pipeline(learning_rate, train_dataset): train = train_module_func( training_data=train_dataset, max_epochs=5, learning_rate=learning_rate) train.runsettings.process_count_per_node = 2 train.runsettings.node_count = 2 score = score_module_func( model_input=train.outputs.model_output, test_data=test_data) eval = eval_module_func(scoring_result=score.outputs.score_output) return {**eval.outputs, **train.outputs} @dsl.pipeline(name='dummy_automl_pipeline', description='A dummy pipeline that trains two models and output the better one', default_compute_target='aml-compute') def dummy_automl_pipeline(train_dataset): train_and_evalute_model1 = training_pipeline(0.01, train_dataset) train_and_evalute_model2 = training_pipeline(0.02, train_dataset) train_and_evalute_model3 = training_pipeline(0.03, train_dataset) train_and_evalute_model4 = training_pipeline(0.04, train_dataset) compare12 = compare_module_func( model1=train_and_evalute_model1.outputs.model_output, eval_result1=train_and_evalute_model1.outputs.eval_output, model2=train_and_evalute_model2.outputs.model_output, eval_result2=train_and_evalute_model2.outputs.eval_output ) compare34 = compare_module_func( model1=train_and_evalute_model3.outputs.model_output, eval_result1=train_and_evalute_model3.outputs.eval_output, model2=train_and_evalute_model4.outputs.model_output, eval_result2=train_and_evalute_model4.outputs.eval_output ) compare = compare_module_func( model1=compare12.outputs.best_model, eval_result1=compare12.outputs.best_result, model2=compare34.outputs.best_model, eval_result2=compare34.outputs.best_result ) return compare.outputs # In[ ]: pipeline = dummy_automl_pipeline(train_data) # In[ ]: pipeline.validate() # In[ ]: run = pipeline.submit( experiment_name='sample-pipelines' ) run.wait_for_completion() run # In[ ]: pipeline.save( experiment_name='sample-pipelines' ) <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # # Demo: Replace module in pipeline # # ## step 0: Preparation - create a simple pipeline # In[ ]: import os from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Module, Pipeline, dsl from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path workspace = Workspace.from_config() print(workspace.name, workspace.resource_group, workspace.location, workspace.subscription_id, sep = '\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(workspace, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(workspace, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # load datasets github_yaml = "https://github.com/sherry1989/sample_modules/blob/master/3_basic_module/basic_module.yaml" github_module = Module.from_yaml(workspace, yaml_file=github_yaml) blob_input_data = get_global_dataset_by_path(workspace, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') hello_world = Module.from_yaml(workspace, yaml_file=os.path.join( 'modules', 'hello_world', 'module_spec.yaml')) hello_world_demo1 = Module.from_yaml(workspace, yaml_file=os.path.join( 'modules', 'hello_world', 'module_replacement_demo1.yaml')) hello_world_demo2 = Module.from_yaml(workspace, yaml_file=os.path.join( 'modules', 'hello_world', 'module_replacement_demo2.yaml')) @dsl.pipeline(name='test_module_replace_sub_pipeline', default_compute_target='aml-compute') def test_module_replace_sub_pipeline(input_path): module1 = hello_world( input_path=input_path, string_parameter="hello", int_parameter=1, boolean_parameter=True, enum_parameter="option1" ) return module1.outputs @dsl.pipeline(name='test_module_replace_parent_pipeline', default_compute_target='aml-compute') def test_module_replace_parent_pipeline(): module1 = test_module_replace_sub_pipeline(blob_input_data) module2 = github_module( input_port=module1.outputs.output_path ) return module2.outputs @dsl.pipeline(name='test_module_replace_pipeline', default_compute_target='aml-compute') def test_module_replace_pipeline(): module1 = hello_world( input_path=blob_input_data, string_parameter="hello", int_parameter=1, boolean_parameter=True, enum_parameter="option1" ) module2 = github_module( input_port=module1.outputs.output_path ) return module2.outputs pipeline = test_module_replace_pipeline() pipeline.validate() # ## Feature 1: Replace module by module function # # * **replace origin module `hello_world` to `hello_world_demo1` which added an optional input port `Input path2`** # In[ ]: pipeline.replace(hello_world, hello_world_demo1) pipeline.validate() # ## *Feature 2: Do some checks to validate operation as much as possible* # # * **try to replace origin module `hello_world` to `hello_world_demo2` which added a required input port `Input path3`** # # **this operation will be rejected* # In[ ]: pipeline = test_module_replace_pipeline() pipeline.replace(hello_world, hello_world_demo2) # ## *Feature 3: Allow user skip those checks mentioned before* # # * **force replace origin module `hello_world` to `hello_world_demo2` which added a required input port `Input path3`** # # **this operation cause pipeline validate raise error* # In[ ]: pipeline = test_module_replace_pipeline() pipeline.replace(hello_world, hello_world_demo2, force=True) pipeline.validate() # ## *Feature 4: Allow replace modules in sub-pipeline or not* # # * **define a simple pipeline with sub-pipeline** # In[ ]: pipeline = test_module_replace_parent_pipeline() pipeline.validate() # * **regular replace with `recursive` default value False** # # **this operation won't make a difference* # In[ ]: pipeline.replace(hello_world, hello_world_demo1) pipeline.validate() # * **replace with `recursive=True`** # # **this operation will make a difference* # In[ ]: pipeline.replace(hello_world, hello_world_demo1, recursive=True) pipeline.validate() <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import json, os from datetime import datetime from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Module, dsl from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path # In[ ]: ws = Workspace.from_config() #ws = Workspace.get(name='itp-pilot', subscription_id='<KEY>', resource_group='itp-pilot-ResGrp') print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') # In[ ]: # Module modulefunc = Module.from_yaml(ws, yaml_file=os.path.join('modules', 'noop', '1in2out.spec.yaml')) # Dataset data = get_global_dataset_by_path(ws, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') # In[ ]: @dsl.pipeline( name='A huge pipeline composed with nodes 1 in 2 outs', description='A sample', default_compute_target='aml-compute' # 'k80-16-a' ) def cell_division(): layer = 6 nodes = [] nodes.append(modulefunc(input1=data)) for i in range(0, layer-1): print('i=', i, ' nodes len=', len(nodes)) current_layer_nodes = [] for j in range(0, pow(2, i)): print(datetime.now().strftime("%d/%m/%Y %H:%M:%S"), '\tj=', j) n = nodes[-j-1] current_layer_nodes.append(modulefunc(input1=n.outputs.output1)) current_layer_nodes.append(modulefunc(input1=n.outputs.output2)) nodes = nodes + current_layer_nodes return {**nodes[-1].outputs} # In[ ]: pipeline = cell_division() pipeline.validate() # In[ ]: print(datetime.now().strftime("%d/%m/%Y %H:%M:%S"), '\t submitting') run = pipeline.submit( experiment_name='module_SDK_test' ) print(datetime.now().strftime("%d/%m/%Y %H:%M:%S"), '\t submitted') # In[ ]: #run.wait_for_completion() run # In[ ]: print(datetime.now().strftime("%d/%m/%Y %H:%M:%S"), '\t saving') draft = pipeline.save( experiment_name='module_SDK_test' ) print(datetime.now().strftime("%d/%m/%Y %H:%M:%S"), '\t saved') draft # In[ ]: <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import json from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Module, dsl, Pipeline from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') # In[ ]: # Module execute_python_script_module = Module.load(ws, namespace='azureml', name='Execute Python Script') # Dataset global_input_data = get_global_dataset_by_path(ws, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') # In[ ]: training_data_name = 'aml_module_training_data' if training_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') train_data = Dataset.File.from_files(path=['https://dprepdata.blob.core.windows.net/demo/Titanic.csv']) train_data.register(workspace=ws, name=training_data_name, description='Training data (just for illustrative purpose)') print('Registerd') else: train_data = ws.datasets[training_data_name] print('Training dataset found in workspace') # In[ ]: module1 = execute_python_script_module( dataset1=global_input_data, ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, ) pipeline1 = Pipeline(nodes=[module2, module1], outputs=module2.outputs, name="p1", default_compute_target='aml-compute') module3 = execute_python_script_module( dataset1=pipeline1.outputs.result_dataset, ) module4 = execute_python_script_module( dataset1=module3.outputs.result_dataset, ) pipeline2 = Pipeline(nodes=[module3, module4, pipeline1], outputs=module4.outputs, name="p2") module5 = execute_python_script_module( dataset1=train_data, dataset2=pipeline2.outputs.result_dataset ) pipeline = Pipeline(nodes=[pipeline2, module5], outputs=module5.outputs, default_compute_target='aml-compute') # In[ ]: pipeline1.validate() # In[ ]: pipeline.validate() # In[ ]: run = pipeline.submit( experiment_name='sample_sub_pipeline_no_dsl' ) run.wait_for_completion() pipeline.save( experiment_name='sample_sub_pipeline_no_dsl' ) <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: from azureml.core import Workspace from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline workspace = Workspace.from_config() print(workspace.name, workspace.resource_group, workspace.location, workspace.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(workspace, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(workspace, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) try: mpi_train_module_func = Module.load(workspace, namespace="microsoft.com/azureml/samples", name="Hello World MPI Job") except: mpi_train_module_func = Module.register(workspace, os.path.join('modules', 'mpi_module', 'module_spec.yaml')) from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path blob_input_data = get_global_dataset_by_path(workspace, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') mpi_train = mpi_train_module_func(input_path = blob_input_data, string_parameter = "test1") mpi_train.runsettings.configure(node_count=2, process_count_per_node=2) print(mpi_train.runsettings.node_count) mpi_train.runsettings.node_count = 1 test_pipeline = Pipeline(nodes=[mpi_train], name="test mpi", default_compute_target='aml-compute') test_pipeline.validate() # In[ ]: import json from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Module, dsl from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path from external_sub_pipeline import external_sub_pipeline0 ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') # Module execute_python_script_module = Module.load(ws, namespace='azureml', name='Execute Python Script') # TODO: Dataset blob_input_data = get_global_dataset_by_path(ws, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') training_data_name = 'aml_module_training_data' if training_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') train_data = Dataset.File.from_files(path=['https://dprepdata.blob.core.windows.net/demo/Titanic.csv']) train_data.register(workspace=ws, name=training_data_name, description='Training data (just for illustrative purpose)') print('Registerd') else: train_data = ws.datasets[training_data_name] print('Training dataset found in workspace') @dsl.pipeline(name='sub0 graph', description='sub0') def sub_pipeline0(input): module1 = execute_python_script_module( # should be pipeline input dataset1=input, ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, ) return module2.outputs @dsl.pipeline(name='sub1 graph', description='sub1') def sub_pipeline1(input): module1 = execute_python_script_module( dataset1=input ) sub0 = sub_pipeline0(module1.outputs.result_dataset) return sub0.outputs @dsl.pipeline(name='sub2 graph', description='sub1') def sub_pipeline2(input): module1 = execute_python_script_module( dataset1=input ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, dataset2=blob_input_data ) module3 = execute_python_script_module( dataset1=input, dataset2=module2.outputs.result_dataset ) module4 = execute_python_script_module( dataset1=train_data, dataset2=module3.outputs.result_dataset ) sub0 = sub_pipeline0(module4.outputs.result_dataset) return sub0.outputs @dsl.pipeline(name='parent graph', description='parent', default_compute_target="aml-compute") def parent_pipeline(): @dsl.pipeline(name='internal sub graph', description='internal sub') def sub_pipeline_internal(input): module1 = execute_python_script_module( # should be pipeline input dataset1=input, ) module2 = execute_python_script_module( dataset1=module1.outputs.result_dataset, ) return module2.outputs sub0 = sub_pipeline_internal(blob_input_data) sub1 = sub_pipeline1(sub0.outputs.result_dataset) sub2 = sub_pipeline2(sub1.outputs.result_dataset) module2 = execute_python_script_module( dataset1=sub2.outputs.result_dataset, dataset2=train_data, ) external = external_sub_pipeline0(sub1.outputs.result_dataset) return module2.outputs pipeline1 = parent_pipeline() pipeline1.validate() # In[ ]: pipeline1.diff(test_pipeline) # In[ ]: test_pipeline.diff(pipeline1) <file_sep># Introduction to azureml-pipeline-wrapper The following notebooks provide an introduction to azureml-pipeline-wrapper. These notebooks below are designed to go in sequence. 1. [sample_simple_module_func.ipynb]: Start with this notebook to understand the basic usage. 2. [sample_builder_pattern.ipynb]: Intro to builder pattern 4. [sample_save_as_pipelinedraft.ipynb]: Save as pipelinedraft 3. [sample_sub_pipeline.ipynb]: Sub pipeline 5. [sample_pipeline_parameter.ipynb] Pipeline parameter <file_sep>#### Steps to create your own image 1. login in to docker: ```docker login``` 2. make an empty directory and move the ```Dockerfile``` into it. Modify this ```Dockerfile``` as you like. 3. build an image and name it as mine: ```docker build -t mine .``` 4. give this image a tag : ```docker tag mine littlehaes/azureml-demo``` Attention: you need to change ```littlehaes``` to the repository name in your docker hub 5. push this image to the your docker hub: ```docker push littlehaes/azureml-demo``` <file_sep>FROM debian:9 # sdk version ARG SDK_VERSION_SHORT=15978945 ARG SDK_SOURCE=https://azuremlsdktestpypi.azureedge.net/CLI-SDK-Runners-Validation/$SDK_VERSION_SHORT ARG SDK_VERSION_LONG=0.1.0.$SDK_VERSION_SHORT ARG AZ_EXTENSION_SOURCE=https://azuremlsdktestpypi.azureedge.net/CLI-SDK-Runners-Validation/$SDK_VERSION_SHORT/azure_cli_ml-0.1.0.$SDK_VERSION_SHORT-py3-none-any.whl # create vsonline ARG USERNAME=vsonline ARG USER_UID=1000 ARG USER_GID=$USER_UID ENV LANG=C.UTF-8 LC_ALL=C.UTF-8 ENV PATH /home/$USERNAME/conda/bin:/home/$USERNAME/.local/bin:$PATH RUN apt-get update --fix-missing && \ apt-get install -y wget bzip2 ca-certificates curl git apt-utils sudo vim htop && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # create vsonline RUN groupadd --gid $USER_GID $USERNAME && \ useradd -s /bin/bash --uid $USER_UID --gid $USER_GID -m $USERNAME && \ apt-get install -y sudo && \ echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME && \ chmod 0440 /etc/sudoers.d/$USERNAME # [Optional] Set the default user. Omit if you want to keep the default as root. USER $USERNAME RUN wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.3-Linux-x86_64.sh -O ~/miniconda.sh && \ /bin/bash ~/miniconda.sh -b -p /home/$USERNAME/conda && \ /home/$USERNAME/conda/bin/pip install --extra-index-url=$SDK_SOURCE azure-cli azureml-defaults==$SDK_VERSION_LONG azureml-pipeline-wrapper[notebooks]==$SDK_VERSION_LONG azureml-pipeline-core==$SDK_VERSION_LONG azure.storage.blob && \ # /home/$USERNAME/conda/bin/pip install --extra-index-url=$SDK_SOURCE azure-cli && \ az extension add --source $AZ_EXTENSION_SOURCE --pip-extra-index-urls $SDK_SOURCE --yes --debug && \ whoami && \ whoami USER root RUN whoami && \ whoami && \ ln -s /home/$USERNAME/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh && \ echo ". ~/conda/etc/profile.d/conda.sh" >> /home/$USERNAME/.bashrc && \ echo "conda activate base" >> /home/$USERNAME/.bashrc ENV TINI_VERSION v0.16.1 ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/bin/tini RUN chmod +x /usr/bin/tini ENTRYPOINT [ "/usr/bin/tini", "--" ] CMD [ "/bin/bash" ]<file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: from azureml.core import Workspace from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline # In[ ]: workspace = Workspace.from_config() print(workspace.name, workspace.resource_group, workspace.location, workspace.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(workspace, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(workspace, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: try: mpi_train_module_func = Module.load(workspace, namespace="microsoft.com/azureml/samples", name="Hello World MPI Job") except: mpi_train_module_func = Module.register(workspace, os.path.join('modules', 'mpi_module', 'module_spec.yaml')) from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path blob_input_data = get_global_dataset_by_path(workspace, 'Automobile_price_data', 'GenericCSV/Automobile_price_data_(Raw)') mpi_train = mpi_train_module_func(input_path = blob_input_data, string_parameter = "test1") mpi_train.runsettings.configure(node_count=2, process_count_per_node=2) print(mpi_train.runsettings.node_count) mpi_train.runsettings.node_count = 1 # In[ ]: test_pipeline = Pipeline(nodes=[mpi_train], name="test mpi", default_compute_target='aml-compute') # In[ ]: errors = test_pipeline.validate() # In[ ]: run = test_pipeline.submit( experiment_name='mpi_test', ) run.wait_for_completion() # In[ ]: pipeline_draft = test_pipeline.save( experiment_name='module_SDK_mpi_test', ) pipeline_draft <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: from azureml.core import Workspace, Dataset from azureml.pipeline.wrapper import Pipeline, Module, dsl # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') # In[ ]: # register anonymous modules import os from azureml.pipeline.wrapper._module_registration import _load_anonymous_module local_module = _load_anonymous_module(ws, yaml_file=os.path.join('modules', 'hello_world', 'module_spec.yaml')) github_yaml = "https://github.com/sherry1989/sample_modules/blob/master/3_basic_module/basic_module.yaml" github_module = _load_anonymous_module(ws, yaml_file=github_yaml) hello_world_module_id = local_module.module_version_id basic_module_id = github_module.module_version_id # In[ ]: # get modules hello_world_anonymous = Module.load(ws, id=hello_world_module_id) basic_module_anonymous = Module.load(ws, id=basic_module_id) # In[ ]: # get dataset from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path automobile_price_data_raw = get_global_dataset_by_path(ws, 'automobile_price_data_raw', 'GenericCSV/Automobile_price_data_(Raw)') # In[ ]: # define pipeline @dsl.pipeline(name='module_SDK_test Run 8575', description='test local module', default_compute_target='aml-compute') def generated_pipeline(): hello_world_anonymous_0 = hello_world_anonymous( input_path=automobile_price_data_raw, int_parameter='1', boolean_parameter='True', enum_parameter='option1', string_parameter='hello') hello_world_anonymous_0.runsettings.configure(target='aml-compute') basic_module_anonymous_0 = basic_module_anonymous( input_port=hello_world_anonymous_0.outputs.output_path, parameter_1='hello', parameter_2='1') basic_module_anonymous_0.runsettings.configure(target='aml-compute') # In[ ]: # create a pipeline pipeline = generated_pipeline() # In[ ]: # validate pipeline and visualize the graph pipeline.validate() # In[ ]: # submit a pipeline run pipeline.submit(experiment_name='module_SDK_test').wait_for_completion() <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: # Initialization Steps from azureml.core import Workspace, Dataset, Datastore from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep = '\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size = "STANDARD_D2_V2", min_nodes = 1, max_nodes = 4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # modules try: ejoin_module_func = Module.load(ws, namespace='microsoft.com/bing', name='ejoin') eselect_module_func = Module.load(ws, namespace='microsoft.com/bing', name='eselect') except: ejoin_module_func = Module.register(ws, os.path.join('modules', 'ejoin', 'amlmodule.yaml')) eselect_module_func = Module.register(ws, os.path.join('modules', 'eselect', 'amlmodule.yaml')) training_data_name = "Titanic.tsv" if training_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') train_data = Dataset.File.from_files(path=['https://desginerdemo.blob.core.windows.net/demo/titanic.tsv']) train_data.register(workspace = ws, name = training_data_name, description = 'Training data (just for illustrative purpose)') print('Registerd') else: train_data = ws.datasets[training_data_name] print('Training dataset found in workspace') # datasets input1 = Dataset.get_by_name(ws, training_data_name) input2 = Dataset.get_by_name(ws, training_data_name) # The created module provide builder style functions to help user change module setting. # - set_parameters # - set_inputs # - inputs.configure # - outputs.configure # - runsettings.configure # # There function also has dynamic generated signature. For exmaple: Press shift-tab in Jupyter will get: # # ![Signature](docs/jupyter_signature_set_parameters.jpg) # # There is known issue with intellisense in VsCode. # In[ ]: import inspect ejoin = ejoin_module_func() # module function has dynamic generated signature print(inspect.signature(ejoin.set_parameters)) # use shift-tab to show signature, tab to auto-completion. This works in jupyter but has some issue in Vscode. ejoin.set_parameters() # In[ ]: # builder pattern to build module step ejoin = ejoin_module_func().set_parameters( leftcolumns='Survived;Pclass;Name', rightcolumns='Sex;Age;SibSp;Parch;Ticket;Fare;Cabin;Embarked', leftkeys='PassengerId', rightkeys='PassengerId', jointype='HashInner' ).set_inputs( left_input=input1, right_input=input2 ) # Configure inputs ejoin.inputs.leftinput.configure(mode='mount') print(ejoin.inputs.leftinput.mode) # Configure outputs ejoin.outputs.ejoin_output.configure(output_mode='mount', datastore=Datastore(ws, name="myownblob")) print(ejoin.outputs.ejoin_output.output_mode) print(ejoin.outputs.ejoin_output.datastore.name) eselect = eselect_module_func( columns='Survived;Name;Sex;Age', input=ejoin.outputs.ejoin_output ) # pipeline pipeline = Pipeline(nodes=[ejoin, eselect], outputs=eselect.outputs, default_compute_target='aml-compute') # In[ ]: pipeline.validate() # In[ ]: run = pipeline.submit( experiment_name='module_SDK_test', ) run.wait_for_completion() pipeline.save( experiment_name='module_SDK_test' ) <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import os from azureml.core import Workspace, Dataset from azureml.core.compute import AmlCompute, ComputeTarget from azureml.pipeline.wrapper import Module, Pipeline # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size="STANDARD_D2_V2", min_nodes=1, max_nodes=4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # modules try: ejoin_module_func = Module.load(ws, namespace='microsoft.com/bing', name='ejoin') eselect_module_func = Module.load(ws, namespace='microsoft.com/bing', name='eselect') except: ejoin_module_func = Module.register(ws, os.path.join('modules', 'ejoin', 'amlmodule.yaml')) eselect_module_func = Module.register(ws, os.path.join('modules', 'eselect', 'amlmodule.yaml')) # datasets left_data_name = "left.tsv" if left_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') left_data = Dataset.File.from_files(path=['https://desginerdemo.blob.core.windows.net/demo/left.tsv']) left_data.register(workspace = ws, name = left_data_name) print('Registerd') else: left_data = ws.datasets[left_data_name] print('Training dataset found in workspace') right_data_name = "right.tsv" if right_data_name not in ws.datasets: print('Registering a training dataset for sample pipeline ...') right_data = Dataset.File.from_files(path=['https://desginerdemo.blob.core.windows.net/demo/right.tsv']) right_data.register(workspace = ws, name = right_data_name) print('Registerd') else: right_data = ws.datasets[right_data_name] print('Training dataset found in workspace') # datasets input1 = Dataset.get_by_name(ws, left_data_name) input2 = Dataset.get_by_name(ws, right_data_name) # In[ ]: # steps ejoin = ejoin_module_func().set_parameters( leftcolumns='m:query;querId', rightcolumns='Market', leftkeys='m:query', rightkeys='m:Query', jointype='HashInner' ).set_inputs( left_input=input1, right_input=input2 ) eselect = eselect_module_func( columns='m:query;Market', input=ejoin.outputs.ejoin_output ) # pipeline pipeline = Pipeline(nodes=[ejoin, eselect], outputs=eselect.outputs, name='module sdk test draft', default_compute_target='aml-compute') # In[ ]: # Graph/module validation and visualization with .validate() function # pipeline.validate() #TODO # In[ ]: run = pipeline.submit( experiment_name='module_SDK_test' ) run.wait_for_completion() pipeline_draft = pipeline.save( experiment_name='module_SDK_test', tags={'Sample':'Save as pipelineDraft'}, properties={'Custom property':'Custom property value'} ) pipeline_draft <file_sep># --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- #!/usr/bin/env python # coding: utf-8 # In[ ]: import os from azureml.core import Workspace, Datastore, Dataset from azureml.pipeline.wrapper import Module, dsl from azureml.pipeline.wrapper._dataset import get_global_dataset_by_path from azureml.core.compute import AmlCompute, ComputeTarget # In[ ]: ws = Workspace.from_config() print(ws.name, ws.resource_group, ws.location, ws.subscription_id, sep='\n') aml_compute_target = "aml-compute" try: aml_compute = AmlCompute(ws, aml_compute_target) print("Found existing compute target: {}".format(aml_compute_target)) except: print("Creating new compute target: {}".format(aml_compute_target)) provisioning_config = AmlCompute.provisioning_configuration(vm_size="STANDARD_D2_V2", min_nodes=1, max_nodes=4) aml_compute = ComputeTarget.create(ws, aml_compute_target, provisioning_config) aml_compute.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # In[ ]: # Module select_columns_in_dataset = Module.load(ws, namespace='azureml', name='Select Columns in Dataset') clean_missing_data = Module.load(ws, namespace='azureml', name='Clean Missing Data') split_data = Module.load(ws, namespace='azureml', name='Split Data') join_data = Module.load(ws, namespace='azureml', name='Join Data') # Dataset try: dset = Dataset.get_by_name(ws, 'Automobile_price_data_(Raw)') except Exception: global_datastore = Datastore(ws, name="azureml_globaldatasets") dset = Dataset.File.from_files(global_datastore.path('GenericCSV/Automobile_price_data_(Raw)')) dset.register(workspace=ws, name='Automobile_price_data_(Raw)', create_new_version=True) blob_input_data = dset # In[ ]: # sub pipeline: TODO improve this experience @dsl.pipeline(name='sub sub', description='sub') def sub_sub_pipeline(minimum_missing_value_ratio): module1 = select_columns_in_dataset( dataset=blob_input_data, select_columns="{\"isFilter\":true,\"rules\":[{\"exclude\":false,\"ruleType\":\"AllColumns\"}," "{\"exclude\":true,\"ruleType\":\"ColumnNames\",\"columns\":[\"normalized-losses\"]}]}" ) module2 = clean_missing_data( dataset=module1.outputs.results_dataset, columns_to_be_cleaned="{\"isFilter\":true,\"rules\":[{\"ruleType\":\"AllColumns\",\"exclude\":false}]}", cleaning_mode='Remove entire row', minimum_missing_value_ratio=minimum_missing_value_ratio ) return module2.outputs @dsl.pipeline(name='sub', description='sub', default_compute_target='aml-compute') def sub_pipeline(random_seed, minimum_missing_value_ratio): sub_sub_pipeline1 = sub_sub_pipeline(minimum_missing_value_ratio) module3 = split_data( dataset=sub_sub_pipeline1.outputs.cleaned_dataset, splitting_mode='Split Rows', randomized_split='True', stratified_split='False', random_seed=random_seed ) return module3.outputs @dsl.pipeline(name='parent', description='parent', default_compute_target='aml-compute') def test_pipeline(): # the sub pipeline's param won't be parsed into pipeline parameter sub_pipeline1 = sub_pipeline('0', 0.0) sub_pipeline2 = sub_pipeline('0', 0.0) module4 = join_data( dataset1=sub_pipeline1.outputs.results_dataset1, dataset2=sub_pipeline2.outputs.results_dataset1, comma_separated_case_sensitive_names_of_join_key_columns_for_l='%7B%22isFilter%22%3Atrue%2C%22rules%22%3A%5B%7B%22' 'exclude%22%3Afalse%2C%22ruleType%22%3A%22AllColumns%22%7D%5D%7D', comma_separated_case_sensitive_names_of_join_key_columns_for_r='%7B%22isFilter%22%3Atrue%2C%22rules%22%3A%5B%7B%22' 'exclude%22%3Afalse%2C%22ruleType%22%3A%22AllColumns%22%7D%5D%7D', ) return module4.outputs # pipeline's param will be parsed into pipeline parameter pipeline1 = sub_pipeline('0', 0.0) pipeline2 = test_pipeline() # In[ ]: pipelines = [pipeline1, pipeline2] for pipeline in pipelines: run = pipeline.submit( experiment_name='module_SDK_pipeline_parameter_test' ) run.wait_for_completion() pipeline.save( experiment_name='module_SDK_pipeline_parameter_test' ) # In[ ]: pipeline2.outputs
a937ccb5fe8c9bdfa52721e836b2bc83e065e7db
[ "Markdown", "Python", "Dockerfile" ]
17
Python
zhohuang/hello-aml-modules
4f2ebe841b5bce933302d5fd35129a9247504c10
516d81d2f892cdd1f87236b0bc3b02503cd88768
refs/heads/master
<file_sep> import java.awt.Color; public class BST { Node root; int depth; public void BST() { depth = 0; } public Node getClickedNode(int mX, int mY, Node current){ if(current != null){ if(current.isInside(mX, mY)) return current; Node n = getClickedNode(mX, mY, current.left); if(n != null) return n; n = getClickedNode(mX, mY, current.right); if(n != null) return n; } return null; } public boolean add(int v){ //System.out.println(v); if(root == null){ root = new Node(v); } else{ Node current = root; while(true){ if(v < current.value){ if(current.left == null){ //System.out.println(v + " added left"); current.left = new Node(v); return true; }else current = current.left; } if(v > current.value){ if(current.right == null){ //System.out.println(v + " added left"); current.right = new Node(v); return true; }else current = current.right; } else if(v == current.value){ return false; } } } return true; } public void assignCoordinates(double offsetX, double offsetY) { assignCoordinatesRec(root, Main.sg.getWidth()/2, 50, offsetX, offsetY); } private void assignCoordinatesRec(Node n, double px, double py, double offX, double offY) { if (n == null) { return; } else { n.x = px; n.y = py; assignCoordinatesRec(n.left, n.x - offX, n.y + offY, offX / 2.0, offY); assignCoordinatesRec(n.right, n.x + offX, n.y + offY, offX / 2.0, offY); } } public void visualize() { visRec(root, null); } private void visRec(Node n, Node parent){ if (n==null){ return; } else { int offset = Main.sg.getWidth()/2 + n.size/2; if (parent != null){ Main.sg.drawLine(n.x, n.y, parent.x, parent.y+parent.size, Color.orange, 1.0, 0, null); } n.visualize(); visRec(n.left, n); visRec(n.right, n); } } public void printTree(Node current){ if(current != null){ if(current.left != null) printTree(current.left); System.out.println(current.value); if(current.right != null) printTree(current.right); } } } <file_sep> import java.awt.Color; import simplegui.DrwImage; public class Node { Node left; Node right; int value; double x; double y; int size; DrwImage pumpkin = new DrwImage("pumpkin.png"); public Node(int v){ value = v; x = 0; y = 0; size = 30; } public void visualize(){ Main.sg.drawImage(pumpkin, x - (size / 2), y, size, size, null); //Main.sg.drawDot(x, y, size, Color.orange, 1.0, null); } public boolean isInside(int mX, int mY){ boolean a = mX > x - size; boolean b = mX < x + size; boolean c = mY > y - size; boolean d = mY < y + size; return (a && b && c && d); } }
a3db1ead8b393cf20030e7559bb6fa86e26c659a
[ "Java" ]
2
Java
JacksonBellinger/Haloween-BST-Game
8d5bb04c5f34ec8dce2d12b51ed021d19ad952e5
1bc0a47864d365f44678abae8fe57de56333b319
refs/heads/master
<repo_name>roblav/pwa-express-demo<file_sep>/server.js var nunjucks = require('nunjucks') var path = require('path') var express = require('express') var app = express() nunjucks.configure(path.join(__dirname, '/views'), { autoescape: true, cache: false, express: app, watch: true }) app.get('/', function (req, res) { res.render('index.html') }); app.listen(3001)
cf01de5fa5f3e85fa32015cb3416f7da11134785
[ "JavaScript" ]
1
JavaScript
roblav/pwa-express-demo
d265c687b6029322c94b024b290035cb670905b9
07bdcf882cac2426003af20dd4ca90758f5e8c26
refs/heads/main
<repo_name>pacive/DI2006<file_sep>/11_as2/payment_plan.py # Define a dictionary of the price factors you can select PRICE_FACTORS = { '1': 0.9, '2': 0.95, '3': 1, '4': 1.2 } price = float(input('Ange pris: ').replace(',', '.')) print('''Välj betalningssätt: 1. Kontant 2. Kort 3. 2 månaders avbetalning 4. 3 månaders avbetalning''') # Check that the selection is valid while (plan := input('> ')) not in PRICE_FACTORS: print('Ogiltigt val, försök igen') final_price = price * PRICE_FACTORS[plan] print(f'Du behöver betala totalt {final_price:.2f} kr') <file_sep>/11_as0/tip.py TIP_RATIO = 0.15 bill = float(input('Vad går notan på? ').replace(',', '.')) tip = bill * TIP_RATIO print('Dricksa {} kr (betala totalt {} kr)'.format(tip, bill + tip)) <file_sep>/11_as1/circular_sector.py from math import pi radius = float(input('Radie: ').replace(',', '.')) degrees = float(input('Grader: ').replace(',', '.')) full_circle_area = pi * radius ** 2 sector_area = full_circle_area * (degrees / 360) print(f'Cirkelsektorns area är {sector_area}') <file_sep>/README.md # DI2006 Repository for assignments in the programming course DI2006 at Halmstad University <file_sep>/11_as1/laps.py from math import pi radius = float(input('Hur stor radie har banan? ').replace(',', '.')) length = float(input('Hur långt har du sprungit? ').replace(',', '.')) circumference = 2 * radius * pi laps = length / circumference print(f'Du har sprungit {laps} varv') <file_sep>/other/test.py import sys import os import time import importlib import stats sys.path.append(os.path.abspath('./DI2006')) prime = importlib.import_module('11_as2.prime') def test(func, iterations, *args): timings = [] for _ in range(iterations): start = time.perf_counter_ns() func(*args) timings.append(time.perf_counter_ns() - start) print(f''' {func} called {iterations} times Total:\t{sum(timings):>10} ns Mean:\t{stats.mean(timings):>10.2f} ns Stddev:\t{stats.stddev(timings):>10.2f} ns ''') test(prime.is_prime, 1000, 9999991) <file_sep>/11_as5/fragaslakten.py import os import re # Regexes for matching questions and answers in a file QUESTION_REGEX = re.compile(r'^\d+\. (.*)\(\d answers\)\n') ANSWER_REGEX = re.compile(r'^(.*) \((\d+) points\)\n') class Question(): '''Class representing a question in the family feud game''' def __init__(self, question): '''Create a new Question instance''' self.question = question self.answers = [] self.scores = [] self.correct = [] def add_answer(self, answer, score): '''Add an answer, with a corresponding score''' self.answers.append(answer) self.scores.append(score) self.correct.append(False) def print_answers(self): '''Print out the answers that the player got right, or just a number for the rest''' for i in range(len(self.answers)): if self.correct[i]: print(f'{self.answers[i]} - {self.scores[i]} points') else: print(i + 1) def match_answer(self, answer): '''Check if the provided answer is correct, and updates state accordingly''' for i in range(len(self.answers)): if answer.lower() == self.answers[i].lower(): self.correct[i] = True return True return False def num_answers(self): '''Gets the number of answers''' return len(self.answers) def get_score(self): '''Get the total score of the correct answers''' score = 0 for i in range(len(self.answers)): if self.correct[i]: score += self.scores[i] return score def load_questions(path = os.path.dirname(__file__)): '''Loads questions from a file''' # Add dir separator to path if necessary if not path.endswith(os.sep): path = path + os.sep questions = [] with open(path + 'questions.txt', 'r') as question_file: while line := question_file.readline(): # Create a new question if the line matches if match := QUESTION_REGEX.match(line): questions.append(Question(match.group(1))) # Otherwise, add it as an answer to the last created question elif match := ANSWER_REGEX.match(line): questions[-1].add_answer(match.group(1), int(match.group(2))) return questions def play_round(question): '''Play a round of the game''' print(question.question) for _ in range(question.num_answers()): question.print_answers() answer = input('==> ') if not question.match_answer(answer): print('\nSorry, wrong answer\n') return question.get_score() def main(): scores = [0, 0] questions = load_questions() rounds = 0 while True: # Ask how many rounds should be played and check if it's valid try: rounds = int(input('How many rounds should each player play? ')) if rounds in range(len(questions) // 2 + 1): break finally: print(f'Please input a value between 1 and {len(questions) // 2}') print() for i in range(rounds * 2): # Alternate between 0 and 1 player = i % 2 print(f'\nRound - {i + 1}\n') print('##############') print(f'Player 1: {scores[0]} points') print(f'Player 2: {scores[1]} points') print('##############\n') print(f'Player {player + 1} Plays') # Play a round and add to the player's score scores[player] += play_round(questions[i]) # Find out who won if scores[0] > scores[1]: print('Player 1 wins') elif scores[0] < scores[1]: print('Player 2 wins') else: print('It\'s a tie') print(f'{max(scores)} to {min(scores)}') main() <file_sep>/11_as2/pi.py # Calculates an approximation of pi using a mathematical formula. # More iterations make the result more accurate def calculate_pi(iterations): total = 0 for n in range(iterations): rational = ((-1) ** n) / (2 * n + 1) total += rational return total * 4 number = int(input('Hur många iterationer? ')) print(calculate_pi(number)) <file_sep>/11_as1/circle_length.py from math import pi radius = float(input('Radie: ').replace(',', '.')) circumference = 2 * radius * pi print(f'Omkrets: {circumference}') <file_sep>/11_as4/postkodmiljonaren.py import os INSTRUCTIONS = '''Welcome to 'Who wants to be a millionaire'! This came consists of 15 questions, that gets progressively harder, but also comes with greater rewards. As long as you answer correctly you earn more money, but if you answer wrong, you lose what you have earned. After questions 5 and 10 you get a guarantee that you will get at least that amount, even if you fail a later question. You are free to give up at any time (by answering with 'q') and you walk away with what you have earned. Press return to begin... ''' class Question(): '''Class for storing a question with muliple answers, whith functions for printing the question to stdout, validating the answer, and getting the correct answer''' def __init__(self, question, choices, correct_answer, prize): self.question = question self.choices = choices self.correct_answer = correct_answer self.prize = prize def print(self): '''Prints the question and alternatives''' print(self.question) for i in range(len(self.choices)): print(f'{i + 1}. {self.choices[i]}') def validate_answer(self, answer): '''Validate if the input answer is correct''' return int(answer) == self.correct_answer def get_correct(self): '''Return the correct answer''' return self.choices[self.correct_answer - 1] def load_questions(path = os.path.dirname(__file__)): '''Read from different files and construct the questions''' # Add dir separator to path if necessary if not path.endswith(os.sep): path = path + os.sep questions = [] # Open files for reading with open(path + 'questions.txt', 'r') as question_file, \ open(path + 'choices.txt', 'r') as choice_file, \ open(path + 'answers.txt', 'r') as answer_file, \ open(path + 'prize.txt', 'r') as prize_file: # Iterate through the files and construct questions for _ in range(15): question = question_file.readline().strip() choices = [] for _ in range(4): choices.append(choice_file.readline().strip()) answer = int(answer_file.readline().strip()) prize = int(prize_file.readline().strip()) questions.append(Question(question, choices, answer, prize)) return questions def get_answer(): '''Reads and validates user input''' while True: answer = input('==> ') if answer in ('q', '1', '2', '3', '4'): return answer print('Ogiltigt svar, försök igen') def main(): # Try to load questions, exit on failiure try: questions = load_questions() except (IOError, FileNotFoundError) as e: print('Failed to load questions:', e) exit(1) # At the beginning, the player isn't guaranteed any prize guaranteed = 0 # Print instructions and wait for the player to start the game input(INSTRUCTIONS) for index, question in enumerate(questions): # Print the question and wait for answer print(f'Question {index + 1} for {question.prize}') question.print() answer = get_answer() # Exit the game if the player demands, and shaw the prize for the previous question if answer == 'q': print(f'Thanks for playing, you get to take {0 if index == 0 else questions[index-1].prize} home.') break # Check if the answer is correct if question.validate_answer(answer): # If it's the last question if index == 14: print('YOU WON!!!!! YOU\'RE A MILLIONAIRE!!!!!!!!!!') else: print('Right answer!\n') # Update the guaranteed prize if at question 5 or 10 (index 4 resp 9) if index % 5 == 4: guaranteed = question.prize else: # Wrong answer, print out the prize, the correct answer and then exit print('Sorry, that is the wrong answer, ', end='') if guaranteed == 0: print('you will go home empty handed.') else: print(f'you get to take {guaranteed} home.') print(f'The right answer was {question.get_correct()}') break main() <file_sep>/11_as0/dollars.py EXCHANGE_RATE = 0.11 sek = float(input('Hur mycket pengar har du? ').replace(',', '.')) dollars = sek * EXCHANGE_RATE print('Du kan köpa ${:.2f}'.format(dollars)) <file_sep>/11_as2/prime.py import math import sys def prime_factors(num, start = 3): # Check if num is 2 - the only even prime if num == 2: return [2] # If num is even, it can't be a prime if num % 2 == 0: return [2] + prime_factors(num // 2) # Only need to test factors up to the sqare root of num largest_factor = int(math.sqrt(num)) # If num is divisible by any other number, it's not prime for n in range(start, largest_factor + 1, 2): if num % n == 0: return [n] + prime_factors(num // n, n) # If not divisible by any number, it must be a prime return [num] if not (len(sys.argv) > 1 and (number := int(sys.argv[1]))): number = int(input('Skriv ett tal: ')) factors = prime_factors(number) if len(factors) == 1: print(f'{number} är ett primtal') else: print(f'{number} faktoriseras till {factors}')<file_sep>/11_as2/vote_drink.py VOTING_AGE = 18 DRINKING_AGE = 21 # Function to count the number of elements in an array of numbers that are higher than # or equal to lower_limit def count_higher(array, lower_limit): count = 0 for number in array: if number >= lower_limit: count += 1 return count ages = [] while (user_input := input('Skriv in en ålder (eller q för att avsluta): ')) != 'q': try: ages.append(int(user_input)) except ValueError: print('Ogiltigt värde') print(f'Av sammanlagt {len(ages)} personer får {count_higher(ages, VOTING_AGE)} rösta\ och {count_higher(ages, DRINKING_AGE)} dricka') <file_sep>/11_as1/hypotenuse.py import math a = float(input('Längd katet 1: ').replace(',', '.')) b = float(input('Längd katet 2: ').replace(',', '.')) c = math.sqrt(a**2 + b**2) print(f'Hypotenusan är {c}') <file_sep>/mastermind/uielements.py COLORS = {'RED': '#ff0000', 'GREEN': '#00ff00', 'BLUE': '#0000ff', 'YELLOW': '#ffff00',\ 'BLACK': '#000000', 'WHITE': '#ffffff', 'CYAN': '#00ffff', 'MAGENTA': '#ff00ff'} class Peg: RADIUS = 10 def __init__(self, canvas, color, xpos, ypos, callback): self._canvas = canvas self.color = color self.x = xpos self.y = ypos self._callback = callback self._id = draw_circle(canvas, xpos, ypos, Peg.RADIUS, fill=COLORS[color], tags=('peg')) self._canvas.tag_bind(self._id, '<B1-Motion>', self.drag) self._canvas.tag_bind(self._id, '<ButtonRelease-1>', self.drop) self._frozen = False def drag(self, event): '''Move with the mouse cursor''' if not self._frozen: self.move_to(event.x, event.y) def drop(self, event): '''Signal to callback that the peg has been dropped and in what position''' if not self._frozen: self._callback.place_peg(event.x, event.y, self) def move_to(self, x, y): '''Move to the absolute coordinates''' self._canvas.move(self._id, x - self.x, y - self.y) self.x = x self.y = y def remove(self): '''Remove the peg from the board''' self._canvas.delete(self._id) def freeze(self): '''Freezes the peg so it can't be moved''' self._frozen = True class Grid(): def __init__(self, canvas, xpos, ypos, rows, columns, rowheight, colwidth): self._canvas = canvas self._x = xpos self._y = ypos self._cols = columns self._rows = rows self._rh = rowheight self._cw = colwidth self._h = rows * rowheight self._w = columns * colwidth def draw(self): '''Draw a grid according to specs''' for col in range(self._cols + 1): x = self._x + self._cw * col self._canvas.create_line(x, self._y, x, self._y + self._h, width=2, fill='#444444') for row in range(self._rows + 1): y = self._y + self._rh * row self._canvas.create_line(self._x, y, self._x + self._w, y, width=2, fill='#444444') def get_field_center(self, row, col): '''Returns the coordinates of the center of a field''' center_x = self._x + (col * self._cw) + self._cw // 2 center_y = (self._y + self._h) - ((row * self._rh) + self._rh // 2) return center_x, center_y def get_field(self, x, y): '''Get a field from coordinates, return None if outside the grid''' rel_x = x - self._x rel_y = y - self._y if rel_x < 0 or rel_x > self._w or rel_y < 0 or rel_y > self._h: return None col = rel_x // self._cw row = (self._rows - 1) - rel_y // self._rh return {'row': row, 'col': col} def draw_circle(canvas, xpos, ypos, radius, **kwargs): '''Draw a circle centered at (xpos, ypos) with specified radius''' x1 = xpos - radius y1 = ypos - radius x2 = xpos + radius y2 = ypos + radius return canvas.create_oval(x1, y1, x2, y2, **kwargs) <file_sep>/other/stats.py import math def mean(array): return sum(array) / len(array) def variance(array): m = mean(array) diffs = [(n - m) ** 2 for n in array] return mean(diffs) def stddev(array): return math.sqrt(variance(array)) <file_sep>/gamla_tentor/tenta-200810.py # Uppgift 1 a) pengar = int(input('Ange hur mycket pengar: ')) rest = pengar antal_hundralappar = rest // 100 rest = rest % 100 antal_femtiolappar = rest // 50 rest = rest % 50 antal_tjugolappar = rest // 20 rest = rest % 20 antal_enkronor = rest print(pengar, 'kronor motsvarar', antal_hundralappar, 'hundralappar,', antal_femtiolappar, 'femtiolappar,', antal_tjugolappar, 'tjugolappar och', antal_enkronor, 'enkronor') # Uppgift 1 b) # Med dessa kombinationer av operatorer är uttrycket True ((4 > 2) or (1.0 == 1.0)) ((4 > 2) or (1.0 < 1.0)) ((4 > 2) or (1.0 > 1.0)) ((4 > 2) or (1.0 <= 1.0)) ((4 > 2) or (1.0 >= 1.0)) ((4 > 2) or (1.0 != 1.0)) ((4 >= 2) or (1.0 == 1.0)) ((4 >= 2) or (1.0 < 1.0)) ((4 >= 2) or (1.0 > 1.0)) ((4 >= 2) or (1.0 <= 1.0)) ((4 >= 2) or (1.0 >= 1.0)) ((4 >= 2) or (1.0 != 1.0)) ((4 != 2) or (1.0 == 1.0)) ((4 != 2) or (1.0 < 1.0)) ((4 != 2) or (1.0 > 1.0)) ((4 != 2) or (1.0 <= 1.0)) ((4 != 2) or (1.0 >= 1.0)) ((4 != 2) or (1.0 != 1.0)) ((4 < 2) or (1.0 == 1.0)) ((4 < 2) or (1.0 <= 1.0)) ((4 < 2) or (1.0 >= 1.0)) ((4 <= 2) or (1.0 == 1.0)) ((4 <= 2) or (1.0 <= 1.0)) ((4 <= 2) or (1.0 >= 1.0)) ((4 == 2) or (1.0 == 1.0)) ((4 == 2) or (1.0 <= 1.0)) ((4 == 2) or (1.0 >= 1.0)) # Uppgift 2 a) x = int(input('Ange x: ')) y = sum(range(x**2)) print(y) # Uppgift 2 b) tal = int(input('Ange tal: ')) for x in range(1, tal + 1): for y in range(x, tal + 1): for z in range(y, tal + 1): if x**2 + y**2 == z**2: print(f'( {x} , {y} , {z} )') # Uppgift 3 a) def foo_bar(string): string2 = '' ending = '' for i in range(len(string)): if string[i] in ('a', 'e', 'i', 'o', 'u', 'y', 'å', 'ä', 'ö'): string2 += string[i] ending += string[i] else: string2 += string[i] + string[i] return string2 + ending # Uppgift 3 b) # i) Samma som värdet på var # ii) Värden som är > 1 eller < -1 # iii) Första gången bar() anropas med ett negativt tal returneras ett positivt, # därefter kommer loopen i foo() fortsätta med positiva värden # iv) def bar(value): return value * (value - 1) def foo(value): if value in range(-1, 2): return value while True: if value > 10: break else: value += bar(value) return value # Uppgift 4 # a) foo() öppnar en fil som specificeras i arg1 och skriver arg2 rader med 1:or, med lika många 1:or som # radens nummer (första raden räknas som 0, så den är tom) # bar() anropar först foo() med samma argument, därefter öppnar den samma fil för läsning och räknar # det totala antalet 1:or i filen, samt returnerar det värdet # b) Då kommer även radbrytningen (\n) räknas med i längden på raden # c) 6 # Uppgift 5 # a) Både foo() och bar() returnerar en dictionary med de bokstäver som förekommer både i string1 och string2 som nycklar, # och det sammanlagda antalet av dessa bostäver i string 1 och string2 som värden. # b) {'h': 4, 'e': 4, 'j': 4, ' ': 3} två gånger. (ordningen i den andra kan variera eftersom set inte garanterar ordning) # Uppgift 6 import math class Ball: def __init__(self, radius): self.radius = radius def compute_volume(self): return (4 * math.pi * self.radius**3) / 3 def __str__(self): return 'Bollen har volymen: ' + str(self.compute_volume()) boll = Ball(1) print(boll) # Uppgift 7 a) class KeyValue: def __init__(self, key, value): self.__key = key self.__value = int(value) def set_key(self, key): self.__key = key def set_value(self, value): self.__value = value def get_key(self): return self.__key def get_value(self): return self.__value def __str__(self): return f'{{{self.__key}: {self.__value}}}' def __repr__(self): return str(self) # Uppgift 7 b) import random def generate_map(string): letters = set(string) keyvalue_list = [] for letter in letters: rnd = random.randint(100, 999) while rnd in [kv.get_value() for kv in keyvalue_list]: rnd = random.randint(100, 999) keyvalue_list.append(KeyValue(letter, rnd)) return keyvalue_list print(generate_map('hej hej')) # Uppgift 8 class Deck: VALUES = ('2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace') SUITES = ('Clubs', 'Spades', 'Hearts', 'Diamonds') def __init__(self): self.__deck = set() self.reset() def reset(self): for suite in Deck.SUITES: for value in Deck.VALUES: self.__deck.add((value, suite)) def remove_card(self, card): if self.has_card(card): self.__deck.remove(card) def add_card(self, card): if Deck.is_valid_card(card): self.__deck.add(card) def has_card(self, card): return card in self.__deck def draw_random(self): if len(self.__deck) > 0: return self.__deck.pop() return None def __str__(self): return f'Deck of {len(self.__deck)} cards' @staticmethod def is_valid_card(card): return card is not None and \ len(card) == 2 and \ card[0] in Deck.VALUES and \ card[1] in Deck.SUITES @staticmethod def card_repr(card): if Deck.is_valid_card(card): return f'{card[0]} of {card[1]}' return None @staticmethod def compare_pairs(pair1, pair2): if Deck.compare_cards(*pair1) == 0: if Deck.compare_cards(*pair2) == 0: return Deck.compare_cards(pair1[0], pair2[0]) return 1 if Deck.compare_cards(*pair2) == 0: return -1 p1_sorted = sorted(pair1, key=lambda c: Deck.VALUES.index(c[0])) p2_sorted = sorted(pair2, key=lambda c: Deck.VALUES.index(c[0])) return Deck.compare_cards(p1_sorted[1], p2_sorted[1]) or Deck.compare_cards(p1_sorted[0], p2_sorted[0]) @staticmethod def compare_cards(card1, card2): c1_index = Deck.VALUES.index(card1[0]) c2_index = Deck.VALUES.index(card2[0]) if c1_index > c2_index: return 1 elif c1_index < c2_index: return -1 return 0 deck = Deck() pair1 = (deck.draw_random(), deck.draw_random()) pair2 = (deck.draw_random(), deck.draw_random()) result = Deck.compare_pairs(pair1, pair2) if result == 1: print(f'{tuple(map(Deck.card_repr, pair1))} beats {tuple(map(Deck.card_repr, pair2))}') elif result == -1: print(f'{tuple(map(Deck.card_repr, pair2))} beats {tuple(map(Deck.card_repr, pair1))}') else: print(f'{tuple(map(Deck.card_repr, pair1))} and {tuple(map(Deck.card_repr, pair2))} have the same value') <file_sep>/11_as2/factorial.py # Calculates the factorial of num def factorial(num): product = 1 for n in range(2, num + 1): product *= n return product number = int(input('Skriv ett tal: ')) print(f'{number}! = {factorial(number)}') <file_sep>/mastermind/main.py import tkinter as tk from tkinter import messagebox, ttk, N, W, S, E import random import uielements class MasterMind: BOARD_WIDTH = 360 BOARD_HEIGHT = 600 COLORS = ('RED', 'GREEN', 'BLUE', 'YELLOW', 'BLACK', 'WHITE', 'CYAN', 'MAGENTA') def __init__(self): # Create UI elements self.root = tk.Tk() self.root.title("Mastermind") self.root.option_add('*tearOff', 0) self.menu = tk.Menu(self.root) self.file_menu = tk.Menu(self.menu) self.window = ttk.Frame(self.root) self.window.grid(column = 0, row = 0, sticky=(N, W, E, S)) self.canvas = tk.Canvas(self.window, width=self.BOARD_WIDTH, height=self.BOARD_HEIGHT) self.peg_grid = uielements.Grid(self.canvas, \ self.BOARD_WIDTH - 250, self.BOARD_HEIGHT - 520, 10, 4, 50, 50) self.score_grid = uielements.Grid(self.canvas, 30, self.BOARD_HEIGHT - 520, 10, 1, 50, 50) self.check_button = ttk.Button(self.canvas, text="Check!", \ command=self.validate_line, state='disabled') # Create game state variables self.base_pegs = {} self.code_pegs = [] self.hint_pegs = [] self.placed_pegs = [[None, None, None, None] for _ in range(10)] self.round = 0 self.code = None self.start() self.root.mainloop() def start(self): '''Starts the app by placing UI elements and initialize game''' self.root['menu'] = self.menu self.menu.add_cascade(menu=self.file_menu, label='File') self.file_menu.add_command(label='New game', command=self.reset) self.file_menu.add_command(label='Exit', command=exit) self.canvas.grid(column=0, row=0, sticky=(N, W, E, S)) self.canvas.create_window(55, 40, window=self.check_button) self.peg_grid.draw() self.score_grid.draw() self.create_pegs() self.code = self.generate_code() def reset(self): '''Resets the game for a new round''' for row in self.placed_pegs: for i, peg in enumerate(row): if isinstance(peg, uielements.Peg): peg.remove() row[i] = None for peg in self.code_pegs: peg.remove() for peg in self.hint_pegs: self.canvas.delete(peg) self.code_pegs.clear() self.hint_pegs.clear() self.code = self.generate_code() self.round = 0 def create_pegs(self): '''Creates the pegs to choose from''' for color in self.COLORS: self.reset_peg(color) self.canvas.tag_raise('peg', 'all') def reset_peg(self, color): '''Create a new peg after one has been used''' self.base_pegs[color] = uielements.Peg(self.canvas, color, \ self.BOARD_WIDTH - 20, (self.BOARD_HEIGHT - 50) - self.COLORS.index(color) * 30, self) def place_peg(self, x, y, peg): '''Place a peg on the board''' field = self.peg_grid.get_field(x, y) self.reset_peg(peg.color) # Check if the peg is already placec (i.e. it's) # moved to a new field, and delete the old reference for i in range(len(self.placed_pegs[self.round])): if self.placed_pegs[self.round][i] is peg: self.placed_pegs[self.round][i] = None # Delete the peg if it's dropped in the wrong place if field is None or field['row'] != self.round: peg.remove() else: # Check if there's already a peg in the field and remove it if isinstance(self.placed_pegs[field['row']][field['col']], uielements.Peg): self.placed_pegs[field['row']][field['col']].remove() # Add the peg to the matrix and center it in the field self.placed_pegs[field['row']][field['col']] = peg peg.move_to(*self.peg_grid.get_field_center(field['row'], field['col'])) # Enable the check button if the row is full if not None in self.placed_pegs[self.round]: self.check_button.state(['!disabled']) else: self.check_button.state(['disabled']) def validate_line(self): '''Compares the row against the hidden code''' score = [] code = list(self.code) # Check for pegs that are exactly right for i, peg in enumerate(self.placed_pegs[self.round]): if peg.color == self.code[i]: score.append(2) code[i] = None # Check for pegs that have the right color but in the wrong place for peg in self.placed_pegs[self.round]: if peg.color in code: score.append(1) code.remove(peg.color) self.show_score(score) # Check if the game is won or lost if score == [2, 2, 2, 2]: self.victory() elif self.round == 9: self.loss() self.next_round() def show_score(self, score): '''Place black or white pegs to indicate retult''' center_x, center_y = self.score_grid.get_field_center(self.round, 0) for i, num in enumerate(score): x = center_x - (-1)**i * 10 y = center_y - (-1)**(i//2) * 10 color = uielements.COLORS['WHITE'] if num == 2: color = uielements.COLORS['BLACK'] self.hint_pegs.append(uielements.draw_circle(self.canvas, x, y, 5, fill=color)) def next_round(self): '''Move on to the next round''' for peg in self.placed_pegs[self.round]: peg.freeze() self.check_button.state(['disabled']) self.round += 1 def generate_code(self): '''Genereate a secret code''' code = [] for _ in range(4): code.append(random.choice(self.COLORS)) return tuple(code) def victory(self): '''The player has won''' self.show_code() messagebox.showinfo(message='You won!') def loss(self): '''The player has lost''' self.show_code() messagebox.showinfo(message='Sorry, you lost!') def show_code(self): '''Display the correct code''' for i, color in enumerate(self.code): x = self.peg_grid.get_field_center(0, i)[0] peg = uielements.Peg(self.canvas, color, x, 40, self) peg.freeze() self.code_pegs.append(peg) MasterMind() <file_sep>/other/list_primes.py import math def list_primes_upto(limit): initial = [2, 3, 5, 7, 11, 13] if limit <= initial[-1]: return initial for i in range(initial[-1] + 2, limit + 1, 2): root = int(math.sqrt(i)) prime = True for prime_number in initial: if prime_number > root: break if i % prime_number == 0: prime = False break if prime: initial.append(i) return initial def largest_prime(limit): if limit % 2 == 0: limit -= 1 for i in range(limit, 2, -2): root = int(math.sqrt(i)) is_prime = True for j in range(3, root + 1, 2): if i % j == 0: is_prime = False break if is_prime: return i return 2 <file_sep>/11_as1/candies.py money = float(input('Hur mycket pengar har du? ').replace(',', '.')) price = float(input('Hur mycket kostar godiset per styck? ').replace(',', '.')) number_of_candies = int(money / price) money_left = money % price print(f'Du kan köpa {number_of_candies} godisbitar, och har sedan {money_left:.2f} kr kvar') <file_sep>/11_as3/diet.py '''Program that uses various body measurements to calculate fitness level, and recommends nutrient intake and examples of food that satisfies the recommendations''' import math import random # Constants for gender MALE = 'M' FEMALE = 'F' # Constants for diffetent nutrients PROTEIN = 'protein' CARBOHYDRATES = 'carbohydrates' FAT = 'fat' # Different categories related to body fat ESSENTIAL = 'Essential fat' ATHLETE = 'Athlete' FITNESS = 'Fitness' ACCEPTABLE = 'Acceptable' OVERWEIGHT = 'Overweight' # Factors for calculating maintenance calories, based on level of activity on # on a scale from 1-5 ACTIVITY_LEVEL_FACTOR = { 1: 1.2, 2: 1.375, 3: 1.55, 4: 1.725, 5: 1.9 } # Recommended percentage of calories from different nutrients PERCENT_CALORIE_INTAKE = { PROTEIN: 0.4, CARBOHYDRATES: 0.3, FAT: 0.3 } # Calories per gram of the different nutrients CALORIE_CONTENT = { PROTEIN: 4, CARBOHYDRATES: 4, FAT: 9 } # Example food, with how many percent of the weight constitutes nutrients EXAMPLE_FOOD = { PROTEIN: [ ( 'Chicken breast', 0.31 ) ], CARBOHYDRATES: [ ( 'Sweet potato', 0.2 ) ], FAT: [ ( 'Olive oil', 1 ) ] } class FitnessProfile(): '''Class for calculating various measurements related to fitness and diet''' def __init__(self, gender, activity_level, height, weight, neck, waist, hip=None): self.gender = gender self.activity_level = activity_level self.height = height self.weight = weight self.neck = neck self.waist = waist if gender == FEMALE and hip is None: raise ValueError('Hip measurement required') self.hip = hip def fat_percent(self): '''Calculates the fat percent dependant on gender and different measurements''' if self.gender == MALE: return 495 / (1.0324 - 0.19077*math.log10(self.waist-self.neck) + 0.15456*math.log10(self.height)) - 450 return 495 / (1.29579 - 0.35004*math.log10(self.waist+self.hip-self.neck) + 0.221*math.log10(self.height)) - 450 def body_fat_category(self): '''Use fat percent to assign different categories''' body_fat_percent = self.fat_percent() if self.gender == FEMALE: if body_fat_percent < 14: return ESSENTIAL if body_fat_percent <= 20: return ATHLETE if body_fat_percent <= 24: return FITNESS if body_fat_percent <= 31: return ACCEPTABLE else: if body_fat_percent < 6: return ESSENTIAL if body_fat_percent <= 13: return ATHLETE if body_fat_percent <= 17: return FITNESS if body_fat_percent <= 24: return ACCEPTABLE return OVERWEIGHT def base_metabolic_rate(self): '''Calculates base metabolic rate''' return 370 + 21.6 * (1 - (self.fat_percent() / 100)) * self.weight def maintenance_calories(self): '''Use base metabolic rate and activity level to calculate maintenance calories per day''' return self.base_metabolic_rate() * ACTIVITY_LEVEL_FACTOR[self.activity_level] def adjusted_maintenance_calories(self): '''Adjust number of calories if person's body fat category is ESSENTIAL or OVERWEIGHT''' category = self.body_fat_category() calories = self.maintenance_calories() if category == ESSENTIAL: return calories * 1.15 if category == OVERWEIGHT: return calories * 0.85 return calories def recommended_intake(self, nutrient): '''Calculates recommended intake of specified nutrient''' calories_from_nutrient = self.adjusted_maintenance_calories() * PERCENT_CALORIE_INTAKE[nutrient] return calories_from_nutrient / CALORIE_CONTENT[nutrient] def example_food(self, nutrient): '''Gives an example of food that satisfies the recommended intake''' food_source = EXAMPLE_FOOD[nutrient][random.randint(0, len(EXAMPLE_FOOD[nutrient]) - 1)] food_amount = self.recommended_intake(nutrient) / food_source[1] return (food_source[0], food_amount) def create_profile(): gender = read_input('Your gender (M/F): ', lambda s: s.upper(), lambda s: s in (MALE, FEMALE)) activity_level = read_input('Your activity level (1-5): ', int, lambda n: n in range(1, 6)) print('Input your measurements') height = read_input('Length: ', int) weight = read_input('Weight: ', float) neck = read_input('Neck: ', int) waist = read_input('Waist: ', int) hip = None if gender == FEMALE: hip = read_input('Hip: ', int) return FitnessProfile(gender, activity_level, height, weight, neck, waist, hip) def read_input(message, conversion=str, validation=(lambda _: True)): while True: value = input(message) try: converted = conversion(value) if validation(converted): return converted print('Ogiltigt värde') except ValueError: print('Ogiltigt värde') profile = create_profile() print(f'Your body fat percent is {profile.fat_percent():.0f}') print(f'This puts you in the category {profile.body_fat_category()}') print(f'Your basal metabolic rate is {profile.base_metabolic_rate():.0f}') print(f'Your maintenance calories is {profile.maintenance_calories():.0f}') print(f'Your adjusted maintenance calories is {profile.adjusted_maintenance_calories():.0f}') print('#######################') print(f'Your recommended protein intake is {profile.recommended_intake(PROTEIN):.0f} grams') print(f'Your recommended carb intake is {profile.recommended_intake(CARBOHYDRATES):.0f} grams') print(f'Your recommended fat intake is {profile.recommended_intake(FAT):.0f} grams') print('#######################') example_protein = profile.example_food(PROTEIN) example_carbs = profile.example_food(CARBOHYDRATES) example_fat = profile.example_food(FAT) print('To satisfy your recommended nutrient intake, you could eat for example:') print(f'{example_protein[1]:.0f} grams of {example_protein[0]},') print(f'{example_carbs[1]:.0f} grams of {example_carbs[0]} and') print(f'{example_fat[1]:.0f} grams of {example_fat[0]}') <file_sep>/11_as2/perfect.py def is_perfect(num): sum_of_factors = 0 # Calculate sum of numbers that divide num for n in range(1, num): if num % n == 0: sum_of_factors += n # Return whether the sum of the factors equals num return sum_of_factors == num number = int(input('Skriv ett tal: ')) if is_perfect(number): print(f'{number} är ett perfekt tal') else: print(f'{number} är inte ett perfekt tal')
81a2849fc19d83df4f1c61b5ffc34a8e5c0fb1cc
[ "Markdown", "Python" ]
23
Python
pacive/DI2006
965b89d02550a7f37c07584ce3d3347eca47eed2
0912c953237e5808d8efded00cae63d5aa81923f
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jan 7 11:53:07 2020 @author: Jaspreetsingh_Tuli """ def findPrefix(pattern, prefixList): patternLength = len(pattern) prefixLength = 0 prefixList[0] = 0 for i in range(1, patternLength): if(pattern[i] == pattern[prefixLength]): prefixLength +=1 prefixList[i] = prefixLength else: if prefixLength != 0: prefixLength = prefixList[prefixLength-1] i -=1 else: prefixList[i] = 0 return prefixList def kmp(text, pattern): textLength = len(text) patternLength = len(pattern) prefixList = [0]*patternLength findPrefix(pattern, prefixList) i = 0 j = 0 indexList = [] while(i<textLength): if(text[i] == pattern[j]): i+=1 j+=1 if j == patternLength: indexList.append(i-j) j = prefixList[j-1] elif i < textLength and pattern[j] != text[i]: if j!=0: j = prefixList[j-1] else: i+=1 return indexList print(kmp("ashishahgdsjgajdgidhgikadhgaid hshivam kahdkahd shiuahsodna","shi")) print(kmp("gajsdabafgliablzbffaiiiaasweajs","ajs"))<file_sep># -*- coding: utf-8 -*- """ Created on Tue Jan 7 13:24:00 2020 @author: Jaspreetsingh_Tuli """ def rabin_karp(text, pattern, prime): text_length = len(text) pattern_length = len(pattern) pattern_hash = 0 text_hash = 0 index_list = [] for i in range(0,pattern_length): pattern_hash += ord(pattern[i]) * (prime ** i) for i in range (0, (text_length - pattern_length)+1): text_hash = 0 for k in range(0, pattern_length): text_hash += ord(text[i+k]) * (prime ** k) if pattern_hash == text_hash: flag = True for j in range (0, pattern_length): if text[i+j] != pattern[j]: flag=False if(flag): index_list.append(i) return index_list print(rabin_karp("sshisahshi","shi",3))<file_sep># Design And Analysis Of Algorithms This repository is an attempt to solve the most common algorithmic problems encountered during the course **DAA**. Designing of algorithms is done in Java <file_sep>import java.util.Scanner; public class ShortestPath { Scanner sc = new Scanner(System.in); final int max = 10; final int INFINITY = 1000; int w[][]; int n_size; int p[]; void in_dat() { System.out.println("\n\t Multi-Stage Graph \n"); System.out.println("\n Enter the number of nodes : "); n_size = sc.nextInt(); int i; for(i=0;i<n_size;i++) { w[i][i] = 0; for(int j=i+1;j<n_size;j++) { System.out.println("Enter the weight of edge "+(65+i)+" to " +(65+j)+": "); w[i][j] = sc.nextInt(); w[j][i] = 0; } } } void dis_dat() { System.out.println("\n The Path adjacent matrix \n"); System.out.println("\n "); for(int i=0;i<n_size;i++) { System.out.println("\n"); for(int j=0;j<n_size;j++) System.out.println("\t"+w[i][j]); } } }
63023636bc4b97b311ea670cd3433f8f6994613a
[ "Markdown", "Java", "Python" ]
4
Python
JaspreetRFSingh/DesignAndAnalysisOfAlgorithms
f9516b5de14e6df5df6dd0c0d258fa6e80dfb464
5dc76d40387554bb851e82be232ee2e4dd5516db
refs/heads/master
<file_sep># RFID reader Read and display 125 kHz RFID tags using Arduino, [RDM-6300](https://roboshop.spb.ru/rfid-RDM6300) and [1602 display](https://roboshop.spb.ru/display/LCD-keypad-shield). <file_sep>#include <Arduino.h> #include <Wire.h> #include <LiquidCrystal.h> #include <rdm6300.h> #define RDM6300_RX_PIN 2 #define READ_LED_PIN 13 Rdm6300 rdm6300; LiquidCrystal lcd(8, 9, 4, 5, 6, 7); void setup() { Serial.begin(9600); lcd.begin(16, 2); lcd.print("Ready..."); rdm6300.begin(RDM6300_RX_PIN); Serial.begin(9600); while (!Serial) {} } uint32_t last_tag; void loop() { if (rdm6300.update()) { uint32_t tag = rdm6300.get_tag_id(); if (tag != last_tag) { char out [16]; sprintf(out, "%8.8lX", tag); lcd.clear(); lcd.setCursor(0, 0); lcd.print("CUR: "); lcd.setCursor(5, 0); lcd.print(out); lcd.setCursor(0, 1); lcd.print("REF: 001FFF0D"); Serial.println(out); last_tag = tag; } } delay(10); /* lcd.noBacklight(); lcd.setCursor(0, 0); lcd.print("HELLO"); delay(2000); lcd.setCursor(0, 1); lcd.print("WORLD"); delay(2000); lcd.backlight(); */ }
65649be08408bfc4f32bf22addcbea60aa2746ab
[ "Markdown", "C++" ]
2
Markdown
h4/rfid-reader
3a49bac269ae66d37fb0e8b22ed8d0c7ee54aad1
02b957eb10e7f8be42351636c473b55c024c54a5
refs/heads/master
<file_sep>package asd.lab3; public class Main { public static void main(String[] args) { Tester tester = new Tester(); tester.testAverage(new RBTree(), 100_000); tester.testAverage(new AVLTree(), 100_000); tester.testWorst(new RBTree(), 100_000); tester.testWorst(new AVLTree(), 100_000); } } <file_sep>package asd.lab3; public class AVLTree implements DataStructure<AVLTree.AVLNode> { public static class AVLNode { int key; int height; AVLNode left; AVLNode right; AVLNode(int key) { this.key = key; } } private AVLNode root; @Override public AVLNode search(int key) { AVLNode current = root; while (current != null) { if (current.key == key) { break; } current = current.key < key ? current.right : current.left; } return current; } @Override public void insert(int key) { root = insert(root, key); } @Override public void delete(int key) { root = delete(root, key); } private AVLNode insert(AVLNode node, int key) { if (node == null) { return new AVLNode(key); } else if (node.key > key) { node.left = insert(node.left, key); } else if (node.key < key) { node.right = insert(node.right, key); } return rebalance(node); } private AVLNode delete(AVLNode node, int key) { if (node == null) { return node; } else if (node.key > key) { node.left = delete(node.left, key); } else if (node.key < key) { node.right = delete(node.right, key); } else { if (node.left == null || node.right == null) { node = (node.left == null) ? node.right : node.left; } else { AVLNode mostLeftChild = mostLeftChild(node.right); node.key = mostLeftChild.key; node.right = delete(node.right, node.key); } } if (node != null) { node = rebalance(node); } return node; } private AVLNode mostLeftChild(AVLNode node) { AVLNode current = node; while (current.left != null) { current = current.left; } return current; } private AVLNode rebalance(AVLNode z) { updateHeight(z); int balance = getBalance(z); if (balance > 1) { if (height(z.right.right) > height(z.right.left)) { z = rotateLeft(z); } else { z.right = rotateRight(z.right); z = rotateLeft(z); } } else if (balance < -1) { if (height(z.left.left) > height(z.left.right)) { z = rotateRight(z); } else { z.left = rotateLeft(z.left); z = rotateRight(z); } } return z; } private AVLNode rotateRight(AVLNode y) { AVLNode x = y.left; AVLNode z = x.right; x.right = y; y.left = z; updateHeight(y); updateHeight(x); return x; } private AVLNode rotateLeft(AVLNode y) { AVLNode x = y.right; AVLNode z = x.left; x.left = y; y.right = z; updateHeight(y); updateHeight(x); return x; } private void updateHeight(AVLNode n) { n.height = 1 + Math.max(height(n.left), height(n.right)); } private int height(AVLNode n) { return n == null ? -1 : n.height; } public int getBalance(AVLNode n) { return (n == null) ? 0 : height(n.right) - height(n.left); } } <file_sep>package asd.lab3; public interface DataStructure<U> { void insert(int element); void delete(int element); U search(int element); }
a7ae5ad824c2402236155f86ef3e1f586da465ef
[ "Java" ]
3
Java
PavloLuchyk/ASD-Lab3
de5c4abc7ba3cef6bbe8f6e1e29d633acf0d31b2
e9586c49198d099d7dae35d40202308ca86923b5
refs/heads/master
<repo_name>enroll/enroll<file_sep>/app/controllers/reservations_controller.rb class ReservationsController < ApplicationController before_filter :authenticate_user!, only: [:show] before_filter :require_course! def new add_body_class('landing-page') @reservation = @course.reservations.build @user = current_user || User.new if @user.enrolled_for?(@course) redirect_to landing_page_path(@course.url) end end def create add_body_class('landing-page') token = params[:reservation].try(:[], :stripe_token) # TODO: There's no point in storing Stripe token to reservation, # it will expire before we charge it. Stripe recommends using that # token to create a customer, and charge that customer later. # https://stripe.com/docs/tutorials/charges # We already have login in place that utilizes User#stripe_customer_id # to charge cards. (course.rb) # We're gonna create customer like they recommend below... @reservation = @course.reservations.build @user = current_user unless @user @user = User.new(user_params) if @user.save sign_in(@user) else return render :new end end @reservation.student = @user if @reservation.save Resque.enqueue UserUpdateStripeCustomer, @user.id, token Event.create_event(Event::STUDENT_ENROLLED, course: @course, user: current_user) redirect_to course_reservation_path(@course, @reservation) else render :new end end def show add_body_class('landing-page') @reservation = @course.reservations.find(params[:id]) @student = @reservation.student end private def require_course! @course = Course.find(params[:course_id]) @logo = @course.logo_if_present unless @course flash[:error] = "Couldn't find the course you were looking for" return redirect_to root_url end end def user_params params.require(:user).permit(:name, :email, :password) end end <file_sep>/db/migrate/20140202221710_add_email_to_marketing_tokens.rb class AddEmailToMarketingTokens < ActiveRecord::Migration def change add_column :marketing_tokens, :email, :string end end <file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. Enroll::Application.config.session_store :cookie_store, key: '_enroll_session', domain: :all <file_sep>/spec/models/cash_register_spec.rb require 'spec_helper' describe CashRegister do let(:course) { build(:course) } describe "#revenue" do context "paid course" do before do 10.times { create(:reservation, course: course) } end it "returns total value of course tickets sold with a different amount" do course.price_per_seat_in_cents = 5000 # $50 course.save CashRegister.revenue(course).should == 50000 end it "returns total value of course tickets sold ignoring fees" do course.price_per_seat_in_cents = 10000 # $100 course.save CashRegister.revenue(course).should == 100000 # $1,000 end end context "free course" do before do course.price_per_seat_in_cents = 0 course.save 10.times { create(:reservation, course: course) } end it "returns zero for free courses" do CashRegister.revenue(course).should == 0 end it "returns zero even if price per seat is not set" do course.price_per_seat_in_cents = nil CashRegister.revenue(course).should == 0 end end end describe "#credit_card_fees" do context "paid course" do before do course.price_per_seat_in_cents = 10000 # $100 course.save 10.times { create(:reservation, course: course) } end it "returns credit card fees" do # Course revenue: $1,000 # CC percentage fees: $1,000 x 2.9% = $29 # CC transaction fees: 10 tix x $0.30 = $3 CashRegister.credit_card_fees(course).should == 3200 # $32 end end context "free course" do before do course.price_per_seat_in_cents = 0 course.save 10.times { create(:reservation, course: course) } end it "returns zero for free courses" do CashRegister.credit_card_fees(course).should == 0 end end end describe "#gross_profit" do context "paid course" do before do course.price_per_seat_in_cents = 10000 # $100 course.save 10.times { create(:reservation, course: course) } end it "returns enroll's cut of the revenue (gross profit)" do # Course revenue: $1,000 # Enroll service fees: $1,000 x 3.1% = $31 CashRegister.gross_profit(course).should == 3100 # $31 end end context "free course" do before do course.price_per_seat_in_cents = 0 course.save 10.times { create(:reservation, course: course) } end it "returns zero for free courses" do CashRegister.gross_profit(course).should == 0 end end end describe "#instructor_payout_amount" do context "paid course" do before do course.price_per_seat_in_cents = 10000 # $100 course.save 10.times { create(:reservation, course: course) } end it "returns the instructor's cut of the course" do # Course revenue: $1,000 # Enroll service fees: $1,000 x 3.1% = $31 # CC percentage fees: $1,000 x 2.9% = $29 # CC transaction fees: 10 tix x $0.30 = $3 # Instructor payout: $1,000 - $31 - $29 - $3 = $937 CashRegister.instructor_payout_amount(course).should == 93700 # $937 end end context "free course" do before do course.price_per_seat_in_cents = 0 course.save 10.times { create(:reservation, course: course) } end it "returns zero for free courses" do CashRegister.instructor_payout_amount(course).should == 0 end end end end<file_sep>/spec/controllers/accounts_controller_spec.rb require 'spec_helper' describe AccountsController do let(:user) { create(:user) } describe 'GET edit' do before(:each) do sign_in user end it 'renders the edit page' do get :edit response.should be_success response.should render_template('edit') end it 'edits the current user' do get :edit assigns[:user].should == user end context 'when not logged in' do before(:each) do sign_out user end it 'redirects the user to the login page' do get :edit response.should be_redirect response.should redirect_to(new_user_session_path) end end end describe 'PUT update' do context 'when successful' do before(:each) do sign_in user put :update, user: { email: '<EMAIL>', name: '<NAME>' } end it 'updates the current user email' do user.reload.email.should == '<EMAIL>' end it 'updates the current user name' do user.reload.name.should == '<NAME>' end it 'redirects to the edit page' do response.should be_redirect response.should redirect_to(edit_account_path) end it 'displays a success message' do flash[:success].should_not be_blank end end context 'when unsuccessful' do before(:each) do sign_in user User.any_instance.stubs(:update_attributes).returns(false) put :update, user: { email: '<EMAIL>' } end it 're-renders the form' do response.should render_template('edit') end it 'displays an error message' do flash[:error].should_not be_blank end end context 'when not logged in' do it 'redirects the user to the login page' do put :update, user: { email: '<EMAIL>' } response.should be_redirect response.should redirect_to(new_user_session_path) end end end end <file_sep>/Rakefile # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) require 'resque/tasks' Enroll::Application.load_tasks task "resque:preload" => :environment task "resque:setup" do ENV['QUEUE'] = '*' end # Rake::Task['default'].prerequisites.clear # Rake::Task['default'].clear task default: [:spec, :teaspoon]<file_sep>/app/controllers/accounts_controller.rb class AccountsController < ApplicationController before_filter :authenticate_user!, except: [:restore] def edit @user = current_user end def update @user = current_user if @user.update_attributes(user_params) flash[:success] = "Account updated successfully." redirect_to edit_account_path else flash.now[:error] = "Unable to update your user account. Sorry about that." render :edit end end def restore if request.post? email = params[:user][:email] user = User.where(email: email).first if user user.send_reset_password_instructions flash.now[:notice] = "Link was sent to your email #{email}" else flash.now[:error] = "Cannot find user with email #{email}" end end end private def user_params params.require(:user).permit(:email, :name, :password) end end <file_sep>/config/initializers/resque.rb require 'enroll' require 'resque/server' Resque.redis = Enroll.redis Resque.inline = Rails.env.development? Resque::Server.use AuthenticatedRack <file_sep>/app/controllers/admin/emails_controller.rb class Admin::EmailsController < ApplicationController http_basic_authenticate_with :name => "enroll", :password => "<PASSWORD>" def index @tokens = MarketingToken.all end def new @available_events = ["Marketing Email #2", "Initial Marketing Email"] end def create emails = emails_from_text(params[:email][:emails]) emails.each do |recipient| token = MarketingToken.where(email: recipient).first || \ MarketingToken.generate!(email: recipient) content = params[:email][:content] content = self.add_token_to_content(content, token) options = { from: params[:email][:sender], to: recipient, subject: params[:email][:subject], content: content } options[:cc] = "<EMAIL>" if params[:email][:cc_us].to_i == 1 GenericMailer.generic_mail(options).deliver! mixpanel_set(token.distinct_id, {email: recipient}) mixpanel_track_event(params[:email][:event], {distinct_id: token.distinct_id}) end flash[:notice] = "#{emails.length} emails were sent!" redirect_to new_admin_email_path end protected def emails_from_text(text) emails = text.split(/[\n,]+/) emails.reject! { |email| email == "," } emails.map! { |email| email.sub(/^.*<(.*?)>.*$/, '\1').strip } emails end def add_token_to_content(content, token) content.gsub 'http://enroll.io', \ 'http://enroll.io/?i=%s' % [token.token] end end<file_sep>/app/jobs/user_update_stripe_customer.rb class UserUpdateStripeCustomer @queue = :notifications def self.perform(user_id, card_token) User.find(user_id).update_stripe_customer(card_token) end end<file_sep>/db/migrate/20130726023227_create_users.rb class CreateUsers < ActiveRecord::Migration def change rename_table :instructors, :users end end <file_sep>/app/controllers/avatars_controller.rb class AvatarsController < ApplicationController before_filter :authenticate_user! def new @user = current_user end def create @user = current_user avatar_params = params.require(:user).permit(:avatar) current_user.update_attributes(avatar_params) flash.now[:notice] = "Photo was updated." render 'new' end end <file_sep>/app/helpers/users_helper.rb module UsersHelper def mailto_users(users) joined_emails = users.map(&:email).join(',') "mailto:#{joined_emails}" end end<file_sep>/db/migrate/20140210151957_add_link_resources.rb class AddLinkResources < ActiveRecord::Migration def change add_column :resources, :resource_type, :string add_column :resources, :link, :string end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception protected helper_method :body_classes def body_classes classes = (@body_classes || []) + [controller_name, action_name, namespace_name] classes.join(' ') end def add_body_class(klass) @body_classes ||= [] @body_classes << klass end def namespace_name self.class.to_s.split("::").first.downcase end # Courses def find_course_as_instructor_by_course_id! @course = current_user.courses_as_instructor.find(params[:course_id]) rescue ActiveRecord::RecordNotFound redirect_to root_path end def find_course_as_student!(id) @course = current_user.courses_as_student.find(id) rescue ActiveRecord::RecordNotFound redirect_to root_path end def find_course_as_student_by_id! find_course_as_student!(params[:id]) end def find_course_as_student_by_course_id! find_course_as_student!(params[:course_id]) end # Mixpanel def mixpanel return nil unless Enroll.mixpanel_token unless @mixpanel @mixpanel = Mixpanel::Tracker.new(Enroll.mixpanel_token) @mixpanel.set visitor_id, {email: current_user.email} if current_user end @mixpanel end def mixpanel_track_event(event, options={}) return unless mixpanel distinct_id = options[:distinct_id] || visitor_id mixpanel.track(event, {distinct_id: distinct_id}) end def mixpanel_set(id, args) return unless mixpanel mixpanel.set(id, args) end def visitor_id @visitor_id ||= if current_user if current_user.visitor_id current_user.visitor_id else current_user.visitor_id = generate_visitor_id! current_user.save!(validate: false) current_user.visitor_id end else generate_visitor_id! end @visitor_id end def generate_visitor_id! if cookies[:visitor_id] cookies[:visitor_id] else id = SecureRandom.base64 cookies.permanent[:visitor_id] = id id end end # Markdown def setup_markdown @markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true) end end <file_sep>/db/migrate/20130704193628_add_course_fields.rb class AddCourseFields < ActiveRecord::Migration def change add_column :courses, :tagline, :string add_column :courses, :course_starts_at, :datetime add_column :courses, :course_ends_at, :datetime add_column :courses, :description, :text end end <file_sep>/docs/tables.md This isn't intended as something we should implement all at once, but rather a sort of textual E-R diagram to guide us and start discussions (w/r/t mapping the frontend and future flexibility) Users ===== name email Authentications (Omniauth standard) =================================== user_id provider uid UserLinks ========= user_id service_name (aka twitter) service_url (aka http://twitter.com/zapnap) Instructors =========== user_id course_id title biography Courses ======= name published_at course_start_date campaign_end_date venue_id <sup>1</sup> instructor_id description min_seats max_seats price_per_seat <sup>2</sup> short_name (slug) custom_domain Venues <sup>1</sup> ====== name address city state zip Reservations ============ course_id user_id canceled_at completed_at payment_fields <sup>3</sup> Notes ===== 1. Should Venue be a separate table? (promotes re-use, engagement with co-working spaces, etc). Otoh, simpler to iterate / edit if we keep it in the same table. 2. We probably want to allow for the possibility of tiered seats / different reservation levels at some point. 3. Payment fields are TBD. We probably hold a reference to an authorization. Will also need a field to indicate if the payment has been captured. We probably want a separate table for this (payments?) <file_sep>/config/initializers/stripe.rb stripe_config = YAML.load_file(Rails.root.join('config', 'stripe.yml').to_s)[Rails.env] Rails.configuration.stripe = { :publishable_key => stripe_config["publishable_key"], :secret_key => stripe_config["secret_key"] } Stripe.api_key = Rails.configuration.stripe[:secret_key]<file_sep>/lib/enroll/config.rb module Enroll module Config # Where to find the Redis server. # # We use RedisToGo in production on Heroku. def redis_url @redis_url ||= ENV["REDISTOGO_URL"] || ENV['GH_REDIS_URL'] || ENV['REDIS_URL'] || 'redis://127.0.0.1:6379/' end attr_writer :redis_url # The Redis client. def redis @redis ||= begin uri = URI.parse(redis_url) Redis.new(:host => uri.host, :port => uri.port, :password => uri.password) end end attr_writer :redis # Google Analytics Tracking Code def ga_tracking_id @ga_config ||= YAML.load_file(Rails.root.join('config', 'ga.yml').to_s)[Rails.env] @ga_tracking_id ||= @ga_config["tracking_id"] end attr_writer :ga_tracking_id # Google Analytics Domain def ga_domain @ga_config ||= YAML.load_file(Rails.root.join('config', 'ga.yml').to_s)[Rails.env] @ga_domain ||= @ga_config["domain"] end attr_writer :ga_domain # MixPanel def mixpanel_token @mixpanel_config ||= YAML.load_file(Rails.root.join('config', 'mixpanel.yml').to_s)[Rails.env] @mixpanel_token ||= @mixpanel_config["token"] end # Amazon S3 def s3_config @s3_config ||= YAML.load_file(Rails.root.join('config', 's3.yml').to_s)[Rails.env] end def s3_config_for(bucket) { bucket: Enroll.s3_config["bucket"][bucket], access_key_id: Enroll.s3_config["access_key_id"], secret_access_key: Enroll.s3_config["secret_access_key"] } end end end <file_sep>/app/models/course_schedule.rb class CourseSchedule < ActiveRecord::Base belongs_to :course, inverse_of: :schedules validates :course_id, presence: true # validates :date, presence: true # validates :starts_at, presence: true # validates :ends_at, presence: true TIME_FORMAT = "%I:%M%p" def as_json(options = {}) { identifier: date, label: date, starts_at: starts_at, ends_at: ends_at, is_skipped: is_skipped } end def starts_at midnight_seconds_to_str(self[:starts_at]) end def starts_at=(value) self[:starts_at] = str_to_midnight_seconds(value) end def starts_at_time Time.parse(date.to_s + " " + starts_at) rescue nil end def ends_at midnight_seconds_to_str(self[:ends_at]) end def ends_at=(value) self[:ends_at] = str_to_midnight_seconds(value) end def ends_at_time Time.parse(date.to_s + " " + ends_at) rescue nil end def range_str if starts_at && ends_at "#{starts_at} - #{ends_at}" elsif starts_at "starting #{starts_at}" elsif ends_at "ends #{ends_at}" end end protected def str_to_midnight_seconds(str) return nil unless str.present? time = Time.strptime(str, TIME_FORMAT) time.seconds_since_midnight end def midnight_seconds_to_str(seconds) return nil unless seconds time = Time.now.midnight + seconds.seconds time.strftime(TIME_FORMAT).downcase end end<file_sep>/spec/models/user_spec.rb require 'spec_helper' describe User do let(:user) { build(:user) } it { should have_many(:reservations) } it { should have_many(:courses_as_student) } it { should have_many(:courses_as_instructor) } it { should validate_presence_of(:email) } describe '.courses' do before(:each) do user.save @instructor_course = create(:course, instructor: user) @student_course = create(:course) create(:reservation, student: user, course: @student_course) end it 'includes courses the user is taking as a student' do user.courses.should include(@student_course) end it 'includes courses that the user is teaching' do user.courses.should include(@instructor_course) end end describe '#display_title' do it 'is the same as the user email' do user.display_title.should == user.email end end describe "#staff?" do it 'returns true' do user.staff?.should be_true end end describe "#reservation_for_course" do it 'returns a reservation for the course if it exists' do user.save course = create(:course) reservation = create(:reservation, course: course, student: user) user.reservation_for_course(course).should == reservation end it 'returns nil if no reservation for the course exists' do course = create(:course) user.reservation_for_course(course).should == nil end end describe "#instructor?" do it 'returns true if user is teaching any courses' do user.save create(:course, instructor: user) user.should be_instructor end it 'returns true if user is teaching a course and attending a course' do user.save create(:course, instructor: user) create(:reservation, student: user) user.should be_instructor end it 'returns false if user is not teaching any courses' do user.save create(:reservation, student: user) user.should_not be_instructor end end describe "#student?" do it 'returns true if user is attending any courses' do user.save create(:reservation, student: user) user.should be_student end it 'returns true if user is attending a course and teaching a course' do user.save create(:reservation, student: user) create(:course, instructor: user) user.should be_student end it 'returns false if user is not attending any courses' do user.save create(:course, instructor: user) user.should_not be_student end end describe "#save_payment_settings!" do before { user.email = "<EMAIL>" } it 'create a Stripe recipient' do Stripe::Recipient.expects(:create).with({ name: "<NAME>", type: "individual", email: "<EMAIL>", bank_account: "abc123" }) user.save_payment_settings!({ name: "<NAME>", stripe_bank_account_token: "abc123" }) end it 'sets the stripe_recipient_id for the user' do Stripe::Recipient.stubs(:create).returns(stub(id: "some-recipient-id")) user.save_payment_settings!({ name: "<NAME>", stripe_bank_account_token: "abc123" }) user.stripe_recipient_id.should == "some-recipient-id" end it 'sets the name for the user' do Stripe::Recipient.stubs(:create).returns(stub(id: "some-recipient-id")) user.save_payment_settings!({ name: "<NAME>", email: "<EMAIL>" }) user.name.should == "<NAME>" end end describe "#update_stripe_customer" do let :customer do stub(deleted: false, id: 'cus1') end context "existing stripe customer" do before do user.stripe_customer_id = 'cus1' customer.stubs(:card=) customer.stubs(:save) Stripe::Customer.stubs(:retrieve).with('cus1').returns(customer) end it "does NOT create a new customer" do Stripe::Customer.expects(:create).never user.update_stripe_customer('card1') user.stripe_customer_id.should == 'cus1' end it "changes card token" do customer.expects(:card=).with('card2') customer.expects(:save) user.update_stripe_customer('card2') end end context "creating new stripe customer" do before do Stripe::Customer.stubs(:create).returns(customer) user.stripe_customer_id = nil end it "creates the customer and then does NOT update it" do customer.expects(:card=).never customer.expects(:save).never Stripe::Customer.expects(:create).returns(customer) user.update_stripe_customer('card4') end end end end <file_sep>/app/models/course.rb class Course < ActiveRecord::Base DEFAULT_DESCRIPTION = [["About the course", "Basic details here..."], ["Prerequisites", "Things students should know..."], ["Syllabus", "Roadmap of the course..."]].map { |t| "# #{t[0]}\n\n#{t[1]}"}.join("\n\n") COLORS = [ {id: '#4191ff', label: 'Blue'}, {id: '#f03328', label: 'Red'}, {id: '#28a60b', label: 'Green'} ] acts_as_url :name has_many :reservations, dependent: :destroy has_many :students, through: :reservations, class_name: 'User' has_many :events has_many :schedules, class_name: 'CourseSchedule' has_many :resources has_many :cover_images belongs_to :location belongs_to :instructor, class_name: 'User' validates :name, presence: true validates :location, associated: true validates :instructor, associated: true validates :url, uniqueness: true, format: { with: /\A[a-z\d]+([-_][a-z\d]+)*\z/i, message: 'is not a valid URL'} scope :future, -> { where("starts_at >= ?", Time.now).order("starts_at ASC") } scope :past, -> { where("starts_at < ?", Time.now).order("starts_at DESC") } scope :without_dates, -> { where(starts_at: nil) } scope :campaign_ended, -> { where("campaign_ends_at < ?", Time.now) } scope :campaign_ending_within, ->(future){ where("campaign_ends_at > :now AND campaign_ends_at < :future", now: Time.now, future: future) } scope :campaign_not_failed, -> { where(campaign_failed_at: nil) } scope :campaign_not_ending_soon_reminded, -> { where(campaign_ending_soon_reminded_at: nil) } after_save :set_defaults after_create :send_course_created_notification before_save :revert_locked_fields_if_published before_save :set_default_color delegate :instructor_payout_amount, to: CashRegister # temporary while we figure out what db columns we want... attr_accessor :motivation, :audience attr_accessor :pricing accepts_nested_attributes_for :schedules has_attached_file :logo, styles: {logo: "320x30>"}, storage: 's3', s3_credentials: Enroll.s3_config_for('logos'), url: ':s3_domain_url', path: "/:class/:id_:basename.:style.:extension" validates_attachment_content_type :logo, :content_type => /\Aimage\/.*\Z/ def self.fail_campaigns # This marks campaigns that haven't reached the minimum number of seats by # their campaign ending time as failed, and notifies students and instructors # that are impacted. Course.future.campaign_ended.campaign_not_failed.each do |course| if course.students.count < course.min_seats course.update_attribute :campaign_failed_at, Time.now Resque.enqueue CampaignFailedNotification, course.id end end end # "Ending Soon" is henceforth defined as within the next 48 hours def self.ending_soon_time 48.hours.from_now end def self.notify_ending_soon_campaigns # This marks campaigns that haven't reached the minimum number of seats by # their campaign ending time as reminded about ending soon, and reminds # students that time is drawing short. Course.future.campaign_not_ending_soon_reminded.campaign_ending_within(ending_soon_time).each do |course| if course.students.count < course.min_seats course.update_attribute :campaign_ending_soon_reminded_at, Time.now Resque.enqueue CampaignEndingSoonNotification, course.id end end end def charge_credit_cards! return if self.free? self.reservations.each do |reservation| next if reservation.charged? if reservation.stripe_token.nil? && reservation.student.stripe_customer_id.nil? Raven.capture_message( "Reservation id=#{reservation.id} has no way to be charged.", level: "warn", logger: "root" ) next end unless reservation.student.stripe_customer_id customer = Stripe::Customer.create( card: reservation.stripe_token, description: reservation.student.email ) reservation.student.update_attribute(:stripe_customer_id, customer.id) end begin charge = Stripe::Charge.create( amount: reservation.charge_amount, currency: 'usd', customer: reservation.student.stripe_customer_id ) reservation.update_attributes( charge_succeeded_at: Time.now, stripe_token: nil ) rescue Stripe::CardError => e reservation.update_attribute(:charge_failure_message, e.message) Raven.capture_exception(e) end end end def send_course_created_notification Resque.enqueue(CourseCreatedNotification, self.id) end def send_course_created_notification! AdminMailer.course_created(self).deliver end def send_campaign_failed_notifications! InstructorMailer.campaign_failed(self).deliver self.students.each do |student| StudentMailer.campaign_failed(self, student).deliver end end def send_campaign_ending_soon_notifications! self.students.each do |student| StudentMailer.campaign_ending_soon(self, student).deliver end end def send_campaign_success_notifications! InstructorMailer.campaign_succeeded(self).deliver self.students.each do |student| StudentMailer.campaign_succeeded(self, student).deliver end end def url_or_short_name url ? url : name.slice(0, 20) end def start_date starts_at.try(:strftime, "%a, %B %e, %Y") end def start_time starts_at.try(:strftime, "%l:%M %p %Z") end def end_time ends_at.try(:strftime, "%l:%M %p %Z") end def date_range return "unknown date" unless starts_at && ends_at format = '%a,&nbsp;%B&nbsp;%e,&nbsp;%Y' if starts_at.to_date == ends_at.to_date starts_at.strftime(format) else "#{starts_at.strftime(format)} - #{ends_at.strftime(format)}" end end def free? price_per_seat_in_cents.blank? || price_per_seat_in_cents == 0 end def paid? !free? end def price_per_seat_in_dollars return nil unless price_per_seat_in_cents price_per_seat_in_cents / 100 end def price_per_seat_in_dollars=(dollars) self.price_per_seat_in_cents = dollars.to_f * 100 end def has_students? reservations.count > 0 end def future? first_day = starts_at.to_date first_schedule = schedules.where("date = ?", first_day).first if first_schedule && first_schedule.starts_at_time start_time = first_schedule.starts_at_time return Time.zone.now <= start_time else return Date.today <= first_day end end def past? !future? end def days_until_start days_until = (starts_at.to_date - Date.today).numerator days_until > 0 ? days_until : 0 end def too_soon? if days_until_start < 14 true else false end end def campaign_failed? campaign_failed_at.present? end def location_attributes=(all_atrs) atrs = all_atrs.dup atrs.delete_if { |k, v| v.blank? } if atrs.any? self.location = Location.where(atrs).first_or_create end self.location.try :update_attributes, all_atrs end def set_default_values_if_nil self.min_seats ||= 5 self.max_seats ||= 10 # self.price_per_seat_in_cents ||= 10000 self.build_location unless self.location self.description = DEFAULT_DESCRIPTION unless self.description.present? end def as_json(options={}) { name: name, location: location || {}, date: starts_at.try(:strftime, "%B %e, %Y"), description: description, logo: logo_json } end def logo_if_present if logo && !logo.blank? logo end end def logo_json return nil unless logo_file_name logo.url(:logo) end def instructor_paid? instructor_paid_at.present? end def pay_instructor! return false if future? || free? || instructor_paid? payout_result = Payout.create({ amount_in_cents: instructor_payout_amount(self), description: self.name, stripe_recipient_id: self.instructor.stripe_recipient_id }).request update_attribute(:instructor_paid_at, Time.now) if payout_result payout_result end def schedules_attributes=(value) self.schedules.each do |schedule| schedule.delete end super(value) end def visible_schedules schedules.where('NOT is_skipped') end def published? !!published_at end def draft? !published? end def publish! if self.starts_at > Time.zone.now self.published_at = Time.zone.now self.save! true else false end end # Finishing steps of the course def step_finished?(step) required = { details: [:name, :url], dates: [:starts_at], location: ['location.name'], pricing: [:price_per_seat_in_cents], landing_page: [:has_landing_page?] } required[step].all? { |p| self.value_for_key_path(p).present? } end def all_steps_finished? steps = [:details, :dates, :location, :pricing, :landing_page] steps.all? { |s| step_finished?(s) } end def has_landing_page? self.description && self.description != DEFAULT_DESCRIPTION end def value_for_key_path(path) keys = path.to_s.split('.') object = self keys.each do |key| object = object.send(key) return nil unless object end object end def cover_image(size) return nil if cover_images.count == 0 cover_image_object.image.url(size) end def cover_image_object cover_images.order('created_at desc').first end def cover_image? !!cover_image_object end private # temporary def set_defaults self.ends_at = self.starts_at + 4.hours if self.starts_at_changed? end def revert_locked_fields_if_published if published? self.price_per_seat_in_cents = self.price_per_seat_in_cents_was self.min_seats = self.min_seats_was self.starts_at = self.starts_at_was self.ends_at = self.ends_at_was self.url = self.url_was end end def set_default_color if !self.color self.color = COLORS[0][:id] end end end <file_sep>/spec/controllers/welcome_controller_spec.rb require "spec_helper" describe WelcomeController do let(:user) { create(:user) } describe "#index" do it "generates a visitor_id and stores it in a cookie" do get :index cookies[:visitor_id].should_not be_nil cookies[:visitor_id].length.should > 5 end it "generates and stores visitor_id in current_user" do sign_in(user) get :index controller.send(:visitor_id).length.should > 10 end it "stores visitor_id from cookie to user object" do cookies[:visitor_id] = "visitor1" sign_in(user) get :index user.reload.visitor_id.should == 'visitor1' end it "uses marketing token to get us a pre-generated cookie" do # Prepare the token token = MarketingToken.generate!(email: '<EMAIL>') # Let's assume there already is a cookie cookies[:visitor_id] = "ugly old token" # Expect the welcome event to be tracked with the new token Mixpanel::Tracker.any_instance.expects(:track).with('Welcome Page', {distinct_id: token.distinct_id}) get :index, i: token.token cookies[:visitor_id].should == token.distinct_id end it "identifies mixpanel user by distinct_id if they DO NOT have visitor id yet" do user.visitor_id = nil user.email = '<EMAIL>' user.save!(validate: false) sign_in(user) controller.stubs(:generate_visitor_id!).returns('abc') Mixpanel::Tracker.any_instance.expects(:set).with('abc', {email: '<EMAIL>'}) get :index end it "identifies mixpanel user by distinct_id if they HAVE visitor id" do user.visitor_id = 'bcd' user.email = '<EMAIL>' user.save!(validate: false) sign_in(user) Mixpanel::Tracker.any_instance.expects(:set).with('bcd', {email: '<EMAIL>'}) get :index end end describe "#about" do it "responds with the about page" do get :about response.should be_ok end end end<file_sep>/spec/controllers/dashboard/courses_controller_spec.rb require "spec_helper" describe Dashboard::CoursesController do let(:user) { create(:user) } before { sign_in(user) } describe "#new" do render_views it "returns ok" do get :new, step: 'details' response.should be_ok end end describe "#update" do let(:course) { create(:course, instructor: user, price_per_seat_in_cents: 2000) } it "saves the price" do course.published?.should be_false course.price_per_seat_in_cents.should == 2000 put :update, id: course.id, step: 'pricing', course: {price_per_seat_in_dollars: 5} response.should redirect_to edit_dashboard_course_path(course, :step => 'page') course.reload.price_per_seat_in_cents.should == 500 end end describe "#publish" do let(:user) { create(:user) } let(:course) { create(:course, instructor: user) } it "publishes the course" do course.should_not be_published get :publish, id: course.id course.reload.should be_published end it "does not publish if date is in the past" do course.starts_at = Date.yesterday course.ends_at = Date.yesterday course.save! course.should_not be_published get :publish, id: course.id course.reload.should_not be_published end end end<file_sep>/spec/controllers/dashboard/payment_settings_controller_spec.rb require 'spec_helper' describe Dashboard::PaymentSettingsController do let(:user) { create(:user) } let(:course) { create(:course, instructor: user) } describe 'GET edit' do before(:each) do sign_in user end it 'renders the edit page' do get :edit, course_id: course.id response.should be_success response.should render_template('edit') end it 'edits the current user' do get :edit, course_id: course.id assigns[:user].should == user end context 'when not logged in' do before(:each) do sign_out user end it 'redirects the user to the login page' do get :edit, course_id: course.id response.should be_redirect response.should redirect_to(new_user_session_path) end end end describe 'PUT update' do context 'when successful' do before(:each) do sign_in user User.any_instance.stubs(:save_payment_settings!).returns(true) end it 'save the payment settings for the user' do User.any_instance.expects(:save_payment_settings!).with({ 'name' => '<NAME>', 'stripe_bank_account_token' => '<PASSWORD>' }) put :update, course_id: course.id, user: payment_settings_params end it 'redirects to the edit page' do put :update, course_id: course.id, user: payment_settings_params response.should be_redirect response.should redirect_to(edit_dashboard_course_payment_settings_path(course)) end it 'displays a success message' do put :update, course_id: course.id, user: payment_settings_params flash[:success].should_not be_blank end end context 'when unsuccessful' do before(:each) do sign_in user User.any_instance.stubs(:save_payment_settings!).returns(false) put :update, course_id: course.id, user: payment_settings_params end it 're-renders the form' do response.should render_template('edit') end it 'displays an error message' do flash[:error].should_not be_blank end end context 'when not logged in' do it 'redirects the user to the login page' do put :update, course_id: course.id, user: payment_settings_params response.should be_redirect response.should redirect_to(new_user_session_path) end end end end def payment_settings_params { 'name' => '<NAME>', 'stripe_bank_account_token' => '<PASSWORD>' } end <file_sep>/app/mailers/generic_mailer.rb class GenericMailer < ActionMailer::Base def generic_mail(options={}) @content = options[:content] mail_options = { to: options[:to], from: options[:from], subject: options[:subject] } mail_options[:cc] = options[:cc] if options[:cc] mail mail_options end end <file_sep>/app/controllers/blog_posts_controller.rb class BlogPostsController < ApplicationController before_filter :setup_markdown before_filter { add_body_class 'welcome' } def index @posts = BlogPost.order('published_at desc') end def show @post = BlogPost.find_by_url(params[:id]) end end <file_sep>/spec/models/resource_spec.rb require 'spec_helper' describe Resource do it { should validate_presence_of(:course_id) } it { should validate_presence_of(:name) } it "checks type of resource" do resource = Resource.new(resource_type: 'file') resource.should be_file resource = Resource.new(resource_type: 'link') resource.should be_link end end <file_sep>/app/jobs/charge_credit_cards.rb class ChargeCreditCards @queue = :notifications def self.perform(id) Course.find(id).charge_credit_cards! end end<file_sep>/docs/competition.md ## Competitors / Co-opitors **SkillShare** - http://www.skillshare.com/ - Great platform, but they are also trying to be a course marketplace - It seems like they are phasing out local courses and focusing on online only - http://help.skillshare.com/customer/portal/topics/444715-teaching-a-local-class/articles - You can't even search for local courses anymore - they've removed it from the search engine - Founder has a nice blog: http://www.mikekarnj.com/blog/ - We should definitely look at their course creation tool: http://www.skillshare.com/classes/local/new/basic-info - Check out my fake course: http://skl.sh/18G6Yxr - Here's a few local course examples (I had to DIG to find these): - http://www.skillshare.com/How-to-Build-an-Awesome-Professional-Network/168031227/1758500734?via=similar-classes - http://www.skillshare.com/Startup-Marketing-for-Dummies-Acquisition-Retention-and-Revenue/1783431596/1053709570?via=similar-classes **General Assembly** - http://generalassemb.ly/ - Curated set of local and live-streamed courses - Very well-designed site with some course tools as well - Interesting Enterprise partnerships - https://generalassemb.ly/enterprise - Uses eventbrite for ticketing?? *boggle* Would love to talk to them about this at some point. - Check out some of their beautifully-designed workshop pages: - All courses: https://generalassemb.ly/learn - Bootcamp: https://generalassemb.ly/education/mobile-app-development-bootcamp/new-york-city/2128 - "Immersive Course": https://generalassemb.ly/education/user-experience-design-immersive/new-york-city - Workshop: https://generalassemb.ly/education/understanding-mobile-user-experience/new-york-city/2140 - Refund policy is 7 days **Custom website + EventBrite** - Many people hosting workshops put together a custom website and use EventBrite for ticketing **SkillsMatter** - http://skillsmatter.com/ - Holy crap, look at the sheer number of workshops and the costs. Crazy. - We can definitely do better than this. **GathersUs** - http://gathers.us/ - Once again, we can do better **The Intro** - http://theint.ro/ - Nicely designed, but the workshop view pages could use a little more oomph **Enterprise Competition** - http://www.abcsignup.com/ - http://www.exitcertified.com/ <file_sep>/app/helpers/dashboard_helper.rb module DashboardHelper def dashboard_menu_link(path, label, icon, controller, action, &block) current_action = action ? action_name : nil klass = if controller_name == controller && current_action == action 'active' else '' end content_tag :li, :class => klass do content_tag :a, :href => path do content = capture_haml(&block) if block_given? content_tag(:i, '', :class => "icon-#{icon}") + ' ' + label + ' ' + content end end end def dashboard_check_link(title, url_options, is_checked) klasses = [] is_active = url_options.all? { |option, value| params[option] == value } klasses << 'active' if is_active klasses << 'checked' if is_checked # url_options[:action] = @course.id ? 'edit' : 'new' url_options[:id] = @course.id content_tag :li, :class => klasses.join(' ') do url = @course.id ? url_options : '' link_to title, url end end def dashboard_check_link_step(title, step, checked) action = @course.id ? 'edit' : 'new' dashboard_check_link title, { controller: 'dashboard/courses', action: action, step: step }, checked end def activity_date_format(date) if date.to_date == Date.today "Today" elsif date.to_date == Date.yesterday "Yesterday" else date.strftime("%a, %b #{date.day.ordinalize}") end end def icon_for_event_type(type) icons = { Event::COURSE_CREATED => 'paper-plane', Event::PAGE_VISITED => 'user', Event::STUDENT_ENROLLED => 'feather' } icon = icons[type] html = '<i class="icon icon-%s"></i>' % [icon] html.html_safe end end<file_sep>/app/helpers/mailers_helper.rb module MailersHelper def enroll_noreply "Enroll <<EMAIL>>" end def enroll_reply "Enroll <<EMAIL>>" end def enroll_support "Enroll Support <<EMAIL>>" end end <file_sep>/db/migrate/20140110094651_courses_is_published.rb class CoursesIsPublished < ActiveRecord::Migration def change add_column :courses, :is_published, :bool, default: false end end <file_sep>/app/helpers/navigation_helper.rb module NavigationHelper def nav_signupbox_class return nil if controller_name == "reservations" (@user && @user.errors.any?) || (@course && @course.errors.any?) ? 'in' : nil end def nav_loginbox_class flash.alert ? 'in' : nil end def course_short_url(course) if course.url.nil? course_url(course) else root_url + 'go/' + course.url end end def course_short_path(course) if course.url.nil? course_path(course) else '/go/' + course.url end end end <file_sep>/spec/controllers/dashboard/resources_controller_spec.rb require "spec_helper" describe Dashboard::ResourcesController do let(:user) { create(:user) } let(:course) { create(:course, instructor: user) } let(:resource) { create(:resource, course: course) } before { sign_in(user) } describe "#index" do it "lists resources for a course" do resource get :index, course_id: course.id assigns(:resources).should_not be_nil assigns(:resources).count.should == 1 assigns(:resources).first.should == resource end end describe "#create" do it "creates the resource" do expect { post :create, course_id: course.id, resource: resource_file_params, transloadit: transloadit_params }.to change{Resource.count}.by(1) Resource.last.tap { |r| r.name.should == 'foo' r.description.should == 'bar' } end it "on success from transloadit, saves the s3_url and assembly_id" do post :create, course_id: course.id, resource: resource_file_params, transloadit: transloadit_params resource = Resource.last resource.s3_url.should == "some-url" resource.transloadit_assembly_id.should == "some-id" response.should redirect_to(dashboard_course_resources_path(course)) end it "on upload failure renders new" do post :create, course_id: course.id, resource: resource_file_params, transloadit: transloadit_failing_params response.should be_ok response.should render_template('new') end it "renders new if response from translaodit is empty" do post :create, course_id: course.id, resource: resource_file_params, transloadit: transloadit_empty_params response.should be_ok response.should render_template('new') end it "creates a link resource" do expect { delete :create, course_id: course.id, resource: resource_link_params }.to change{Resource.count}.by(1) Resource.last.tap { |r| r.name.should == 'foo' r.description.should == 'bar' r.link.should == 'http://foo.bar' r.should be_link } end end describe "#destroy" do it "deletes resource" do resource # create resource expect { delete :destroy, course_id: course.id, id: resource.id }.to change{Resource.count}.by(-1) end end def transloadit_params { ok: "ASSEMBLY_COMPLETED", assembly_id: "some-id", results: { ":original" => [{ url: "some-url" }] } }.to_json end def transloadit_empty_params { ok: 'ASSEMBLY_COMPLETED', assembly_id: 'some-id', results: {} }.to_json end def transloadit_failing_params {error: "INVALID_FILE_META_DATA"}.to_json end def resource_file_params {name: 'foo', description: 'bar', resource_type: 'file'} end def resource_link_params {name: 'foo', description: 'bar', link: 'http://foo.bar', resource_type: 'link'} end end<file_sep>/app/controllers/dashboard/courses_controller.rb class Dashboard::CoursesController < ApplicationController before_filter :authenticate_user! before_filter :find_course_as_instructor!, only: [:show, :edit, :update, :share, :review, :publish, :destroy_logo] include CoursesEditingConcern before_filter :prepare_steps, only: [:new, :edit, :create, :update] before_filter :update_steps_for_dashboard, only: [:edit, :update] def new @course = Course.new render 'edit' end def create @course = Course.new @course.instructor = current_user create_update end def show if @course.draft? return redirect_to edit_dashboard_course_path(@course, step: 'details') end @events = Event.grouped_by_date_and_type(course: @course) mixpanel_track_event 'Dashboard' end def edit @course.set_default_values_if_nil end def update create_update end def publish unless @course.publish! flash[:error] = "Cannot publish course with date in the past" end redirect_to dashboard_course_path(@course, published: 1) mixpanel_track_event 'Publish Course' end def destroy_logo @course.logo = nil @course.save! render nothing: true end protected def create_update # raise course_params.inspect if @course.update_attributes(course_params) respond_to do |format| format.html { if next_step redirect_to_next_step else redirect_to review_dashboard_course_path(@course) end } format.json { render json: @course } end else render :edit end mixpanel_track_event current_step_mixpanel_event end def redirect_to_next_step if next_step redirect_to edit_dashboard_course_path(@course, :step => next_step[:id]) else redirect_to dashboard_course_path(@course) end end def update_steps_for_dashboard end end<file_sep>/app/models/marketing_token.rb class MarketingToken < ActiveRecord::Base def self.generate!(options={}) token = MarketingToken.new(options) token.token = self.generate_token token.distinct_id = SecureRandom.base64 token.save! token end protected def self.generate_token(length=2) # 20 times try to generate token that's not taken yet. 20.times do token = random_string(length) existing = MarketingToken.where(token: token).first return token unless existing end # if it fails, increase length and try again. generate_token(length+1) end def self.random_string(length=10) chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789' password = '' length.times { password << chars[rand(chars.size)] } password end end<file_sep>/spec/mailers/instructor_mailer_spec.rb require 'spec_helper' describe InstructorMailer do let(:instructor) { build(:instructor, :email => "<EMAIL>") } let(:course) { build(:course, instructor: instructor, name: "Hackers 101", url: nil) } let(:student) { build(:student, :email => "<EMAIL>") } let(:reservation) { build(:reservation, student: student, course: course) } describe "#student_enrolled" do let(:email) { InstructorMailer.student_enrolled(reservation) } it "delivers the enrollment notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end describe "#campaign_failed" do let(:email) { InstructorMailer.campaign_failed(course) } it "delivers the campaign failed notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end describe "#campaign_succeeded" do let(:email) { InstructorMailer.campaign_succeeded(course) } it "delivers the campaign succeeded notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end end <file_sep>/app/mailers/instructor_mailer.rb class InstructorMailer < ActionMailer::Base include MailersHelper def student_enrolled(reservation) @student = reservation.student @instructor = reservation.instructor @course = reservation.course mail \ :to => @instructor.email, :from => enroll_noreply, :subject => "[#{@course.url_or_short_name}] A new student just enrolled." end def campaign_failed(course) @instructor = course.instructor @students = course.students @course = course mail \ :to => @instructor.email, :from => enroll_reply, :subject => "[#{@course.url_or_short_name}] Your course didn't meet reach your minimum reservations." end def campaign_succeeded(course) @instructor = course.instructor @students = course.students @course = course mail \ :to => @instructor.email, :from => enroll_reply, :subject => "[#{@course.url_or_short_name}] Congrats! Your course has met your minimums." end end <file_sep>/app/jobs/campaign_failed_notification.rb class CampaignFailedNotification @queue = :notifications def self.perform(id) course = Course.find(id) course.send_campaign_failed_notifications! end end <file_sep>/app/controllers/courses_controller.rb class CoursesController < ApplicationController before_filter :authenticate_user!, only: [:new, :create, :edit, :update, :index] before_filter :find_course_as_instructor!, only: [:edit, :update] before_filter :find_course_by_url!, only: [:show, :preview] include CoursesEditingConcern before_filter :prepare_steps, only: [:new, :edit, :create, :update] before_filter :setup_markdown, only: [:show, :preview] def index @courses_teaching = current_user.courses_as_instructor @courses_studying = current_user.courses_as_student end def show @preview = false add_body_class('landing-page') Event.create_event(Event::PAGE_VISITED, course: @course) mixpanel_track_event 'Landing Page' end def preview @course.attributes = course_params @preview = true render json: { preview: render_to_string('show', layout: false), cover_image: @course.cover_image_object } end protected def redirect_to_next_step if next_step redirect_to edit_course_step_path(@course, :step => next_step[:id]) else redirect_to dashboard_course_path(@course) end end end <file_sep>/app/helpers/styling_helper.rb module StylingHelper def course_text_style "color: #{@course.color}" end def course_background_style "background-color: #{@course.color}" end def logo_style(logo) if !logo.blank? "background-image: url(#{logo.url(:logo)}); background-size: contain; background-position: 0 0;" end end end<file_sep>/docs/features.md # Potential Features ### Product Story Mike knows Ruby really well, and has a decent gig in town working for a local consultancy. However, he wants to make a little cash on the side and make a name for himself. He decides he'll run a 4-day workshop in the evenings at the local coworking space and teach Ruby. He needs to spend most of his time building his slide decks and planning the curriculum, but he also needs to promote the workshop and get people to sign up and pay him. Enter Workshop Platform! Mike surfs over to Workshop Platform. Without signing up, he's able to enter a few details about his workshop–time and dates, location, topics, information about him as an instructor. He chooses a few visual details, and then immediately he previews his custom created workshop page. He takes a little screenshot tour of the backend course and ticketing management functions, and then decides to go for it. They want a few percentage points of his ticket sales, but they'll save him a ton of time building a website to promote his workshop, so he gladly signs up and his workshop page is instantly live. Over the next few weeks, he promotes his workshop site via Facebook, twitter, and local user groups and gets a lot of traffic to his workshop page. He decides to purchase a custom domain to make his site stand out a little more and capture some Google pagerank magic. It's a quick one-click setup on the workshop platform to activate his new custom domain name. As the week approaches for his workshop, he gets notification emails for each signup as they sign up and pay. Exciting! He's making money already! The week of the workshop comes and his students get emailed an invite to access the course materials on the workshop platform. Mike posts an announcement for students to make sure they have a certain version of Ruby installed prior to the first night of the workshop. The workshop platform has a simple Q&A piece where they can ask Mike questions. Students ask a few questions that Mike hadn't thought of. Do I need to read any books before coming? Are you going to cover this-or-that topic? Mike is able to communicate with them prior to them showing up at class and other students are able to see the questions and answers, thus relieving Mike of the burden of answering the questions multiple times. Students can see who else is signed up for the workshop and a few of them contact each other and work out rides from downtown to the coworking location. The workshop goes off really well! Mike is nervous the first night, but each night he gains confidence in his speaking and the material. The students really enjoy learning from him and from each other. After the workshop, Mike kicks off the "improve your workshop fu" feature of the workshop platform which sends an email out to all of the students requesting feedback on how well the workshop was run and the opportunity to offer anonymous feedback for Mike if so desired. A few of the students give great constructive feedback for Mike, but most of the just take a few seconds to click a few numbers between 1 and 10. Still, useful. A few weeks go by and Mike starts thinking. Maybe I should do that again? It was fun, he made money, and even made a few friends. And what do ya know, he gets an email from the Workshop Platform, asking if he'd like to set up another version of the class. He clicks the link and is guided through a simple interface asking him to update any of the workshop info and enter new dates and locations. He also sees the feedback from the previous students and is able to automatically add a testimonials section to his new workshop site. He sees the students questions from the Q&A tool and is easily able to add an FAQ section to the site. When he's done creating the new workshop site, he sees he has a link to the old workshop, and the new site looks even more convincing and fully fleshed out than the past one. Wow, this workshop platform makes is really easy for Mike to make money doing what Mike does best: teach his stuff!<file_sep>/spec/models/payout_spec.rb require 'spec_helper' describe Payout do let(:payout) { build(:payout) } context "validations" do it "requires an 'amount_in_cents'" do payout.amount_in_cents = nil payout.valid? payout.errors[:amount_in_cents].should include("can't be blank") end it "requires a 'description' of what bank transfer will say" do payout.description = nil payout.valid? payout.errors[:description].should include("can't be blank") end it "requires a 'stripe_recipient_id'" do payout.stripe_recipient_id = nil payout.valid? payout.errors[:stripe_recipient_id].should include("can't be blank") end end it "starts in the 'pending' status" do payout.status.should == 'pending' end context "#request" do before { payout.stubs(:transfer_funds!).returns(true) } it "updates the status to 'requested" do payout.request payout.status.should == 'requested' end it "requests a funds transfer" do payout.expects(:transfer_funds!).returns(stub_everything) payout.request end it "sets the transfer id" do payout.expects(:set_transfer_id).returns(stub_everything) payout.request end end context "#transfer_funds!" do it "transfers funds to a stripe recipient" do payout = build(:payout, :description => "Ruby Fundamentals", :amount_in_cents => 14000, :stripe_recipient_id => "rp_2FUrV5Zn4ILgfo" ) VCR.use_cassette('stripe/transfer') do transfer = payout.transfer_funds! transfer.status.should == "pending" transfer.recipient.should == "rp_2FUrV5Zn4ILgfo" transfer.amount.should == 14000 end end end context "#set_transfer_id" do it "sets the stripe_transfer_id from the transfer" do payout.transfer = stub(:id => "abc123") payout.set_transfer_id payout.stripe_transfer_id.should == "abc123" end it "handles the case where the transfer is nil" do payout.transfer = nil payout.set_transfer_id payout.stripe_transfer_id.should be_nil end end context "#transfer_params" do it "includes the amount" do payout.amount_in_cents = 1000 payout.transfer_params[:amount].should == 1000 end it "includes the currency" do payout.transfer_params[:currency].should == 'usd' end it "includes the stripe recipient" do payout.stripe_recipient_id = 54321 payout.transfer_params[:recipient].should == 54321 end it "includes the statement_descriptor" do payout.description = "Negotiation 101" payout.transfer_params[:statement_descriptor].should == "Negotiation 101" end end context "#complete" do it "updates the status to 'paid'" do payout = build(:payout_requested) payout.complete payout.status.should == 'paid' end end end <file_sep>/spec/controllers/users/registrations_controller_spec.rb require 'spec_helper' describe Users::RegistrationsController do include Devise::TestHelpers render_views before do setup_controller_for_warden request.env["devise.mapping"] = Devise.mappings[:user] end let(:user_attributes) { attributes_for(:user).merge({ course: attributes_for(:course)}) } context "POST users" do context "with valid params" do it "creates a new user" do expect { post :create, user: user_attributes }.to change(User, :count) end it "creates a new course" do expect { post :create, user: user_attributes }.to change(Course, :count) end it "associates the course and the user" do post :create, user: user_attributes Course.last.instructor.should == User.last end it "redirects to the manage course page" do post :create, user: user_attributes response.should be_redirect response.should redirect_to(edit_dashboard_course_path(Course.last)) end end context "with invalid params" do before { Course.any_instance.stubs(:save).returns(false) } it "assigns a newly created but unsaved user as @user" do post :create, user: user_attributes assigns(:user).should be_instance_of(User) end it "assigns a newly created but unsaved course as @course" do post :create, user: user_attributes assigns(:course).should be_instance_of(Course) end end end end <file_sep>/app/controllers/dashboard/cover_images_controller.rb class Dashboard::CoverImagesController < ApplicationController before_filter :find_course_as_instructor_by_course_id!, except: [:update, :destroy] def create puts "Creating the cover image" @course.cover_images.delete_all image = CoverImage.new(cover_image_params) image.course = @course image.save! render json: image end def update image = CoverImage.find(params[:id]) image.update_attributes!(params.require(:cover_image).permit(:offset_admin_px)) render nothing: true end def destroy image = CoverImage.find(params[:id]) image.delete render nothing: true end protected def cover_image_params params.require(:course).require(:cover_image).permit(:image) end end<file_sep>/spec/helpers/navigation_helper_spec.rb require 'spec_helper' class NavigationTest include NavigationHelper attr_accessor :user, :course, :controller_name, :flash def initialize(options={}) options.each { |k,v| instance_variable_set("@#{k}", v) } end end describe NavigationHelper do let(:user) { build(:user) } let(:course) { build(:course) } before(:each) do @nav = NavigationTest.new(user: user, course: course) end describe 'nav_signupbox_class' do it 'returns nil if there are no errors' do @nav.nav_signupbox_class.should be_nil end it 'returns nil if user and course are not set' do @nav.course = nil @nav.user = nil @nav.nav_signupbox_class.should be_nil end it 'returns "in" if there are @user errors' do @nav.user.stubs(:errors).returns({ name: 'is invalid' }) @nav.nav_signupbox_class.should == 'in' end it 'returns "in" if there are @course errors' do @nav.course.stubs(:errors).returns({ name: 'is invalid' }) @nav.nav_signupbox_class.should == 'in' end it 'returns nil regardless of errors if we are creating a reservation' do @nav.user.stubs(:errors).returns({ name: 'is invalid' }) @nav.stubs(:controller_name).returns('reservations') @nav.nav_signupbox_class.should be_nil end end describe 'nav_loginbox_class' do it 'returns nil if no flash alert is set' do @nav.flash = OpenStruct.new({ success: 'hurray' }) @nav.nav_loginbox_class.should be_nil end it 'returns "in" if a flash alert is present' do @nav.flash = OpenStruct.new({ alert: 'ohno' }) @nav.nav_loginbox_class.should == 'in' end end describe 'course_short_url' do it 'returns the course url properly constructed' do course = build(:course, url: 'my-fresh-course') course_short_url(course).should == 'http://test.host/go/my-fresh-course' end it 'returns the standard course url if course url is nil' do course = create(:course) course.url = nil course_short_url(course).should include("http://test.host/courses/") end end describe 'course_short_path' do it 'returns the course path properly constructed' do course = build(:course, url: 'my-fresh-course') course_short_path(course).should == '/go/my-fresh-course' end it 'returns the standard course path if course url is nil' do course = create(:course) course.url = nil course_short_path(course).should include("/courses/") end end end <file_sep>/spec/models/marketing_token_spec.rb require "spec_helper" describe MarketingToken do it "generates random tokens" do token1 = MarketingToken.generate! token2 = MarketingToken.generate! token1.token.should_not be_nil token2.token.should_not be_nil token1.distinct_id.should_not be_nil token2.distinct_id.should_not be_nil token1.token.should_not == token2.token token1.distinct_id.should_not == token2.distinct_id end end<file_sep>/app/controllers/dashboard/payment_settings_controller.rb class Dashboard::PaymentSettingsController < ApplicationController before_filter :authenticate_user! before_filter :find_course_as_instructor_by_course_id!, only: [:edit, :update] def edit @user = current_user end def update @user = current_user if @user.save_payment_settings!(stripe_recipient_params) flash[:success] = "Payment settings updated successfully." redirect_to edit_dashboard_course_payment_settings_path(@course.id) else flash.now[:error] = "Unable to update your payment settings. Sorry about that." render :edit end end private def stripe_recipient_params params.require(:user).permit(:name, :stripe_bank_account_token) end end <file_sep>/lib/tasks/scheduler.rake desc "Check to see if any campaigns have failed" task :fail_campaigns => :environment do Course.fail_campaigns end desc "Check to see if any campaigns are ending soon and have not met minimums" task :ending_soon_campaigns => :environment do Course.notify_ending_soon_campaigns end <file_sep>/app/mailers/student_mailer.rb class StudentMailer < ActionMailer::Base include MailersHelper def campaign_failed(course, student) @student = student @instructor = course.instructor @course = course mail \ :to => @student.email, :from => enroll_noreply, :subject => "[#{@course.url_or_short_name}] Your course didn't reach its minimum reservations." end def campaign_succeeded(course, student) @student = student @instructor = course.instructor @course = course mail \ :to => @student.email, :from => enroll_noreply, :subject => "[#{@course.url_or_short_name}] Get ready! Your course reached its minimum reservations." end def campaign_ending_soon(course, student) @student = student @instructor = course.instructor @course = course mail \ :to => @student.email, :from => enroll_noreply, :subject => "[#{@course.url_or_short_name}] Course needs your help!" end def enrolled(reservation) @student = reservation.student @course = reservation.course mail \ :to => @student.email, :from => enroll_noreply, :subject => "[#{@course.url_or_short_name}] You're enrolled!" end end <file_sep>/app/controllers/users/registrations_controller.rb class Users::RegistrationsController < Devise::RegistrationsController def new @user = User.new @course = Course.new end def create @user = User.new(user_params) @course = Course.new(course_params) @course.instructor = @user if @course.save sign_up(:user, @user) mixpanel_track_event 'Sign Up' respond_with @user, location: after_sign_up_path_for(@user) else clean_up_passwords @user render 'new' end end private def user_params params.require(:user).permit(:username, :name, :email, :password, :salt, :encrypted_password) end def course_params params.require(:user).require(:course).permit(:name) end def after_sign_up_path_for(user) edit_dashboard_course_path(user.courses.last) end end <file_sep>/spec/models/location_spec.rb require 'spec_helper' describe Location do let(:location) { build(:location) } it { should have_many(:courses) } describe "zip_and_state" do it "returns the correct value based on values present" do location.state = "" location.zip = "" location.zip_and_state.should == "" location.state = "California" location.zip = "94107" location.zip_and_state.should == "California 94107" location.state = "California" location.zip = nil location.zip_and_state.should == "California" end end describe "city_and_state" do it "returns the correct value based on values present" do location.state = "" location.city = "Boston" location.city_and_state.should == "Boston" location.state = "MA" location.city = nil location.city_and_state.should == "MA" location.state = "MA" location.city = "Boston" location.city_and_state.should == "Boston, MA" end end end <file_sep>/script/cibuild #!/bin/bash # Usage: script/cibuild # CI build script # set -e echo "Tests started at..." date "+%H:%M:%S" # GC customizations export RUBY_GC_MALLOC_LIMIT=1000000000 export RUBY_HEAP_SLOTS_GROWTH_FACTOR=1.25 export RUBY_HEAP_MIN_SLOTS=800000 export RUBY_FREE_MIN=600000 # setup environment export PATH="/var/lib/jenkins/.rbenv/shims:/usr/bin:/bin" export RAILS_ENV="test" export RACK_ENV="$RAILS_ENV" echo "Using..." ruby -v mkdir -p log mkdir -p tmp trap "rm -f tmp/bootstrap.$$" EXIT # list of bundler groups to exclude when bootstrapping bundle_without="development:staging:production" echo "Bundler started at..." date "+%H:%M:%S" bundle install --without="$bundle_without" --path vendor/gems 1>tmp/bootstrap.$$ 2>&1 || { echo "error: bundle failed (exit $?)" 1>&2 cat tmp/bootstrap.$$ exit 1 } echo "Creating test database for enroll..." date "+%H:%M:%S" dropdb enroll_test 2>/dev/null || true createdb enroll_test --template template0 --encoding unicode 2>/dev/null || true cp config/database.ci.yml config/database.yml bundle exec rake db:schema:load echo "Running tests ..." date "+%H:%M:%S" bundle exec rake <file_sep>/db/migrate/20140320060005_add_is_skipped_to_course_schedules.rb class AddIsSkippedToCourseSchedules < ActiveRecord::Migration def change add_column :course_schedules, :is_skipped, :boolean, default: false end end <file_sep>/db/migrate/20130623192717_create_reservations.rb class CreateReservations < ActiveRecord::Migration def change create_table :reservations do |t| t.integer :course_id end add_index :reservations, :course_id end end <file_sep>/spec/controllers/courses_controller_spec.rb require 'spec_helper' describe CoursesController do let(:course) { build(:course) } let(:course_attributes) { attributes_for(:course).merge({ location_attributes: attributes_for(:location)}) } let(:saved_course) { create(:course, instructor: user, name: 'foo') } let(:user) { create(:user) } context "GET show" do render_views before { course.save } it "renders the show page" do get :show, id: course.to_param assigns[:course].should == course response.should be_success response.should render_template :show end it "renders the landing page via landing page url" do get :show, url: course.url assigns[:course].should == course response.should be_success response.should render_template :show end it "creates an event about page being visited" do get :show, url: course.url Event.last.tap { |e| e.event_type.should == Event::PAGE_VISITED e.course.should == course } end it "works ok with description being nil" do course.description = nil course.save! get :show, url: course.url response.should be_success end end context "GET index" do before { course.save } it "renders the index" do sign_in(user) get :index response.should be_success response.should render_template :index end it "includes some courses" do sign_in(user) get :index assigns[:courses_teaching].should_not be_nil assigns[:courses_studying].should_not be_nil end end end <file_sep>/script/bootstrap #!/bin/sh set -e export CC=gcc echo "==> Installing gem dependencies..." bundle check --path vendor/gems 2>&1 > /dev/null || { bundle install --path vendor/gems --quiet --without staging:production } # make the log directory mkdir -p log echo "==> Setting up database..." bundle exec rake db:create bundle exec rake db:create RAILS_ENV=test bundle exec rake db:migrate db:test:prepare echo "==> Creating seed data..." bundle exec rake db:seed echo "==> Enroll is bootstrapped!" <file_sep>/db/migrate/20131212135640_create_course_schedule.rb class CreateCourseSchedule < ActiveRecord::Migration def change create_table :course_schedules do |t| t.integer :course_id t.date :date t.integer :starts_at # Number of seconds from midnight t.integer :ends_at # ... end end end <file_sep>/db/migrate/20140111000417_courses_min_seats_default.rb class CoursesMinSeatsDefault < ActiveRecord::Migration def change change_column :courses, :min_seats, :integer, default: 0 end end <file_sep>/spec/mailers/student_mailer_spec.rb require 'spec_helper' describe StudentMailer do let(:instructor) { build(:instructor, :email => "<EMAIL>") } let(:course) { build(:course, instructor: instructor, name: "Hackers 101", url: nil) } let(:student) { build(:student, :email => "<EMAIL>") } let(:reservation) { build(:reservation, student: student, course: course) } describe "#campaign_failed" do let(:email) { StudentMailer.campaign_failed(course, student) } it "delivers the campaign failure notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end describe "#campaign_succeeded" do let(:email) { StudentMailer.campaign_succeeded(course, student) } it "delivers the campaign success notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end describe "#campaign_ending_soon" do let(:email) { StudentMailer.campaign_ending_soon(course, student) } it "delivers the campaign ending soon reminder" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end describe "#enrolled" do let(:email) { StudentMailer.enrolled(reservation) } it "delivers the enrollment notification" do email.should deliver_to("<EMAIL>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/Hackers 101/) end end end <file_sep>/app/models/user.rb class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessor :account_number, :routing_number, :stripe_bank_account_token has_many :reservations, dependent: :destroy, foreign_key: :student_id has_many :courses_as_student, through: :reservations, class_name: 'Course', source: :course, foreign_key: :student_id has_many :courses_as_instructor, class_name: 'Course', foreign_key: :instructor_id, dependent: :destroy has_many :events has_attached_file :avatar, :styles => { :large => "240x240>", :medium => "120x120#", :thumb => "60x60#" }, :default_url => "/images/avatar_:style_missing.png" validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/ def to_s email # todo name end def courses (courses_as_instructor + courses_as_student).uniq end def display_title name || email end def reservation_for_course(course) Reservation.where(course_id: course.id, student_id: self.id).first end def enrolled_for?(course) !!reservation_for_course(course) end def instructor? courses_as_instructor.any? end def student? courses_as_student.any? end def save_payment_settings!(params) params[:type] = "individual" params[:bank_account] = params.delete(:stripe_bank_account_token) params[:email] = self.email begin recipient = Stripe::Recipient.create(params) if recipient && recipient.id self.stripe_recipient_id = recipient.id self.name = params[:name] save else false end rescue Stripe::InvalidRequestError => e return false end end # TODO: Add a 'role' column to actually distinguish # between Enroll staff and Enroll customers def staff? true end # Stripe def update_stripe_customer(token) return unless token.present? customer = nil if stripe_customer_id begin customer = Stripe::Customer.retrieve(stripe_customer_id) rescue Stripe::InvalidRequestError => e end end if customer && !customer.deleted # Customer exists, update the card using token from the form customer.card = token customer.save else # Customer doesn't exist yet, create a customer with token from the form customer = Stripe::Customer.create( card: token, description: email ) end self.stripe_customer_id = customer.id self.save!(validate: false) customer end end <file_sep>/app/models/resource.rb class Resource < ActiveRecord::Base belongs_to :course validates :course_id, presence: true validates :name, presence: true validates :s3_url, presence: true, if: :file? validates :link, presence: true, if: :link? def file? resource_type == 'file' end def link? resource_type == 'link' end end <file_sep>/config/deploy.rb set :application, 'enroll' set :deploy_to, '/var/apps/enroll' set :scm, :git set :repo_url, '<EMAIL>:enroll/enroll.git' set :branch, ENV['BRANCH'] || 'master' set :ssh_options, {forward_agent: true} set :log_level, :debug set :linked_files, %w{config/database.yml} set :linked_dirs, ["tmp/pids", "log", "public/system"] set :test_log, "log/capistrano.test.log" require 'tinder' # Resque set :resque_environment_task, true namespace :deploy do desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do # Your restart mechanism here, for example: execute :touch, release_path.join('tmp/restart.txt') end end after :restart, :clear_cache do on roles(:web), in: :groups, limit: 3, wait: 10 do # Here we can do anything such as: # within release_path do # execute :rake, 'cache:clear' # end end end after :finishing, 'deploy:cleanup' after 'deploy:restart', 'resque:restart' end # Campfire campfire = Tinder::Campfire.new 'launchwise', :token => '42a2b525c7066a643cbf5ec448ee98728994923a' room = campfire.find_room_by_name 'Enroll' namespace :campfire do task :started do room.speak ":fire: Deploy #{fetch(:branch)} to #{fetch(:stage)} started!" end task :finished do room.speak ":fire: Deploy #{fetch(:branch)} to #{fetch(:stage)} finished!" end task :reverted do room.speak ":fire: Deploy #{fetch(:branch)} to #{fetch(:stage)} reverted!" end end # Tests namespace :tests do task :run do puts "--> Running tests, please wait ..." system 'bundle exec kitty' test_log = fetch(:test_log) unless system "bundle exec rake > #{test_log} 2>&1" #' > /dev/null' puts "--> Tests failed. Run `cat #{test_log}` to see what went wrong." exit else puts "--> Tests passed :-)" system "rm #{test_log}" end end end before 'deploy:starting', 'tests:run' after 'deploy:started', 'campfire:started' after 'deploy:finished', 'campfire:finished' after 'deploy:reverted', 'campfire:reverted' after 'deploy:publishing', 'deploy:restart'<file_sep>/spec/models/reservation_spec.rb require 'spec_helper' describe Reservation do let(:instructor) { build(:instructor) } let(:course) { build(:course, instructor: instructor) } let(:student) { build(:student) } let(:reservation) { build(:reservation, student: student, course: course, stripe_token: 'foo') } it { should belong_to(:course) } it { should belong_to(:student) } it { should validate_presence_of(:course) } it { should validate_presence_of(:student) } before do Stripe::Customer.stubs(:create).with(anything).returns(stub(:id => 'cus_1')) Stripe::Charge.stubs(:create).with(anything).returns(stub()) end context "#instructor" do it "should be the instructor of the course" do reservation.instructor.should == instructor end end context "when a reservation is made" do it "delivers an enrollment notification" do reservation.expects(:send_enrollment_notification) reservation.save! end it "fails if student is already enrolled for that course" do reservation.save! reservation = Reservation.new reservation.student = student reservation.course = course reservation.save.should == false end end context "#charged?" do it "returns true if charge succeeded at is set" do reservation.charge_succeeded_at = Time.now reservation.should be_charged end it "returns false if charge succeeded at is not set" do reservation.charge_succeeded_at = nil reservation.should_not be_charged end end context "#charge_amount" do context "paid course" do before { course.price_per_seat_in_cents = 5000 } it "saves the course's price as charge amount when reservation created" do reservation.charge_amount.should be_nil reservation.save! reservation.charge_amount.should == 5000 end it "does not change the charge amount when course price changes" do reservation.save! course.price_per_seat_in_cents = 10000 reservation.save! reservation.reload.charge_amount.should == 5000 end end end context "#send_enrollment_notification" do before { reservation.save! } it "enqueues an enrollment notification job" do Resque.expects(:enqueue).with(EnrollmentNotification, reservation.id) reservation.send_enrollment_notification end end context "#send_enrollment_notification!" do it "notifies the instructor when a student enrolls" do InstructorMailer.expects(:student_enrolled). with(reservation).returns(mock 'mail', :deliver => true) reservation.send_enrollment_notification! end it "notifies the student that they enrolled" do StudentMailer.expects(:enrolled). with(reservation).returns(mock 'mail', :deliver => true) reservation.send_enrollment_notification! end end context "#check_campaign_success" do context "when minimum seats is zero" do before do course.min_seats = 0 reservation.save! end it "does not enqueue a job" do Resque.expects(:enqueue).never reservation.check_campaign_success end end context "when minimum seats is greater than zero" do context "when reservation satisfies minimum seats" do before do course.min_seats = 1 reservation.save! end it "enqueues a campaign success notification job" do Resque.stubs(:enqueue).with(ChargeCreditCards, course.id) # the other enqueue call Resque.expects(:enqueue).with(CampaignSuccessNotification, course.id) reservation.check_campaign_success end context "when workshop is free" do it "does not charge credit cards" do course.update_attribute(:price_per_seat_in_cents, 0) Resque.stubs(:enqueue).with(CampaignSuccessNotification, course.id) # the other enqueue call Resque.expects(:enqueue).with(ChargeCreditCards, course.id).never reservation.check_campaign_success end end context "when workshop is not free" do it "enqueues a charge credit cards job" do Resque.stubs(:enqueue).with(CampaignSuccessNotification, course.id) # the other enqueue call Resque.expects(:enqueue).with(ChargeCreditCards, course.id) reservation.check_campaign_success end end end context "when reservation is short of minimum seats" do before do course.min_seats = 2 reservation.save! end it "does not enqueue a job" do Resque.expects(:enqueue).never reservation.check_campaign_success end end context "when minimum seats has already been met" do before do course.min_seats = 1 course.save # Have to enroll as different student 2nd time other_student = create(:student) create(:reservation, course: course, student: other_student) reservation.save! end it "does not send a notification" do course.expects(:send_campaign_success_notifications!).never reservation.check_campaign_success end it "charges credit card for the reservation" do reservation.charged?.should be_false reservation.save! reservation.reload.charged?.should be_true end end end end end <file_sep>/app/assets/javascripts/lib/visual_select.js window.assert = (function(){ var assert = function(what) { if (!what) { throw new Error('Assertion failed'); } }; assert.el = function($el) { if (!$el || $el.length == 0) { throw new Error('Assertion failed'); } } return assert; })(); window.VisualSelect = (function(){ return Spine.Controller.sub({ elements: { 'input': '$input' }, events: { 'click .choice': 'selectAction' }, init: function() { this.$choices = this.$el; assert.el(this.$el); assert.el(this.$input); var id = this.$input.val(); if (id) { this.selectById(id); } else { // this.selectAtIndex(0); } }, children: function(selector) { var children = this.$choices.children(); // debugger; if (selector) { return children.filter(selector); } else { return children; } }, selectAction: function(ev) { var $target = $(ev.currentTarget); if ($target.hasClass('delete')) return; var $choice = $target.closest('.choice'); var index = this.children().index($choice); this.selectAtIndex(index); }, selectAtIndex: function(index) { var $choice = this.children().eq(index); this.selectObject($choice); }, selectById: function(id) { var $choice = this.children('[data-id=' + id + ']'); this.selectObject($choice); }, selectObject: function($choice) { this.children().removeClass('selected'); $choice.addClass('selected'); var id = $choice.attr('data-id'); this.$input.val(id); } }); })();<file_sep>/spec/controllers/reservations_controller_spec.rb require 'spec_helper' describe ReservationsController do let(:user) { create(:user) } let(:user_attributes) { attributes_for(:user) } let(:course) { create(:course) } let(:reservation) { build(:reservation, course: course) } let(:reservation_attributes) { attributes_for(:reservation, course: course) } let(:user_attributes) { attributes_for(:user) } before do sign_in user create(:schedule, course: course) end context "GET new" do render_views it "renders the new page" do get :new, course_id: course.to_param response.should be_success response.should render_template :new end it "initializes a new reservation for a course" do get :new, course_id: course.to_param assigns[:course].should_not be_nil assigns[:reservation].should_not be_nil end it "redirects to show if already enrolled" do create(:reservation, course: course, student: user) get :new, course_id: course.to_param response.should redirect_to landing_page_path(course.url) end end context "POST create" do let :customer do customer = stub(id: '123') customer.stubs(:card=) customer.stubs(:save) customer end before do Stripe::Customer.stubs(:create).returns(customer) end context "when course is paid" do it "creates customer with card token and saves customer token" do Stripe::Customer.expects(:create) .with(card: 'aaa', description: user.email) .returns(customer) post :create, course_id: course.to_param, reservation: reservation_attributes.merge(stripe_token: 'aaa') user.reload.stripe_customer_id.should == '123' end end context "with an existing user" do it "creates a reservation for the current user" do expect { post :create, course_id: course.to_param, reservation: reservation_attributes }.to change(user.reservations, :count) user.courses_as_student.last.should == course end it "redirects to the reservation" do post :create, course_id: course.to_param, reservation: reservation_attributes response.should redirect_to(course_reservation_path(course, assigns[:reservation])) end it "creates an event about reservation" do post :create, course_id: course.to_param, reservation: reservation_attributes Event.last.tap { |e| e.event_type.should == Event::STUDENT_ENROLLED e.user.should == user e.course.should == course } end end context "with a new user" do before(:each) do sign_out :user end it "creates a new user account" do expect { post :create, course_id: course.to_param, reservation: reservation_attributes, user: user_attributes }.to change(User, :count) end it "creates a reservation for the new user" do expect { post :create, course_id: course.to_param, reservation: reservation_attributes, user: user_attributes }.to change(course.reservations, :count) User.last.reservations.count.should == 1 User.last.reservations.last.course.should == course end it "signs in the new user" do post :create, course_id: course.to_param, reservation: reservation_attributes, user: user_attributes warden.authenticated?(:user).should == true end it "requires an email and password" do post :create, course_id: course.to_param, user: { email: '', password: '' } assigns(:user).errors.messages.should_not be_empty end end context "when submitting invalid data" do before do Reservation.any_instance.stubs(:save).returns(false) Reservation.any_instance.stubs(:valid?).returns(false) end it "renders the new page" do post :create, course_id: course.to_param, reservation: {} response.should render_template :new end end end context "GET show" do before { reservation.save } it "renders the show page" do get :show, course_id: course.to_param, id: reservation.to_param response.should be_success response.should render_template :show end end end <file_sep>/app/controllers/concerns/courses_editing_concern.rb module CoursesEditingConcern extend ActiveSupport::Concern STEPS = [ {id: 'details', mixpanel_event: 'Edit Course Details'}, {id: 'dates', mixpanel_event: 'Edit Course Dates'}, {id: 'location', mixpanel_event: 'Edit Course Location'}, {id: 'pricing', mixpanel_event: 'Edit Course Pricing'}, {id: 'page', mixpanel_event: 'Edit Course Landing Page'} ] included do helper_method :current_step helper_method :current_step_mixpanel_event helper_method :next_step end def prepare_steps if !current_step redirect_to :step => 'details' end end def current_step @steps ||= STEPS step = @steps.find { |s| s[:id] == params[:step] } step end def current_step_mixpanel_event current_step[:mixpanel_event] end def next_step index = @steps.index(current_step) @steps[index + 1] end protected def course_params params.require(:course).permit( :name, :url, :tagline, :starts_at, :ends_at, :description, :instructor_biography, :min_seats, :max_seats, :price_per_seat_in_dollars, :color, :logo, location_attributes: [ :name, :address, :address_2, :city, :state, :zip, :phone ], schedules_attributes: [ :date, :starts_at, :ends_at, :is_skipped ] ) end def find_course_as_instructor! @course = current_user.courses_as_instructor.find(params[:id]) rescue ActiveRecord::RecordNotFound redirect_to root_path end def find_course_by_url! @course = if params[:url].present? Course.find_by!(url: params[:url]) else Course.find(params[:id]) end @logo = @course.logo_if_present end end<file_sep>/db/migrate/20140120101504_courses_change_is_published.rb class CoursesChangeIsPublished < ActiveRecord::Migration def change remove_column :courses, :is_published, :boolean add_column :courses, :published_at, :datetime end end <file_sep>/app/jobs/course_created_notification.rb class CourseCreatedNotification @queue = :notifications def self.perform(id) course = Course.find(id) course.send_course_created_notification! end end <file_sep>/db/seeds.rb puts "Creating seed data" puts "==================" Course.delete_all User.delete_all Reservation.delete_all instructor = User.create!(email: "<EMAIL>", password: "<PASSWORD>") student = User.create!(email: "<EMAIL>", password: "<PASSWORD>") student1 = User.create!(email: "<EMAIL>", password: "<PASSWORD>") student2 = User.create!(email: "<EMAIL>", password: "<PASSWORD>") students = [student, student1, student2] puts "Created 4 users." location = Location.create!( name: "Moscone Center West", address: "250 4th Street", address_2: "Suite 150", city: "San Francisco", state: "CA", zip: "94107", phone: "403.288.1927" ) puts "Created 1 location." course1 = Course.create!( name: "Test-Driven Development for Rails", tagline: "Spend hours writing tests, but do it first.", starts_at: 3.days.from_now, ends_at: 3.days.from_now + 4.hours, campaign_ends_at: 1.day.from_now, description: "Level up as a developer that builds levels.", instructor: instructor, location: location, min_seats: 10, max_seats: 25, price_per_seat_in_cents: 85000, instructor_biography: "<NAME>Duck has taught 2 courses before." ) course2 = Course.create!( name: "How to launch your startup", tagline: "Learn how not to spend $5 MM in stealth mode building a product that nobody is going to buy", starts_at: 2.month.from_now, ends_at: 2.month.from_now + 4.hours, campaign_ends_at: 1.month.from_now, description: "Be YCombinator's next success after taking this class!", instructor: instructor, location: location, min_seats: 100, max_seats: 225, price_per_seat_in_cents: 1400000, instructor_biography: "<NAME> has taught 2 courses before." ) puts "Created 2 courses." # Students sign up for course 1 students.each do |student| Reservation.create!( course: course1, student: student ) end puts "Created 3 reservations."<file_sep>/docs/mvp_features.md # MVP Features This is pretty much exactly what's in [Trello](https://trello.com/board/workshop-platform/51b06b4d6024b43523001cf2), but it's a little easier to see in this format and discuss as a Pull Request. I'll update the Trello list once we have some decisions here. ## "Base" Features ### Instructor - sign up - create a paid workshop - create a free workshop - edit a workshop - edit the short url for a workshop - be notified when student enrolls - publish the workshop (make it live) - only I can view my workshop while in draft mode - get paid - send a broadcast to all enrolled students ### Student - enroll in a free workshop - enroll in a paid workshop (pay) ## Differentiated Features ### Instructor - promote my workshop via social media - WYSIWYG landing page editor (should this be in?) - set a minimum number of tickets threshold (kickstarter features) ### Student - enroll in a workshop from my mobile device - request a refund (cancel a ticket) - promote a workshop I enrolled in to my friends (kickstarter features) - be notified when minimum threshold gets met for a workshop (kickstarter features) - be notified when minimum threshold does not get met for a workshop (kickstarter features) - be notified when minimum threshold is close for a workshop (kickstarter features) ## Post-MVP Features ### Instructor - awesome onboarding (try before you buy) - course materials - early-bird and tiered pricing - expert advice - multi-day workshops - custom domains - re-teach my workshop - franchise my workshop - prompt students for feedback ### Student - ask the instructor a question - view other enrolled students - waiting lists for full workshops - give feedback on a workshop - request workshop be taught again <file_sep>/app/controllers/student/courses_controller.rb class Student::CoursesController < ApplicationController include Icalendar before_filter :authenticate_user! before_filter :find_course_as_student_by_id! before_filter :setup_markdown, only: [:show] def show end def calendar cal = Calendar.new course = @course course.schedules.each do |day| cal.event do dtstart day.starts_at_time.to_datetime dtend day.ends_at_time.to_datetime summary course.name location course.location.to_calendar_s end end cal.publish respond_to do |format| format.ics { render text: cal.to_ical } end end end<file_sep>/db/migrate/20130906185951_add_campaign_ending_soon_reminded_at_to_courses.rb class AddCampaignEndingSoonRemindedAtToCourses < ActiveRecord::Migration def change add_column :courses, :campaign_ending_soon_reminded_at, :datetime end end <file_sep>/docs/customers.md # Potential Customers ## Companies / Groups Already Offering Workshops - http://workshops.squarespace.com/ - http://therubyworkshop.com/ - http://workshops.railsbridge.org/ - Notice how they use EventBrite to manage ticket sales... [Example Workshop Listing](http://workshops.railsbridge.org/ai1ec_event/nyc-railsbridge-workshop/?instance_id=223) - http://workshop.bostonrb.org/ ## Enterprise Sales - Github: http://training.github.com/in-person/git-foundations/ - They should totally be using WP for their in-person courses - Twitter University: - They could use this to power all of their internal courses - Duke University - Rose Ritts - RedHat internal training team ## Example Workshops - http://www.yowconference.com.au/lambdajam/Clojure.html - http://gathers.us/events/everyday-python-by-ramece-cave - http://ruby201.eventbrite.com/ - http://www.meetup.com/Chicago-Python-Workshop/events/91720342/ - http://www.appworkshops.com/ - http://2012.leanstartup.co/workshops - http://www.enterpriseleanstartup.com/ - http://railsgirls.com/clt - http://hackeryou.com/workshops/ - Using ShopLocket to charge and a custom designed site - https://www.shoplocket.com/products/0VJ73-storytelling-with-data-introduction-to-data-visualization-best-practices - http://course.daeken.com/ - Using PageWiz for the landing page and EventBee for ticketing - Rackspace Traveling Workshops - http://unlocked.io/ - Designed a custom website that looks really nice... - But using the TERRIBLE cvent site for selling tickets. Wow it's ugly. - http://skillcrush.com/classes/skillcrush-101-create-your-own-website/ - Awesome page advertising her workshop! ## People To Reach Out To For Feedback - <NAME> - <NAME> - <EMAIL> - <NAME> - <NAME> - <NAME> - Why did he stop teaching his courses in person and switch to video only? - http://goodenoughsoftware.net/online-videos/ <file_sep>/spec/helpers/course_helper_spec.rb require 'spec_helper' describe CourseHelper do context "#reservations_needed" do it "returns zero if there are more reservations than the minimum number of seats" do course = create(:course, min_seats: 2) 3.times { create(:reservation, course: course) } reservations_needed(course).should == 0 end it "returns the minimum number of seats minus the number of reservations" do course = create(:course, min_seats: 10) 3.times { create(:reservation, course: course) } reservations_needed(course).should == 7 end it "returns question mark if min seats is not set" do course = create(:course, min_seats: nil) reservations_needed(course).should == "?" end end context "#days_until_start" do it "returns the number of days until the course starts if it's in the future" do current_time = "2013-08-01 12:00:00 UTC" starts_at = "2013-08-21 12:00:00 UTC" Timecop.freeze(current_time) do course = build(:course, starts_at: starts_at) days_until_start(course).should == 20 end end it "returns zero if it's in the past" do course = build(:course, starts_at: 20.days.ago) days_until_start(course).should == 0 end it "returns zero if it's today" do course = build(:course, starts_at: Date.today) days_until_start(course).should == 0 end it "returns question mark if starts_at is not set" do course = build(:course, starts_at: nil) days_until_start(course).should == "?" end end context "#percentage_to_full" do it "returns the percentage of reservations to max seats" do course = create(:course, max_seats: 20) 5.times { create(:reservation, course: course) } percentage_to_full(course).should == 25 end it "returns zero if max seats is not set" do course = create(:course, max_seats: nil) percentage_to_full(course).should == 0 end end context "#percentage_goal" do it "returns the percentage of min seats to max seats" do course = build(:course, min_seats: 10, max_seats: 20) percentage_goal(course).should == 50 end it "returns zero if max seats is not set" do course = build(:course, max_seats: nil) percentage_goal(course).should == 0 end it "returns zero if min seats is not set" do course = build(:course, min_seats: nil) percentage_goal(course).should == 0 end end context "#course_reservation_link" do it "returns a link to the course reservation page" do course = create(:course) price = number_to_currency(price_in_dollars(course.price_per_seat_in_cents)) link = link_to "Enroll - #{price}", new_course_reservation_path(course), :class => 'btn btn-primary btn-large reserve' course_reservation_link(course).should == link end end context "#facebook_og_meta_tags" do let(:course) { build(:course) } it "returns an og title with course title" do course.name = "My course" facebook_og_meta_tags(course).should =~ /meta property="og:title" content="My course"/ end it "returns an og description with course tagline" do course.tagline = "The best course EVAR!!!" facebook_og_meta_tags(course).should =~ /meta property="og:description" content="The best course EVAR!!!"/ end it "returns an og url with course short url" do course.url = "best-course-evar" facebook_og_meta_tags(course).should =~ /meta property="og:url" content=".*\/go\/best-course-evar"/ end it "returns an og image with enroll logo" do facebook_og_meta_tags(course).should =~ /meta property="og:image" content=".*\/assets\/images\/enroll-io-logo.png"/ end end end <file_sep>/docs/overview.md # Workshop Planner ## Meta-Goals - Develop a habit of shipping. - Ship in 4-8 weeks of part-time work. - Evaluate how well we all work together. - Test a market by shipping and see what comes next. - Spend no more than $500 per person. If we go to $1000, we’ll talk first. ## Meta Non-goals - Making lots of money - Finding the "next big thing" ## Product Goals A one-pager site for powering and promoting your workshop. ## Schedule **Release date: Tuesday, July 23, 2013** - "Fix Time and Budget, Flex Scope" -37 Signals - "Always launch on a Tuesday." -Jess ## Potential Names - CourseHoster - WorkShopper - WorkShopIt - TeachAnything - TeachIt - Host Your Course - WorkShopOut ## Potential Taglines - Teach Your Course. - Tools for Teaching. - Tools for Teachers. - We Organize. You Teach. - Teach Your Self. - Teach Your Stuff. ## Process - Objectives/Goals in a 1-pager - Name and tagline - Wireframes <file_sep>/db/migrate/20130803194803_add_url_to_courses.rb class AddUrlToCourses < ActiveRecord::Migration def change add_column :courses, :url, :string add_index :courses, :url end end <file_sep>/lib/paperclip_processors/backgroundize.rb module Paperclip class Backgroundize < Processor def initialize(file, options = {}, attachment = nil) @file = file @current_format = File.extname(@file.path) @basename = File.basename(@file.path, @current_format) @format = 'jpg' @is_enabled = options[:background] @size = options[:geometry].sub('#', '') @options = options end def make src = @file if !@is_enabled dst = create_temp_image(@basename) convert(":source :dest", source: File.expand_path(src.path), dest: File.expand_path(dst.path) ) return dst end # Add color overlay to image solid = create_temp_image("solid", "png") convert("-size #{@size} xc:rgba\\(237,226,198,0.6\\) :dest", dest: File.expand_path(solid.path) ) lightened_image = Tempfile.new(["lightened", ".jpg"]) Paperclip.run('composite', "-compose Screen -gravity center :change :base :output", change: File.expand_path(solid.path), base: File.expand_path(src.path), output: File.expand_path(lightened_image.path) ) # Blend image with bloom bloom_path = Rails.root.join("lib", "paperclip_processors", "bloom.jpg") bloomed_image = create_temp_image("bloomed") Paperclip.run('composite', "-compose Screen -gravity center :change :base :output", change: File.expand_path(bloom_path), base: File.expand_path(lightened_image.path), output: File.expand_path(bloomed_image.path) ) compressed_image = create_temp_image("#{@basename}_compressed") convert( "-strip -interlace Plane -quality 70% :source :dest", source: File.expand_path(bloomed_image.path), dest: File.expand_path(compressed_image.path) ) compressed_image end protected def create_temp_image(name, extension="jpg") file = Tempfile.new([name, ".#{extension}"]) file.binmode file end end end<file_sep>/lib/enroll.rb module Enroll puts "loading enroll" autoload :Config, 'enroll/config' extend Config end <file_sep>/app/jobs/campaign_ending_soon_notification.rb class CampaignEndingSoonNotification @queue = :notifications def self.perform(id) course = Course.find(id) course.send_campaign_ending_soon_notifications! end end <file_sep>/app/helpers/landing_helper.rb module LandingHelper def cover_image_style(course) return '' unless course.cover_image_object style = "background-image: url(#{course.cover_image(:main)}); " style += "background-position: center #{course.cover_image_object.offset_main_percent}%; " style end end<file_sep>/app/controllers/dashboard/students_controller.rb class Dashboard::StudentsController < ApplicationController before_filter :authenticate_user! before_filter :find_course! def find_course! @course = current_user.courses_as_instructor.find(params[:course_id]) rescue ActiveRecord::RecordNotFound redirect_to new_user_session_path end end <file_sep>/docs/training-industry.md # Training Industry ## Magazines / Periodicals / Blogs - http://www.learningsolutionsmag.com/ - http://www.trainingindustry.com/ ## Conferences - http://www.learningsolutionsmag.com/lscon/content/2988/learning-solutions-2014---conference-homepage/ - ## Books - http://usablelearning.com/the-book/ ## Initiatives - http://elearningmanifesto.org/ - http://www.learningsolutionsmag.com/articles/1366/learning-industry-experts-commit-to-disrupt-the-current-state-of-elearning - https://twitter.com/search?q=elearningmanifesto&src=typd - http://openbadges.org/ - <file_sep>/app/models/payout.rb class Payout < ActiveRecord::Base validates_presence_of :amount_in_cents, :description, :stripe_recipient_id attr_accessor :transfer state_machine :status, :initial => :pending do after_transition :on => :request, :do => [:transfer_funds!, :set_transfer_id] # Request a transfer of funds event :request do transition :pending => :requested end # A funds transfer has been completed event :complete do transition :requested => :paid end end # Required parameters for transferring funds: # https://stripe.com/docs/tutorials/sending-transfers # def transfer_params { :amount => amount_in_cents, :currency => 'usd', :recipient => stripe_recipient_id, :statement_descriptor => description } end # Initiate a funds transfer def transfer_funds! self.transfer = Stripe::Transfer.create(transfer_params) end def set_transfer_id if transfer && transfer.id self.stripe_transfer_id = transfer.id end end end <file_sep>/app/helpers/social_helper.rb module SocialHelper NETWORKS = { :facebook => "https://www.facebook.com/sharer/sharer.php?s=100&u=:url", :twitter => "https://twitter.com/intent/tweet?text=:text%20:url" } def share_button(network, target_url, label, text = '', cls = '') url = NETWORKS[network] return '' unless url url.sub!(':url', CGI.escape(target_url)) url.sub!(':text', CGI.escape(text)) content_tag :a, label, :href => '#', :class => "social #{network} #{cls}", :onclick => "window.open('#{url}', '#{network}-share-dialog', 'width=626,height=436'); return false;".html_safe end end<file_sep>/spec/spec_helper.rb # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/instafail' require 'vcr' require 'email_spec' require 'vcr' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration) VCR.configure do |c| c.cassette_library_dir = 'spec/cassettes' c.hook_into :webmock # or :fakeweb c.default_cassette_options = { :record => :once } # c.allow_http_connections_when_no_cassette = true c.configure_rspec_metadata! c.debug_logger = File.open('log/vcr.log', 'w') c.ignore_hosts 'api.mixpanel.com' c.ignore_hosts 'enroll-test-cover-images.s3.amazonaws.com' end RSpec.configure do |config| config.mock_with :mocha config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.treat_symbols_as_metadata_keys_with_true_values = true config.include FactoryGirl::Syntax::Methods # Authentication config.include Devise::TestHelpers, type: :controller # Aliases config.filter_run focused: true config.alias_example_to :fit, focused: true config.alias_example_to :pit, pending: true config.run_all_when_everything_filtered = true # config.render_views config.include EmailSpec::Helpers config.include EmailSpec::Matchers config.treat_symbols_as_metadata_keys_with_true_values = true config.before(:suite) do Resque.inline = true end end <file_sep>/app/controllers/student/resources_controller.rb class Student::ResourcesController < ApplicationController before_filter :authenticate_user! before_filter :find_course_as_student_by_course_id! def index @resources = @course.resources end end<file_sep>/spec/factories/blog_posts.rb # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :blog_post do title "MyString" content "MyString" author_id 1 published_at "2014-02-10 15:15:01" end end <file_sep>/docs/email-requesting-feedback.md Friends, Shay, Nick and I are working on a system to make it easier for people to market, manage and sell tickets for short courses, such as workshops. We were frustrated with the hodgepodge solutions available: instructors are forced to cobble together an event ticketing system with a separate marketing site and homegrown social media promotion tools. And don't even start on the course management tools out there. There simply is no one stop solution that allows teachers to simply teach, while facilitating an awesome teaching and learning experience. We believe with better tools available, more people will be able to share their knowledge through short courses and workshops, and generate extra income in the process. So here we go. We're building it. Where do you come in? You're a teacher. You've taught a workshop or a class or spoken at a local user group. You know the pain of trying to promote and organize and market and ticket. Creating the course materials is hard enough! We're building this system for you. We'd love to hear what would make your life easier. We've already built a prototype of the marketing site builder. Our goals is that it should take you less than 10 minutes to build your site promoting your course. You can check out our demo here: http://workshop-platform.herokuapp.com We've got a lot of other exciting features planned. Frankly, there are so many, we're not sure where to start! Take a look at some of our ideas below or at the bottom of the demo and do one of three things: 1. Give me (Jess) a call and tell me what you think: **979-215-6777**. Seriously, I'd love to hear from you. 2. Email us your thoughts, criticisms, and requests. We want this system to make your life easier. 3. [Pass the demo on](mailto:<EMAIL>,subject?) to someone you think might like to use it. We're busy little bees building this tool. We're hoping to launch the basic toolset soon, and we think it will already be head-and-shoulders better than anything you've used yet. If you'd like to keep receiving updates as we build, add your email here: http://workshop-platform.herokuapp.com/demo ## Possible Features Check out the [feature sketches](https://www.dropbox.com/sh/miiuyqsfnht2wwg/XdhEsTJSzq). - "Early Bird" Ticket Pricing @done - Mobile-Targeted Layouts @done - "Ask the Instructor" section for students @done - Hosted Course Materials (like slides, etc) @done - Student feedback to instructor @done - "Take me there!" mapping tool for students on their mobiles @done - Waiting List for full courses @done - Custom domain name @done - "Reteach" this course @done - Request refunds @done - Social media promotion tools @done - Auto-magic Testimonials constructed from previous student feedback @done - "Request this workshop" for students @done - Course email aliases - Advanced theming - Drip marketing tools ## Recipients *I'm thinking of people who either a) have taught courses/workshops before or b) have good product or design sense or c) both.* *Would be nice to have some people on this list who are not teaching on technical subjects.* - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def gravatar_for(email, options = {}) options = {:alt => 'avatar', :class => 'img-rounded', :size => 30}.merge! options id = email.blank? ? "00000000000000000000000000000000" : Digest::MD5::hexdigest(email.strip.downcase) url = 'https://www.gravatar.com/avatar/' + id + '.jpg?s=' + options[:size].to_s + '&d=retro' options.delete :size image_tag url, options end def icon(icon) ('<i class="icon-%s"></i>' % icon).html_safe end # Render that supports passing a block # Shortcut to `render layout: '...', locals: {...}` def yrender(partial, locals, &block) render(layout: partial, locals: locals, &block) end def short_date(date) return nil unless date date.strftime("%a,&nbsp;%b&nbsp;#{date.day.ordinalize}").html_safe end def long_date(date) return nil unless date date.strftime("%B %e, %Y") end end <file_sep>/app/helpers/format_helper.rb module FormatHelper def number_to_currency_from_cents(value, options={}) number_to_currency((value || 0) / 100.0, options) end def price_in_dollars(price_in_cents) (price_in_cents.to_f / 100) if price_in_cents end end <file_sep>/docs/paying_instructors.md # Paying Instructors A payout needs to be initiated with Stripe from our enroll account to the Instructor's bank account. For now, we'll initiate each transfer manually via the console since it involves moneys, and potentially large amounts of it. ## Initiate a payout via the console Find the course that needs to be paid out. ```ruby course = Course.find(some_id) => #<Course> course.title # check the title of the course => "Ruby on Rails for Beginners" course.pay_instructor! => true ``` Now I'd go check out the [Strie interface](https://manage.stripe.com) to make sure there's a transfer there. The transfer should be completed in the next 1-2 business days. <file_sep>/spec/mailers/admin_mailer_spec.rb require 'spec_helper' describe AdminMailer do let(:instructor) { build(:instructor, :email => "<EMAIL>") } let(:course) { build(:course, instructor: instructor, name: "Hackers 101", url: "hackers-101") } describe "#course_created" do let(:email) { AdminMailer.course_created(course) } it "delivers the course created notification" do email.should deliver_to("Enroll Support <<EMAIL>>") email.should deliver_from("Enroll <<EMAIL>>") email.should have_subject(/\[hackers-101\]/) end end end <file_sep>/app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def index update_visitor_id_from_marketing_token() mixpanel_track_event 'Welcome Page' if current_user return redirect_to courses_path end @user = User.new @course = Course.new end def about end protected def update_visitor_id_from_marketing_token if params[:i] token = MarketingToken.where(token: params[:i]).first return unless token cookies[:visitor_id] = token.distinct_id end end end <file_sep>/db/migrate/20140228081442_add_offset_to_cover_images.rb class AddOffsetToCoverImages < ActiveRecord::Migration def change add_column :cover_images, :offset, :float end end <file_sep>/README.md Enroll ====== ## Getting Started cp config/database.example.yml config/database.yml ./script/bootstrap bundle exec rake ### Documentation - [Overview](https://github.com/enroll/enroll/blob/master/docs/overview.md) - [Product Story](https://github.com/enroll/enroll/blob/master/docs/features.md) - [Competition](https://github.com/enroll/enroll/blob/master/docs/competition.md) - [Potential Customers](https://github.com/enroll/enroll/blob/master/docs/customers.md) - [User Stories](https://trello.com/b/vKPGr2jm/enroll-io-wip) (Trello) - [Deployment and CI](https://github.com/enroll/enroll/blob/master/docs/deployment.md) - [Paying Instructors](https://github.com/enroll/enroll/blob/master/docs/paying_instructors.md) <file_sep>/app/helpers/course_helper.rb include NavigationHelper include FormatHelper module CourseHelper def reservations_needed(course) return "?" unless course.min_seats needed = course.min_seats - course.reservations.count needed > 0 ? needed : 0 end def days_until_start(course) return "?" unless course.starts_at course.days_until_start end def percentage_to_full(course) return 0 unless course.max_seats (course.reservations.count.to_f / course.max_seats) * 100 end def percentage_goal(course) return 0 unless course.max_seats && course.min_seats (course.min_seats.to_f / course.max_seats) * 100 end def course_reservation_link(course, options={}) klasses = options[:class] ||= 'btn btn-primary btn-large reserve' path = new_course_reservation_path(course) if options[:disabled] klasses += ' disabled' path = '#' end link_to "Enroll - #{course_price_text(course)}", path, :class => klasses, :style => options[:style] end def course_price_text(course) if course.paid? number_to_currency(price_in_dollars(course.price_per_seat_in_cents)) else "FREE" end end def facebook_og_meta_tags(course) meta_tags = [] meta_tags << %Q[<meta property="og:title" content="#{course.name}" />] meta_tags << %Q[<meta property="og:description" content="#{course.tagline}" />] meta_tags << %Q[<meta property="og:url" content="#{course_short_url(course)}" />] meta_tags << %Q[<meta property="og:image" content="/assets/images/enroll-io-logo.png" />] meta_tags.join("\n").html_safe end def enrolled_for?(course) current_user && current_user.enrolled_for?(course) end def missing_label content_tag 'div', class: 'label label-error mini' do content_tag 'strong', 'Missing' end end def instructor_logged_in?(course) current_user && course.instructor == current_user end end <file_sep>/spec/controllers/student/resources_controller_spec.rb require "spec_helper" describe Student::ResourcesController do let(:student) { create(:student) } let(:course) { create(:course) } before { sign_in(student) reservation = create(:reservation, student: student, course: course) } describe "#index" do it "looks up all resources for course" do create(:resource, course: course) create(:resource, course: course) get :index, course_id: course.id response.should be_ok assigns(:resources).should_not be_nil assigns(:resources).length.should == 2 end end end<file_sep>/db/migrate/20131011013322_add_charge_succeeded_at_to_reservations.rb class AddChargeSucceededAtToReservations < ActiveRecord::Migration def change add_column :reservations, :charge_succeeded_at, :datetime end end <file_sep>/app/mailers/admin_mailer.rb class AdminMailer < ActionMailer::Base include MailersHelper helper :navigation def course_created(course) @instructor = course.instructor @course = course mail \ :to => enroll_support, :from => enroll_reply, :subject => "[#{@course.url_or_short_name}] New course created." end end <file_sep>/spec/controllers/dashboard/students_controller_spec.rb require 'spec_helper' describe Dashboard::StudentsController do let(:course) { build(:course) } let(:user) { create(:user) } context "GET index" do before { course.save } context "when logged in and course belongs to instructor" do before do course.update_attribute(:instructor_id, user.id) sign_in(user) end it "renders the index" do get :index, course_id: course.id response.should be_success response.should render_template :index end it "includes the course" do get :index, course_id: course.id assigns[:course].should_not be_nil end end context "when logged in and course does not belong to instructor" do before { sign_in(user) } it "redirects to login" do get :index, course_id: course.id response.should be_redirect response.should redirect_to(new_user_session_path) end end context "when not logged in" do it "redirects to login" do get :index, course_id: course.id response.should be_redirect response.should redirect_to(new_user_session_path) end end end end <file_sep>/spec/models/course_spec.rb require 'spec_helper' describe Course do let(:course) { build(:course) } it { should belong_to(:location) } it { should belong_to(:instructor) } it { should have_many(:reservations) } it { should have_many(:students) } it { should validate_presence_of(:name) } describe "#url" do before(:each) do course.save end context "when editing a saved resource url directly" do it "only allows valid subdomain characters" do course.url = 'fap fap fap' course.should_not be_valid course.errors[:url].should include('is not a valid URL') end it "must be unique" do new_course = create(:course) new_course.url = course.url new_course.should_not be_valid new_course.errors[:url].should include("has already been taken") end end end describe "#url_or_short_name" do it "shortens the course name to 20 characters when there is no url" do course.name = "Introduction to Ruby on Rails" course.url = nil course.url_or_short_name.should == "Introduction to Ruby" end it "returns url when there is a url" do course.name = "Introduction to Ruby on Rails" course.url = "intro-to-rails" course.url_or_short_name.should == "intro-to-rails" end end describe ".fail_campaigns" do context "when a course does not have the minimum reservations after the campaign end date" do before do course.campaign_ends_at = 1.day.ago course.min_seats = 2 course.save create(:reservation, course: course) end it "sends email notifications" do Resque.expects(:enqueue).with(CampaignFailedNotification, course.id) Course.fail_campaigns end it "marks the campaign as failed" do Course.fail_campaigns course.reload.campaign_failed_at.should_not be_nil end end context "when a course has the minimum reservations after the campaign end date" do before do course.campaign_ends_at = 1.day.ago course.min_seats = 1 course.save 2.times { create(:reservation, course: course) } end it "does not send email notifications" do Resque.expects(:enqueue).never Course.fail_campaigns end it "does not mark the campaign as failed" do Course.fail_campaigns course.reload.campaign_failed_at.should be_nil end end context "when the campaign end date has not arrived" do before do course.campaign_ends_at = 1.day.from_now course.min_seats = 2 course.save create(:reservation, course: course) end it "does not email" do Resque.expects(:enqueue).never Course.fail_campaigns end it "does not mark the campaign as failed" do Course.fail_campaigns course.reload.campaign_failed_at.should be_nil end end end describe "#send_campaign_failed_notifications!" do before do course.save create(:reservation, course: course) end it "notifies the instructor when the campaign fails" do InstructorMailer.expects(:campaign_failed). with(course).returns(mock 'mail', :deliver => true) course.send_campaign_failed_notifications! end it "notifies the student when the campaign fails" do student = course.students.first StudentMailer.expects(:campaign_failed). with(course, student).returns(mock 'mail', :deliver => true) course.send_campaign_failed_notifications! end end describe "#send_campaign_ending_soon_notifications!" do before do course.save create(:reservation, course: course) end it "notifies the student when the campaign fails" do student = course.students.first StudentMailer.expects(:campaign_ending_soon). with(course, student).returns(mock 'mail', :deliver => true) course.send_campaign_ending_soon_notifications! end end describe ".notify_ending_soon_campaigns" do context "when the campaign is under 48 hours from ending" do context "and minimums are met" do before do course.campaign_ends_at = 1.day.from_now course.min_seats = 1 course.save 2.times { create(:reservation, course: course) } end it "does not notify students" do Resque.expects(:enqueue).never Course.notify_ending_soon_campaigns end it "sets the course as having been reminded" do Course.notify_ending_soon_campaigns course.reload.campaign_ending_soon_reminded_at.should be_nil end end context "and minimums are not met" do before do course.campaign_ends_at = 1.day.from_now course.campaign_ending_soon_reminded_at = nil course.min_seats = 2 course.save create(:reservation, course: course) end it "notifies students that the end is nigh" do Resque.expects(:enqueue).with(CampaignEndingSoonNotification, course.id) Course.notify_ending_soon_campaigns end it "sets the course as having been reminded" do Course.notify_ending_soon_campaigns course.reload.campaign_ending_soon_reminded_at.should_not be_nil end end context "and campaign has already been reminded" do before do course.campaign_ends_at = 1.day.from_now course.min_seats = 2 course.campaign_ending_soon_reminded_at = Time.now course.save create(:reservation, course: course) end it "does not notify students" do Resque.expects(:enqueue).never Course.notify_ending_soon_campaigns end end end end describe "#charge_credit_cards!", :vcr do before do course.price_per_seat_in_cents = 1000 course.save @user = create(:student, email: '<EMAIL>') @stripe_token = Stripe::Token.create( :card => { :number => "4242424242424242", :exp_month => 10, :exp_year => 2014, :cvc => "314" }, ) @reservation = course.reservations.create( student: @user, stripe_token: @stripe_token.id ) end context "when user doesn't have a stripe customer" do before do Stripe::Charge.stubs(:create) end it "creates a customer" do Stripe::Customer.expects(:create) .with(card: @stripe_token.id, description: '<EMAIL>') .returns(stub(id: 1)) course.charge_credit_cards! end it "associates the customer with the user" do Stripe::Customer.stubs(:create).returns(stub(id: 1)) course.charge_credit_cards! @user.stripe_customer_id.should == 1 end end context "when user has a stripe customer" do before do customer = Stripe::Customer.create(card: @stripe_token.id) @user.update_attribute(:stripe_customer_id, customer.id) end it "does not create a customer" do Stripe::Customer.expects(:create).never end end context "when the reservation has not been charged" do before { @reservation.update_attribute(:charge_succeeded_at, nil) } it "charges the customer" do Stripe::Charge.expects(:create).with(has_entries(amount: 1000, currency: 'usd')) course.charge_credit_cards! end context "when charge succeeds" do it "updates the reservation with the charged date" do course.charge_credit_cards! @reservation.charge_succeeded_at.should_not be_nil end it "clears the token" do course.charge_credit_cards! @reservation.stripe_token.should be_nil end end context "when charge fails" do let(:exception) { Stripe::CardError.new("Card declined", "param", "code") } it "updates the reservation with the charge error" do Stripe::Charge.expects(:create).raises(exception) course.charge_credit_cards! @reservation.charge_failure_message.should == "Card declined" end it "charges other reservations" do @user.update_attribute(:stripe_customer_id, 1) user_two = create(:student, stripe_customer_id: 2) course.reservations.create(student: user_two) Stripe::Charge.expects(:create) .with(has_entry(customer: 1)) .raises(exception) Stripe::Charge.expects(:create) .with(has_entry(customer: 2)) course.charge_credit_cards! end end context "when there is no token and no stripe customer" do before do @reservation.update_attributes( charge_succeeded_at: nil, stripe_token: nil ) @user.update_attribute(:stripe_customer_id, nil) end it "logs an error message" do Raven.expects(:capture_message) course.charge_credit_cards! end it "doesn't create a customer" do Stripe::Customer.expects(:create).never course.charge_credit_cards! end end end context "when the reservation has been charged" do it "does not charge the customer" do @reservation.update_attribute(:charge_succeeded_at, Time.now) Stripe::Charge.expects(:create).never course.charge_credit_cards! end end it "charges the amount on the reservation even if it differs from course" do @reservation.charge_amount = 2000 Stripe::Charge.expects(:create).with(has_entries(amount: 2000, currency: 'usd')) course.charge_credit_cards! end it "does not charge when the course is free" do course.update_attribute(:price_per_seat_in_cents, 0) Stripe::Charge.expects(:create).never Stripe::Customer.expects(:create).never end end describe "#start_date" do it "returns a date value" do course.starts_at = Time.parse("January 1 2014 12:01 PM EST") course.start_date.should == "Wed, January 1, 2014" end it "returns nil if a start date isn't set" do course.starts_at = nil course.start_date.should be_nil end end describe "#start_time" do it "returns a time value" do course.starts_at = Time.parse("January 1 2014 12:01 PM EST") course.start_time.should == " 5:01 PM UTC" end it "returns nil if the start date isn't set" do course.starts_at = nil course.start_time.should be_nil end end describe "#end_time" do it "returns a time value" do course.ends_at = Time.parse("January 1 2014 4:01 PM EST") course.end_time.should == " 9:01 PM UTC" end it "returns nil if the end date isn't set" do course.ends_at = nil course.end_time.should be_nil end end describe "#location_attributes=" do before { course.location = nil } it "creates a location" do expect { course.location_attributes = { name: 'New Location' } course.location.should_not be_nil course.location.name.should == 'New Location' }.to change(Location, :count) end it "matches an existing location" do create(:location, name: 'Existing Location') expect { course.location_attributes = { name: 'Existing Location' } course.location.name.should == 'Existing Location' }.to_not change(Location, :count) end it "only creates a location if attrs are present" do expect { course.location_attributes = { name: '', address: '' } course.location.should be_nil }.to_not change(Location, :count) end it "changes attribute to blank value" do course.location_attributes = { name: 'Test', address: '' } course.location.address.should == '' end end describe ".future" do it "returns a course in the future" do course = create(:course, starts_at: Time.now + 1.day) Course.future.should include(course) end it "does not return a course in the past" do course = create(:course, starts_at: Time.now - 1.day) Course.future.should_not include(course) end it "returns a course that is today" do course = create(:course, starts_at: Time.now + 1.hour) Course.future.should include(course) end it "returns courses sorted with sooner courses first" do later_course = create(:course, starts_at: Time.now + 1.day) next_course = create(:course, starts_at: Time.now + 1.hour) Course.future.should == [next_course, later_course] end end describe ".past" do it "returns a course in the past" do course = create(:course, starts_at: Time.now - 1.day) Course.past.should include(course) end it "does not return a course in the future" do course = create(:course, starts_at: Time.now + 1.day) Course.past.should_not include(course) end it "does not return a course that is today" do course = create(:course, starts_at: Time.now + 1.minute) Course.past.should_not include(course) end it "returns courses sorted with most recent courses first" do long_ago_course = create(:course, starts_at: Time.now - 12.hours) recent_course = create(:course, starts_at: Time.now - 1.hour) Course.past.should == [recent_course, long_ago_course] end end describe ".without_dates" do it "returns a course without a date" do course = create(:course, starts_at: nil) Course.without_dates.should include(course) end it "does not return a course with a date" do course = create(:course, starts_at: Time.now + 1.day) Course.without_dates.should_not include(course) end end describe "#free?" do it "is true if price per seat is zero" do course.price_per_seat_in_cents = 0 course.should be_free end it "is false if price per seat is non-zero" do course.price_per_seat_in_cents = 10000 course.should_not be_free end end describe "#has_students?" do it "returns true if course has reservations" do create(:reservation, course: course) course.has_students?.should be_true end it "returns false if course has no reservations" do course.has_students?.should be_false end end describe "#send_campaign_success_notifications!" do before do course.save create(:reservation, course: course) end it "notifies the instructor when the course has met minimum enrollment" do InstructorMailer.expects(:campaign_succeeded). with(course).returns(mock 'mail', :deliver => true) course.send_campaign_success_notifications! end it "notifies the students when the course has met minimum enrollment" do student = course.students.first StudentMailer.expects(:campaign_succeeded). with(course, student).returns(mock 'mail', :deliver => true) course.send_campaign_success_notifications! end end describe "#future?" do context "has NO time schedule" do it "returns true if the start day is today" do course.starts_at = Date.today course.should be_future end it "returns false if the start day is yesterday" do course.starts_at = Date.today - 1.day course.should_not be_future end end context "has a time schedule" do before do course.starts_at = "2014-04-23" course.save! course.schedules_attributes = [{"date"=>"2014-04-23", "starts_at"=>"8:30am", "ends_at"=>"4:30pm"}] course.save! end it "returns true if starts in one minute" do Timecop.freeze(Time.new(2014, 4, 23, 8, 29)) course.should be_future Timecop.return end it "returns false if started a minute ago" do Timecop.freeze(Time.new(2014, 4, 23, 8, 31)) course.should_not be_future Timecop.return end end end describe "#campaign_failed?" do it "returns true if campaign failed at is not nil" do course.campaign_failed_at = Time.now - 1.hour course.should be_campaign_failed end it "returns false if campaign failed at is nil" do course.campaign_failed_at = nil course.should_not be_campaign_failed end end describe "#send_course_created_notification" do it "queues a course created notification when course is created" do Resque.expects(:enqueue).with(CourseCreatedNotification, kind_of(Integer)) create(:course) end it "does not queue a course created notification when existing course is saved" do course.save Resque.expects(:enqueue).never course.save end end describe "#send_course_created_notification!" do it "notifies the admins that a course has been created" do AdminMailer.expects(:course_created). with(course).returns(mock 'mail', :deliver => true) course.send_course_created_notification! end end describe "#pay_instructor!" do before do course.instructor.stripe_recipient_id = "asdf1234" course.name = "Some course name" course.starts_at = course.ends_at = 1.day.ago course.save end it "creates a Stripe payout" do CashRegister.expects(:instructor_payout_amount).with(course).returns(50123) Payout.expects(:create).with({ amount_in_cents: 50123, description: "Some course name", stripe_recipient_id: "<PASSWORD>" }).returns(stub 'payout', :request => true) course.pay_instructor! end context "payout initiates successfully" do before { Payout.stubs(:create).returns(stub 'payout', :request => true) } it "returns true" do course.pay_instructor!.should be_true end it "sets instructor_paid_at" do course.pay_instructor! course.reload.instructor_paid_at.should_not be_nil end end context "payout did NOT initiate successfully" do before { Payout.stubs(:create).returns(stub 'payout', :request => false) } it "returns false" do course.pay_instructor!.should be_false end it "does not set instructor_paid_at" do course.pay_instructor! course.reload.instructor_paid_at.should be_nil end end it "returns false if course has not happened yet" do Payout.stubs(:create).returns(stub 'payout', :request => true) course.ends_at = course.starts_at = 1.day.from_now course.pay_instructor!.should be_false end it "returns false if course is free" do Payout.stubs(:create).returns(stub 'payout', :request => true) course.price_per_seat_in_cents = nil course.pay_instructor!.should be_false end it "returns false if course has already been paid" do Payout.stubs(:create).returns(stub 'payout', :request => true) course.instructor_paid_at = 1.day.ago course.pay_instructor!.should be_false end end describe "#price_per_seat_in_dollars" do it 'does not fail when there is no price set' do course.price_per_seat_in_cents = nil course.price_per_seat_in_dollars.should == nil end end describe "#price_per_seat_in_dollars=" do it 'sets price in dollars as string' do course.price_per_seat_in_dollars = '20' course.price_per_seat_in_cents.should == 2000 end end describe "#schedules_attributes=" do it "preserves schedules between saves" do course.save! # only works on a saved course course.schedules_attributes = [{date: '2013-12-31', starts_at: '9:00am'}] course.save! course.schedules.count.should == 1 course.save! course.schedules.count.should == 1 end end describe "#as_json" do it "returns nil for date if date is nil" do course.starts_at = nil course.as_json[:starts_at].should == nil end end describe "#publish!" do it "publishes the course" do course.published?.should == false course.publish! course.reload.published?.should == true end end describe "#cover_image" do it "returns nil if there is no cover image" do course.cover_images.to_a.should == [] course.cover_image(:admin).should be_nil end it "returns url for image" do image = create(:cover_image, course: course) image.image.should_not be_nil course.cover_image(:admin).tap { |url| url.should_not be_nil url.should be_a(String) url.should include('enroll-test-cover-images.s3.amazonaws.com') } end end end <file_sep>/app/models/blog_post.rb class BlogPost < ActiveRecord::Base acts_as_url :title belongs_to :author, class_name: 'User' def publish! self.save! end end <file_sep>/app/jobs/enrollment_notification.rb class EnrollmentNotification @queue = :notifications def self.perform(id) reservation = Reservation.find(id) reservation.send_enrollment_notification! end end <file_sep>/app/models/event.rb class Event < ActiveRecord::Base include ActionView::Helpers::TextHelper COURSE_CREATED = 'course_created' PAGE_VISITED = 'page_visited' STUDENT_ENROLLED = 'student_enrolled' belongs_to :course belongs_to :user validates :event_type, :presence => true before_create :store_date def to_s if event_type == COURSE_CREATED "The course was created." elsif event_type == PAGE_VISITED "#{pluralize(self.count, 'student')} visited the course page." elsif event_type == STUDENT_ENROLLED "#{pluralize(self.count, 'student')} enrolled!" else "???" end end def self.create_event(event_type, options = {}) event = Event.new event.event_type = event_type event.course = options[:course] event.user = options[:user] event.save! end def self.grouped_by_date_and_type(options) course = options[:course] events = Event .select('date, event_type, count(1) as count, max(created_at) ts') .order('ts desc') .where('course_id = ?', course.id) .group('date, event_type') events.to_a.group_by(&:date) end protected def store_date self.date = Date.today end end <file_sep>/app/models/reservation.rb class Reservation < ActiveRecord::Base belongs_to :course belongs_to :student, class_name: 'User' delegate :instructor, to: :course validates :course, presence: true validates :student, presence: true validate :cannot_enroll_twice_for_the_same_course before_create :set_charge_amount_from_course after_create :send_enrollment_notification after_create :check_campaign_success def charged? charge_succeeded_at.present? end def set_charge_amount_from_course self.charge_amount = course.price_per_seat_in_cents end def send_enrollment_notification Resque.enqueue EnrollmentNotification, id end def send_enrollment_notification! InstructorMailer.student_enrolled(self).deliver StudentMailer.enrolled(self).deliver end def check_campaign_success return if course.min_seats == 0 if course.students.count == course.min_seats Resque.enqueue CampaignSuccessNotification, course.id end if course.paid? && course.students.count >= course.min_seats Resque.enqueue ChargeCreditCards, course.id end end def cannot_enroll_twice_for_the_same_course existing = Reservation.where(student_id: student.try(:id), course_id: course.try(:id)) unless new_record? existing = existing.where('id != ?', id) end if existing.first errors.add(:course, 'you are already enrolled for this course') end end end <file_sep>/db/migrate/20131011152047_add_charge_failure_message_to_reservations.rb class AddChargeFailureMessageToReservations < ActiveRecord::Migration def change add_column :reservations, :charge_failure_message, :string end end <file_sep>/docs/deployment.md ## Deploying on DigitalOcean/Other VPS Bootstrap new servers with: https://github.com/enroll/enroll-bootstrap ### Prepare SSH Edit `~/.ssh/config`: Host staging.enroll.io ForwardAgent yes Host enroll.io ForwardAgent yes Run `ssh-add`. ### Deploy Run: be cap staging deploy For production: be cap production deploy To deploy a specific branch: BRANCH=awesome cap staging deploy Deploying will also restart Resque worker to handle sending emails and other background tasks. **If server crashes it is needed to deploy the app, so that worker would get started!** (There is no automatic startup script.) ## Continuous Integration ### Janky The Janky CI server is deployed here: * http://enroll-janky.herokuapp.com The code we're running on our Janky CI server lives here: * https://github.com/enroll/janky ### Jenkins Jenkins is set up at http://ci.enroll.io or http://172.16.31.10, hosted on Linode. username: `jenkins` ### Hubot Branches should build automatically on Janky when they're pushed up to GitHub, but you can manually run a build in [Campfire](chat) with Hubot like: hubot ci build enroll/branch-name The Hubot server is deployed here: * http://enroll-hubot.herokuapp.com The code we're running on our Hubot server lives here: * https://github.com/enroll/hubot If you want to enable a specific [hubot-script](hubot-scripts), just add the script name to the [hubot scripts package](hubot-script-json), and redeploy the Hubot application on Heroku. [chat]: https://launchwise.campfirenow.com/room/564908 [hubot-scripts]: http://hubot-script-catalog.herokuapp.com [hubot-scripts-json]: https://github.com/enroll/hubot/blob/master/hubot-scripts.json <file_sep>/app/jobs/campaign_success_notification.rb class CampaignSuccessNotification @queue = :notifications def self.perform(id) course = Course.find(id) course.send_campaign_success_notifications! end end <file_sep>/app/controllers/dashboard/resources_controller.rb class Dashboard::ResourcesController < ApplicationController include Transloadit::Rails::ParamsDecoder before_filter :authenticate_user! before_filter :find_course_as_instructor_by_course_id! def index @resources = @course.resources end def new @resource = Resource.new end def create @resource = Resource.new(resource_params) @resource.course = @course if @resource.file? && !handle_transloadit_upload flash.now[:error] = "File upload failed" return render 'new' end if @resource.save flash[:notice] = "Resource was added" redirect_to dashboard_course_resources_path(@course) else render 'new' end end def destroy resource = @course.resources.find(params[:id]) resource.delete flash[:notice] = "Resource was deleted" redirect_to dashboard_course_resources_path(@course) end protected def resource_params params.require(:resource).permit(:name, :description, :s3_url, :resource_type, :link) end def transloadit_response params[:transloadit] end def handle_transloadit_upload unless transloadit_response && transloadit_response[:ok] && !transloadit_response[:results].empty? return false end @resource.s3_url = transloadit_response[:results][":original"].first[:url] @resource.transloadit_assembly_id = transloadit_response[:assembly_id] true end end<file_sep>/app/controllers/dashboard/landing_pages_controller.rb class Dashboard::LandingPagesController < ApplicationController include CoursesEditingConcern before_filter :find_course_as_instructor!, only: [:edit, :update] def edit end def update if @course.update_attributes(course_params) redirect_to edit_dashboard_landing_page_path(@course) else render 'edit' end end end<file_sep>/spec/controllers/admin/emails_controller_spec.rb require "spec_helper" describe Admin::EmailsController do before :each do request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('enroll', 'coffee') ActionMailer::Base.deliveries = [] end it "generates marketing token" do post :create, email: {emails: '<EMAIL>', content: 'hello', sender: '<EMAIL>'} MarketingToken.last.tap do |token| token.should_not be_nil token.token.should_not be_nil token.token.length.should == 2 token.distinct_id.should_not be_nil token.distinct_id.length.should > 10 end end it "sends an email to every address" do emails = "<EMAIL>,<EMAIL>\<EMAIL>" post :create, email: {emails: emails, subject: 'bazinga', content: 'hello', sender: '<EMAIL>', cc_us: '0'} ActionMailer::Base.deliveries.tap do |deliveries| deliveries.count.should == 3 deliveries[0].to.should == ['<EMAIL>'] deliveries[1].to.should == ['<EMAIL>'] deliveries[2].to.should == ['<EMAIL>'] deliveries.last.subject.should == 'bazinga' deliveries.last.body.raw_source.strip.should == 'hello' deliveries.last.from.should == ['<EMAIL>'] deliveries.last.cc.should == nil end end it "generates token for each email" do MarketingToken.count.should == 0 emails = "<EMAIL>,<EMAIL>\<EMAIL>" post :create, email: {emails: emails, subject: 'bazinga', content: 'hello', sender: '<EMAIL>'} MarketingToken.count.should == 3 MarketingToken.all.to_a.collect(&:email).should == ['<EMAIL>', '<EMAIL>', 'baz<EMAIL>'] end it "replaces mentions of enroll.io with the customized link" do emails = "<EMAIL>" content = "Hello there, check out http://enroll.io !" post :create, email: {emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>'} token = MarketingToken.last.token mail_content = ActionMailer::Base.deliveries.last.body.raw_source.strip mail_content.should == 'Hello there, check out http://enroll.io/?i=%s !' % [token] end it "tracks the mixpanel event with the token's distinct_id" do SecureRandom.expects(:base64).returns('SOME_DISTINCT_ID') mixpanel = Mixpanel::Tracker.any_instance mixpanel.expects(:set).with('SOME_DISTINCT_ID', {email: '<EMAIL>'}) mixpanel.expects(:track).with('Initial Marketing Email', {distinct_id: 'SOME_DISTINCT_ID'}) emails = "<EMAIL>" content = "Hello there, check out http://enroll.io !" post :create, email: {emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>', event: 'Initial Marketing Email'} end it "ccs to ourselves" do emails = "<EMAIL>" content = "Hello there, check out http://enroll.io !" post :create, email: { emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>', cc_us: '1' } ActionMailer::Base.deliveries.last.cc.should == ['<EMAIL>'] end it "uses the same token for an existing email address" do emails = "<EMAIL>" content = "Hello there, check out http://enroll.io !" post :create, email: {emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>'} post :create, email: {emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>'} MarketingToken.count.should == 1 end it "allows to select mixpanel event" do SecureRandom.expects(:base64).returns('SOME_DISTINCT_ID') mixpanel = Mixpanel::Tracker.any_instance mixpanel.stubs(:set) mixpanel.expects(:track).with('AWESOME EVENT', {distinct_id: 'SOME_DISTINCT_ID'}) emails = "<EMAIL>" content = "Hello there, check out http://enroll.io !" post :create, email: {emails: emails, subject: 'bazinga', content: content, sender: '<EMAIL>', event: 'AWESOME EVENT'} end end<file_sep>/config/routes.rb require 'resque/server' Enroll::Application.routes.draw do devise_for :users, :controllers => { :registrations => "users/registrations" } mount Resque::Server, :at => '/resque' resources :courses, only: [:index, :show, :preview] do resources :reservations resources :students, only: [:index] member do post :preview end end get '/courses/new/:step', to: 'courses#new', as: :new_course_step get '/courses/:id/edit/:step', to: 'courses#edit', as: :edit_course_step # Teacher dashboard namespace :dashboard do resources :courses do member do get :share get :review get :publish post :destroy_logo end resources :students, only: [:index] resources :resources resource :payment_settings, only: [:edit, :update] end resources :landing_pages resources :cover_images end # Student dashbaord namespace :student do resources :courses do resources :resources member do get :calendar end end end namespace :admin do resources :emails resources :posts end get '/admin', to: 'admin/emails#index' resource :account, only: [:edit, :update] do # resources :courses get :restore post :restore end resources :avatars get '/go/:url', to: 'courses#show', as: :landing_page get '/about', to: 'welcome#about', as: :about_page get '/blog', to: 'blog_posts#index', as: :blog_posts get '/blog/:id', to: 'blog_posts#show', as: :blog_post root 'welcome#index' end <file_sep>/spec/models/course_schedule_spec.rb describe CourseSchedule do it { should validate_presence_of(:course_id) } # it { should validate_presence_of(:date) } # it { should validate_presence_of(:starts_at) } # it { should validate_presence_of(:ends_at) } let(:schedule) { CourseSchedule.new(date: Date.today) } describe "#starts_at=, #ends_at=" do it "converts time string to seconds sicne midnight" do schedule.starts_at = "9:00am" schedule.ends_at = "5:00PM" schedule[:starts_at].should == 32400 schedule[:ends_at].should == 61200 end end describe "#starts_at" do it "converts seconds from midnight to time string" do schedule[:starts_at] = 32460 schedule[:ends_at] = 61320 schedule.starts_at.should == "09:01am" schedule.ends_at.should == "05:02pm" end end describe "#starts_at_time, #ends_at_time" do it "returns time object" do schedule[:starts_at] = 32460 schedule[:ends_at] = 61320 schedule.starts_at_time.to_date.should == Date.today schedule.starts_at_time.hour.should == 9 schedule.starts_at_time.min.should == 1 schedule.ends_at_time.hour.should == 17 schedule.ends_at_time.min.should == 2 end end end<file_sep>/app/models/location.rb class Location < ActiveRecord::Base has_many :courses, dependent: :destroy def as_json(options = {}) { name: name, address: address, city: city, state: state } end def to_s [name, city_and_state].select(&:present?).join(", ") end def city_and_state [city, state].select(&:present?).join(", ") end def city_and_zip_and_state [city, zip_and_state].select(&:present?).join(", ") end def zip_and_state [state, zip].select(&:present?).join(" ") end def address_1_and_2 [address, address_2].select(&:present?).join(", ") end def to_calendar_s [address_1_and_2, city_and_zip_and_state].select(&:present?).join(", ") end def to_full_s s = [] s << "<strong>#{name}</strong>" if name.present? s << address_1_and_2 if address_1_and_2.present? s << city_and_zip_and_state if city_and_zip_and_state.present? s.join("<br />").html_safe end end <file_sep>/spec/models/event_spec.rb require 'spec_helper' describe Event do it 'does not save without an event type' do e = Event.new e.save.should be_false end it 'stores date' do e = Event.new e.event_type = 'foo' e.save! e.date.should == Date.today end end <file_sep>/db/migrate/20130730224326_change_price_per_seat.rb class ChangePricePerSeat < ActiveRecord::Migration def change rename_column :courses, :price_per_seat, :price_per_seat_in_cents end end <file_sep>/app/controllers/admin/posts_controller.rb class Admin::PostsController < ApplicationController before_filter :authenticate_user! http_basic_authenticate_with :name => "enroll", :password => "<PASSWORD>" def index @posts = BlogPost.all end def new @post = BlogPost.new end def create @post = BlogPost.new(post_params) @post.author = current_user if @post.save @post.publish! redirect_to admin_posts_path else render 'new' end end def edit @post = BlogPost.find(params[:id]) end def update @post = BlogPost.find(params[:id]) @post.author ||= current_user if @post.update_attributes(post_params) redirect_to admin_posts_path else render 'edit' end end def destroy BlogPost.find(params[:id]).delete redirect_to admin_posts_path end protected def post_params params.require(:blog_post).permit(:title, :content, :intro, :published_at) end end<file_sep>/db/migrate/20130623223733_create_payouts.rb class CreatePayouts < ActiveRecord::Migration def change create_table :payouts do |t| t.string :stripe_transfer_id t.string :stripe_recipient_id t.string :status t.string :description t.integer :amount_in_cents end add_index :payouts, :status end end <file_sep>/docs/flows.md # Flows ## Instructor ### Creating a course - Landing page - Quick Course Creation - Title* - Short URL* - Tagline - Date - Location - Instructor Bio - Description - Free or paid? - Number of seats (minimum vs maximum capacity, 'kickstarter-esque') - Ticket price - Sign-up - Email - Password - Sign up with Facebook/other social services - Course Management - View Enrolled Students - Edit Course Landing Page - Contact Enrolled Students - Payment details - How to get - Get the Word Out (and modify your incentives) - Connect with Facebook - Connect with Twitter - Connect with Github - Connect with Google+ * = required ## Student ### Enrolling in a course - Workshop landing page for course - Date, location, cost, etc. - Who else is attending? and link to social profiles (http://frontenddesignconference.com/) - Progress towards "going live" / remaining seats (are earlier seats cheaper?) - Days until "campaign ends" vs Days until event? (golden path discussion) - Contact the instructor / ask a question (becomes public?) - Register for workshop - Name, personal details - Credit card details (authorize now, charge later) - Social links (if not linked to profile already) - Optional discount code - Confirmation / promotion - You won't be charged until later (authorize card) - Share this with your friends to receive a discount (pop-up) - Connect and authorize with any of these social services (and we'll pull your info in ;-) - Emailed receipt ### Classroom Experience - Event summary - Days until event - How do I get there (navigate me there) - What do I need? - Your profile is XX% complete - Edit profile - Connect to facebook, github, linkedin, etc - Attempt to auto-fill your bio and background, allow edits - Ask a question - Promote event with link / social connections - More (TBD) <file_sep>/spec/factories.rb FactoryGirl.define do factory :course do name { "Space Monkeys Learn Java" } tagline { "You'll be peeling XML bananas in no time." } starts_at { 2.weeks.from_now } ends_at { 2.weeks.from_now + 4.hours } campaign_ends_at { 1.week.from_now } campaign_failed_at { nil } campaign_ending_soon_reminded_at { nil } description { "Learn NetBeans, Eclipse, and Static Typing" } instructor_biography { "Professor <NAME> has been teaching for 40 years." } min_seats { 10 } max_seats { 25 } price_per_seat_in_cents { 14999 } url { "space-monkeys-learn-java" } # associations location instructor factory: :instructor end factory :cover_image do course image File.open(Rails.root.join('spec', 'fixtures', 'unicorn.jpg')) end factory :reservation do course student end factory :schedule, class: CourseSchedule do course date Date.today end factory :location do name "The Corner Pub" end factory :resource do name "MyString" description "MyString" s3_url "MyString" transloadit_assembly_id "MyString" end factory :event do end factory :payout do amount_in_cents 15000 # $150 USD description 'How to raise seed funding' stripe_recipient_id 12345 factory :payout_requested do status "requested" end factory :payout_completed do status "paid" end end factory :user do sequence(:email) {|n| "<EMAIL>" } password "<PASSWORD>" factory :student do sequence(:email) {|n| "<EMAIL>" } end factory :instructor do sequence(:email) {|n| "<EMAIL>" } end end end <file_sep>/app/models/cover_image.rb class CoverImage < ActiveRecord::Base ADMIN_HEIGHT = 242 MAIN_HEIGHT = 384 belongs_to :course has_attached_file :image, styles: { main: {geometry: "1688x9999>"}, admin: {geometry: "1130x9999>"}, background: {geometry: "2168x1626#", background: true} }, default_url: "/images/:style/missing.png", processors: [:thumbnail, :backgroundize], storage: 's3', s3_credentials: Enroll.s3_config_for('cover_images'), url: ':s3_domain_url', path: "/:class/:id_:basename.:style.:extension" validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ def as_json(options={}) { id: id, admin: image.url(:admin), background: image.url(:background) } end def offset_admin_px=(value) self.offset = value.to_f / ADMIN_HEIGHT.to_f end def offset_admin_px return 0 unless self.offset (self.offset * ADMIN_HEIGHT).to_i end def offset_main_px return 0 unless self.offset (self.offset * MAIN_HEIGHT).to_i end def offset_main_percent return 0 unless self.offset (self.offset.abs * 100).to_i end end<file_sep>/db/migrate/20130728213953_add_course_seats.rb class AddCourseSeats < ActiveRecord::Migration def change add_column :courses, :min_seats, :integer add_column :courses, :max_seats, :integer add_column :courses, :price_per_seat, :integer add_column :courses, :instructor_biography, :text rename_column :courses, :course_starts_at, :starts_at rename_column :courses, :course_ends_at, :ends_at add_column :locations, :address_2, :string end end <file_sep>/config/initializers/raven.rb # Sentry Exception Notification - http://getsentry.com # https://github.com/getsentry/raven-ruby#sentry_dsn require 'raven' Raven.configure do |config| config.dsn = 'https://6c21ec5fb70840c38a199d35facedc4d:3aa2984b908947deaa496fd998842734@app.getsentry.com/18653' end <file_sep>/spec/controllers/student/courses_controller_spec.rb require "spec_helper" describe Student::CoursesController do let(:student) { create(:student) } let(:course) { create(:course) } before(:each) do sign_in(student) reservation = create(:reservation, student: student, course: course) CourseSchedule.create!({ course_id: course.id, date: Date.new(2014, 4, 7), starts_at: "9:00am", ends_at: "5:30pm" }) end describe "#index" do it "finds student's course" do get :show, id: course.id response.should_not redirect_to(root_path) response.should be_ok assigns(:course).should == course end it "redirects to home if student doesn't own the course" do get :show, id: create(:course).id response.should redirect_to(root_path) end end describe "#calendar" do it "generates ical file" do get :calendar, id: course.id, format: 'ics' response.body.tap { |r| r.should include("DTSTART:20140407T090000") r.should include("DTEND:20140407T173000") } end end end<file_sep>/Gemfile source 'https://rubygems.org' source 'http://gems.github.com' ruby '2.0.0' gem 'rails', '~> 4.0.0' # Standard gems gem 'angularjs-rails' gem 'aws-sdk' gem 'coffee-rails', '~> 4.0.0' gem 'devise', '~> 3.0.1' gem 'dotenv-rails' gem 'entypo-rails' gem 'faraday', '0.8.8' gem 'haml', '~> 4.0.3' gem 'icalendar' gem 'jbuilder', '~> 1.0.1' gem 'jquery-rails' gem 'less' gem 'mail_gate', '1.1.2' gem 'mixpanel' gem 'paperclip' #, '2.4.5' gem 'pg' gem 'redcarpet' gem 'resque', '1.24.1' gem 'retina_tag' gem 'sass-rails', '~> 4.0.0' gem 'sentry-raven', '0.6.0' gem 'simple_form', '~> 3.0.0' gem 'spinjs-rails' gem 'state_machine', '1.2.0' gem 'stringex' gem 'stripe', '1.8.3' gem 'therubyracer' gem 'tilt-jade' gem 'transloadit-rails', '1.1.1' gem 'unicorn' gem 'uglifier', '>= 1.3.0' # ^- remember to keep this in alphabetical order # Production gems that need further explanation: # Try out bootstrap 3 gem 'bootstrap-sass', '~> 3.1.0' group :development, :test do gem 'factory_girl_rails' gem 'mocha', '~> 0.13.3', require: false gem 'rspec-instafail' gem 'rspec-rails' gem 'shoulda-matchers' gem 'vcr' gem 'email_spec' gem 'timecop' gem 'phantomjs' gem 'teaspoon' gem 'kitty' end group :test do gem 'webmock' end group :development do gem 'capistrano' gem 'capistrano-rails' gem 'capistrano-resque', git: 'https://github.com/sshingler/capistrano-resque.git', require: false gem 'capistrano-bundler' gem 'foreman' gem 'guard' gem 'guard-bundler' gem 'guard-rspec' gem 'guard-shell' gem 'letter_opener' gem 'pry-rails' gem 'tinder', '1.9.3' end group :production, :staging do gem 'rails_12factor' end <file_sep>/spec/helpers/format_helper_spec.rb require 'spec_helper' describe FormatHelper do context "#price_in_dollars" do it "returns the price in dollars" do helper.price_in_dollars(19999).should == 199.99 end it "returns nil if no price is passed in" do helper.price_in_dollars(nil).should == nil end end end <file_sep>/app/models/cash_register.rb class CashRegister def self.revenue(course) return 0 if course.free? course.price_per_seat_in_cents * course.reservations.count end # Stripe takes a 2.9% cut of every ticket sold and 30 cents per ticket STRIPE_CREDIT_CARD_PERCENTAGE = 0.029 # 2.9% STRIPE_CREDIT_CARD_TRANSACTION_FEE_IN_CENTS = 30 # $0.30 def self.credit_card_fees(course) return 0 if course.free? (revenue(course) * STRIPE_CREDIT_CARD_PERCENTAGE) + (course.reservations.count * STRIPE_CREDIT_CARD_TRANSACTION_FEE_IN_CENTS) end # Enroll takes a 3.1% cut of every ticket sold ENROLL_SERVICE_FEE_PERCENTAGE = 0.031 # 3.1% def self.gross_profit(course) return 0 if course.free? revenue(course) * ENROLL_SERVICE_FEE_PERCENTAGE end def self.instructor_payout_amount(course) revenue(course) - gross_profit(course) - credit_card_fees(course) end end<file_sep>/app/helpers/visual_select_helper.rb module VisualSelectHelper def visual_select_sequence @visual_select_counter ||= 0 @visual_select_counter += 1 end def visual_select(model, method, options = {}) collection = options[:collection] klass = options[:class] || "" form = options[:form] id = "visual-select-#{visual_select_sequence}" selector = "##{id}" capture_haml do haml_tag 'div', :class => "choices #{klass}", :id => id do haml_concat form.input_field(method, :as => :hidden) collection.each do |item| haml_tag 'div', :class => 'choice', :"data-id" => item[:id] do yield(item) end end end haml_tag "script" do haml_concat %{new VisualSelect({el: "#{selector}"})} end end end end
1ecaaa7dff2f056fc19de305ab2ffaa7c4594b8b
[ "Markdown", "JavaScript", "Ruby", "Shell" ]
130
Ruby
enroll/enroll
ac65bcd4d4859353272405d67019935e6a2e99e9
7d8a08ca06546051c0349a9f1191e511ca80ef42
refs/heads/master
<repo_name>SongSing/ClientScripts<file_sep>/old/script.js // These are old, get these: <a href='https://raw.githubusercontent.com/SongSing/ClientScripts/master/bumble.js'>https://raw.githubusercontent.com/SongSing/ClientScripts/master/bumble.js</a> // /* ***************************************************** */ /* ********* BUY ME A BIG BOTTLE OF JOGURT!! *********** */ /* ***************************************************** */ var settingsPath = "CSSettings.txt"; var emotesPath = "emotes.txt"; var network = client.network(); var defaults = [ "cmdSymbol;~", "botColour;red", "botName;Delibird", "emotes;on", "flashColour;gold", "etext;on", "stalkwords;", "ignorechals;off", "auth0;", "auth1;+", "auth2;+", "auth3;+", "auth4;", "sep;((sc))" ]; var initCheck = false; var sep = "⁄"; var scriptUrl = "https://raw.githubusercontent.com/SongSing/ClientScripts/master/script.js"; var emoteUrl = "https://raw.githubusercontent.com/SongSing/ClientScripts/master/Emotes"; var emotesCheck = false; var authSymbols = []; var emotesData; var emotesList; var acceptCommand = true; // commands format: command [param1];[param2] - desc // params not required obv var commands = [ "commands - Shows commands", "lookup [name] - Displays information about [name]", "pm [name] - Opens PM window with [name] selected", "pm [name]((sep))[message] - PMs user [name] with [message]", "ranking [name] - Opens ranking window and selects [name]", "changename [name] - Attempts to change your name to [name]", "setcommandsymbol [symbol] - Changes your command symbol to [symbol]", "setbotname [name] - Changes my name to [name]", "setbotcolour [colour] - Changes my colour to [colour]", "eval [string] - Runs [string] through a JavaScript evaluator. Can be used for math and things!", "emotes - Shows available emotes", "emotes [on/off] - Enables/disables emotes", "update - Checks for updates", "stalkwords - Shows a list of your stalkwords", "addstalkword [stalkword] - Adds [stalkword] to your stalkwords", "removestalkword [stalkword] - Removes [stalkword] from your stalkwords", "enrichedtext [on/off] - Enables or disables enriched text", "setauthsymbol [symbol] - Changes symbol used to denote auth", "setauthsymbol [symbol]((sep))[level] - Changes symbol used to denote [level]-level auth. [level] is an integer from 0 to 4", "setflashcolour [colour] - Changes the highlight colour of your name and stalkwords", "updateemotes - Downloads the emotes file", "ignorechallenges [on/off] - Enables or disables auto-ignored challenges", "setseparater [separater] - Sets the command parameter separater to [separater]" ]; function cs() { return getVal("cmdSymbol"); } function say(message, channel) { if (channel === undefined) { channel = client.currentChannel(); } network.sendChanMessage(channel, message); } function hexToRgb(hex) // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb { hex = hex.toString(); hex = hex.replace(/#/g, ""); var bigint = parseInt(hex, 16); var r = (bigint >> 16) & 255; var g = (bigint >> 8) & 255; var b = bigint & 255; return "(" + r + ", " + g + ", " + b + ")"; } function randomInt(arg1, arg2) { if (arg2 !== undefined) // randomInt(min, max) return Math.floor(Math.random() * (arg2 - arg1)) + arg1; else // randomInt(max) return Math.floor(Math.random() * arg1); } function checkForUpdate(silent) { sys.webCall(scriptUrl, function (resp) { checkUpdate(resp, silent); }); } function checkUpdate(resp, silent) { if (resp === undefined || resp === "") { printMessage("There was a problem checking for updates. (Are you connected to the internet?)"); return; } if (resp !== sys.getFileContent(sys.scriptsFolder + "scripts.js")) { printMessage("There's an update available! <a href='po:send/" + sep + sep + "doupdate'>(Click here to update)</a>"); } else if (silent === undefined || silent === false) { printMessage("No updates available at this time. (Surprisingly!)"); } } function cmp(x1, x2) { if (typeof x1 !== typeof x2) { return false; } else if (typeof x1 === "string") { if (x1.toLowerCase() === x2.toLowerCase()) { return true; } } return x1 === x2; } function getVal(key, setanyway, def) { if (setanyway === undefined) setanyway = true; if (def === undefined) { for (var i = 0; i < defaults.length; i++) { var s = defaults[i].split(";"); if (cmp(key, s[0])) { def = s[1].replace(/\(\(sc\)\)/g, ";"); break; } } } if (def === undefined) // still def = ""; if (sys.filesForDirectory(sys.getCurrentDir()).indexOf(settingsPath) === -1) { sys.writeToFile(settingsPath, ""); if (setanyway) setVal(key, def); return def; } var lines = sys.getFileContent(settingsPath).split("\n"); for (var i = 0; i < lines.length; i++) { if (cmp(lines[i].split(";")[0].toString(), key.toString())) { return lines[i].substr(lines[i].indexOf(";") + 1); } } if (setanyway) setVal(key, def); return def; } function escapeHTML(str) // stole from moogle bc lazy { var m = String(str); if (m.length > 0) { var amp = "&am" + "p;"; var lt = "&l" + "t;"; var gt = "&g" + "t;"; return m.replace(/&/g, amp) .replace(/</g, lt) .replace(/>/g, gt); } else { return ""; } } function setVal(key, val) { var lines = sys.getFileContent(settingsPath).split("\n"); var found = false; if (typeof (val) === "array") { val = val.join(sep); } val = val.toString(); for (var i = 0; i < lines.length; i++) { if (lines[i].split(";")[0] === key) { lines[i] = lines[i].split(";")[0] + ";" + val; found = true; break; } } if (!found) { lines.push(key + ";" + val); } sys.writeToFile(settingsPath, lines.join("\n")); } function randomWord() { var rs = ["Amazing!", "Fantastic!", "Whaddya know?!", "I bet your mom is proud!", "But are you truly happy?", "Or...?"]; var r = randomInt(rs.length); return rs[r]; } String.prototype.insert = function (index, string) { if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length); else return string + this; }; function botHTML(timestamp, colon, symbol) { if (timestamp === undefined) timestamp = true; if (colon === undefined) colon = true; if (symbol === undefined) symbol = true; return "<font color='" + getVal("botColour", "red") + "'>" + (timestamp ? "<timestamp />" : "") + "<b>" + (symbol ? "±" : "") + (getVal("emotes", "on") === "on" ? getVal("botName", "Delibird").withEmotes() : getVal("botName", "Delibird")) + (colon ? ":" : "") + "</font></b>"; } String.prototype.getMessage = function () { if (this.indexOf(":") !== -1) return this.substr(this.indexOf(":") + 2); return this; }; String.prototype.getUser = function () { return this.split(':')[0]; // users can't have colons in names }; String.prototype.parseCmdDesc = function () { var cmd = "<b>" + this.split(" ")[0] + "</b>"; var params = this.substr(this.split(" ")[0].length).split(" - ")[0]; var desc = this.substr(this.indexOf(" - ")); params = params.replace(/\(\(sep\)\)/g, getVal("sep")).replace(/\[/g, "<code>[").replace(/]/g, "]</code>"); desc = desc.replace(/\[/g, "<code>[").replace(/]/g, "]</code>"); var ret = "<a href='po:setmsg/" + this.substr(0, this.indexOf(" - ")) + "' style='text-decoration:none;'>" + cmd + "</a> " + params + desc; return ret; }; function getEmotes(force) { if (force === undefined) force = false; if (sys.filesForDirectory(sys.getCurrentDir()).indexOf(emotesPath) === -1 || force) { if (emotesCheck) return; emotesCheck = true; setVal("emotes", "off"); printMessage("Downloading emotes..."); sys.webCall(emoteUrl, function (resp) { if (resp === "") { printMessage("Couldn't download emotes. Turning emotes off."); setVal("emotes", "off"); return; } sys.writeToFile(emotesPath, resp); emotesData = resp; emotesList = ""; var e = emotesData.replace(/\r/g, "").split("\n"); for (var i = 0; i < e.length; i++) { emotesList += "<a href='po:appendmsg/:" + e[i].split("\\")[0] + ":'><img src='" + e[i].split("\\")[1] + "'></a> "; } printMessage("Emotes downloaded!"); setVal("emotes", "on"); emotesCheck = false; }); } } String.prototype.withEmotes = function () { if (sys.filesForDirectory(sys.getCurrentDir()).indexOf(emotesPath) === -1) { getEmotes(); } else { var e = emotesData.replace(/\r/g, "").split("\n"); var ret = this; for (var i = 0; i < e.length; i++) { ret = ret.replace(new RegExp("\:" + e[i].split("\\")[0] + "\:", "gi"), "<img src='" + e[i].split("\\")[1] + "'>"); } return ret; } }; String.prototype.enriched = function () { var ret = this.replace(/(^|\s|\<u\>|\<b\>)\/(.+)\/($|\s|\<\/u\>|\<\/b\>)/g, "$1<i>$2</i>$3") .replace(/(^|\s|\<i\>|\<b\>)_(.+)_($|\s|\<\/i\>|\<\/b\>)/g, "$1<u>$2</u>$3") .replace(/(^|\s|\<i\>|\<u\>)\*(.+)\*($|\s|\<\/i\>|\<\/u\>)/g, "$1<b>$2</b>$3"); ret = ret.replace(/(^|\s|\<u\>|\<b\>)\/(.+)\/($|\s|\<\/u\>|\<\/b\>)/g, "$1<i>$2</i>$3") .replace(/(^|\s|\<i\>|\<b\>)_(.+)_($|\s|\<\/i\>|\<\/b\>)/g, "$1<u>$2</u>$3") .replace(/(^|\s|\<i\>|\<u\>)\*(.+)\*($|\s|\<\/i\>|\<\/u\>)/g, "$1<b>$2</b>$3"); ret = ret.replace(/(^|\s|\<u\>|\<b\>)\/(.+)\/($|\s|\<\/u\>|\<\/b\>)/g, "$1<i>$2</i>$3") .replace(/(^|\s|\<i\>|\<b\>)_(.+)_($|\s|\<\/i\>|\<\/b\>)/g, "$1<u>$2</u>$3") .replace(/(^|\s|\<i\>|\<u\>)\*(.+)\*($|\s|\<\/i\>|\<\/u\>)/g, "$1<b>$2</b>$3"); return ret; }; String.prototype.fixLinks = function () { var text = this; var words = text.split(" "); for (var w = 0; w < words.length; w++) { var word = words[w]; if (word.length < 7) { continue; } var ind = word.indexOf("."); if (((cmp(word.substr(0, 7), "http://") && ind > 7) || (cmp(word.substr(0, 8), "https://")) && ind > 8) && ind !== -1 && word.length > ind + 1) { words[w] = "<a href='" + word + "'>" + word + "</a>"; } } return words.join(" "); }; function isPlayerBattling(id) { if (client.player == null) { return false; } return (client.player(id).flags & (1 << 2)) > 0; } function isPlayerOnline(name) { return client.id(name) !== -1; } function print(message, channel) { if (channel === undefined) { channel = client.currentChannel(); } client.printChannelMessage(message, channel, true); } function printMessage(message, channel) { print((cmp(getVal("emotes", "on"), "on") ? botHTML().withEmotes() : botHTML()) + " " + (cmp(getVal("emotes", "on"), "on") ? message.withEmotes() : message), channel); } function printBorder(channel) { print("<hr>", channel); } function header(text) { return "<b><u>" + text + "</u></b>"; } function center(text) { return "<table width='100%'><tr><td align='center'>" + text + "</td></tr></table>"; } Array.prototype.shuffle = function () { var count = this.length; var ret = new Array(); var rands = new Array(); var nos = new Array(); for (var i = 0; i < count; i++) { nos.push(i); } for (var i = 0; i < count; i++) { var r = randomInt(nos.length); rands.push(nos[r]); nos.removeAt(r); } for (var i = 0; i < count; i++) { ret.push(this[rands[i]]); } for (var i = 0; i < count; i++) { this.removeAt(0); } for (var i = 0; i < count; i++) { this.push(ret[i]); } return; }; Array.prototype.removeAt = function (ind) { this.splice(ind, 1); return; }; function sayMispelled(m, channel) { var words = m.split(" "); var newwords = ""; for (var i = 0; i < words.length; i++) { var word = words[i]; var fl = word[0]; var ll = word[word.length - 1]; var letters = new Array(); if (word.length === 1) { newwords += word + " "; continue; } for (var j = 1; j < word.length - 1; j++) { letters.push(word[j]); if (randomInt(6) === 2) { var l = "qwertyuiop[]\asdfghjkl;'zxcvbnm,./"; letters.push(l[randomInt(l.length)]); } } letters.shuffle(); var newword = fl + letters.join("") + ll; newwords += newword + " "; } newwords = newwords.substr(0, newwords.length - 1); // remove last space say(newwords, channel); } Array.prototype.indexOf = function (item) { if (cmp(this, item)) return 0; for (var i = 0; i < this.length; i++) { if (cmp(this[i], item)) { return i; } } return -1; }; String.prototype.indexOf = function (str) { if (str.length > this.length) return -1; if (cmp(str, this)) return 0; for (var i = 0; i < this.length; i++) { if (cmp(this.substr(i, str.length), str)) return i; } return -1; }; function flashStyle(text) { return "<i><span style='background:" + getVal("flashColour", "gold") + ";'>" + text + "</span></i><ping />"; } function init() { if (getVal("cmdSymbol", "::") === "::") // weird way to test if doesnt exist { sys.writeToFile(settingsPath, ""); // create file setVal("cmdSymbol", "~"); setVal("botName", "Delibird"); setVal("botColour", "red"); setVal("auth0", ""); setVal("auth1", "+"); setVal("auth2", "+"); setVal("auth3", "+"); setVal("auth4", ""); } if (sys.filesForDirectory(sys.getCurrentDir()).indexOf(emotesPath) === -1) { getEmotes(); } else { emotesData = sys.getFileContent(emotesPath); emotesList = ""; var e = emotesData.replace(/\r/g, "").split("\n"); for (var i = 0; i < e.length; i++) { emotesList += "<a href='po:appendmsg/:" + e[i].split("\\")[0] + ":'><img src='" + e[i].split("\\")[1] + "'></a> "; } } client.printHtml(botHTML() + " Hey, you're running cool client scripts, guy!"); client.printHtml(botHTML() + " Your command symbol is: <b>" + cs() + "</b>"); checkForUpdate(); } ({ beforeSendMessage: function (message, channel) { var m = message; if (m === "/~?") { sys.stopEvent(); printMessage("Your command symbol is: <b>" + cs() + "</b>"); } else if ((m.substr(0, cs().length) === cs() || m.substr(0, 2) === sep + sep) && acceptCommand) { sys.stopEvent(); m = m.replace(sep + sep, cs()); handleCommand(m.split(" ")[0].substr(cs().length), ((m.indexOf(" ") !== -1 && m.replace(/ /g, "").length < m.length) ? m.substr(m.indexOf(" ") + 1).split(getVal("sep")) : [undefined]), channel); } else if ((m.substr(0, cs().length) === cs() || m.substr(0, 2) === sep + sep) && !acceptCommand) { sys.stopEvent(); m = m.replace(sep + sep, cs()); acceptCommand = true; handleCommand(m.split(" ")[0].substr(cs().length), ((m.indexOf(" ") !== -1 && m.replace(/ /g, "").length < m.length) ? m.substr(m.indexOf(" ") + 1).split(getVal("sep")) : [undefined]), channel); } else { if (getVal("misspell", "off") === "on") { sys.stopEvent(); sayMispelled(m, channel); } } }, beforeChannelMessage: function (message, channel, html) { if (!initCheck) { initCheck = true; init(); } if (message.indexOf(": ") !== -1 && isPlayerOnline(message.getUser())) { var name = message.getUser(); var msg = message.getMessage(); var id = client.id(name); var colour = client.color(id); sys.stopEvent(); // ok lets do this msg = msg.replace(/ /g, " "); if (cmp(getVal("etext", "on"), "on")) msg = escapeHTML(msg).enriched(); var cmd = "po:send/" + sep + sep + "lookup " + name; var cmd2 = "po:setmsg/<timestamp />" + message.replace(/'/g, "((sq))"); msg = msg.replace(/\//g, sep); msg = msg.replace(new RegExp("(^|\\s)(" + escapeHTML(client.ownName()) + ")($|\\s)", "gi"), flashStyle("$1$2$3")); var stalkwords = getVal("stalkwords", ""); if (stalkwords !== "") { if (stalkwords.indexOf(sep) === -1) { stalkwords = [stalkwords]; } else { stalkwords = stalkwords.split(sep); } for (var i = 0; i < stalkwords.length; i++) { msg = msg.replace(new RegExp("(^|\\s)(" + escapeHTML(stalkwords[i]) + ")($|\\s)", "gi"), flashStyle("$1$2$3")); } } if (getVal("emotes", "on") === "on") msg = msg.withEmotes(); msg = msg.replace(new RegExp(sep, "g"), "/"); if (msg.indexOf("http") !== -1) msg = msg.fixLinks(); msg = msg.replace(/\<i\>\/(.+)\/\<\/i\>/g, "//$1//"); print("<a href='" + cmd2 + "' style='text-decoration:none; color:" + colour + ";'><timestamp /></a><a href='" + cmd + "' style='text-decoration:none; color:" + colour + ";'> " + (client.auth(id) > 0 ? (getVal("emotes", "on") === "on" ? getVal("auth" + client.auth(id)).withEmotes() : getVal("auth" + client.auth(id))) + "<b><i>" + name + ":</i>" : getVal("auth0") + "<b>" + name + ":") + "</b></a> " + msg, channel); } }, beforeChallengeReceived: function(challengeId, opponentId, tier, clauses) { if (getVal("ignoreChals", "off") === "on") { sys.stopEvent(); } }, onPlayerReceived: function(id) { var friendslist = getVal("friendslist", ""); if (friendslist === "") { return; } friendslist = (friendslist.indexOf(";") === -1 ? [ friendslist ] : friendslist.split(";")); for (var i = 0; i < friendslist.length; i++) { if (cmp(friendslist[i], client.name(id))) { printMessage(client.name(id) + " is <b><font color='green'>online!</font></b><ping />"); } } } }) function handleCommand(command, data, channel) { if (!acceptCommand) return; if (cmp(command, "commands") || cmp(command, "commandslist") || cmp(command, "commandlist")) { printBorder(); printMessage(header("Commands:")); for (var i = 0; i < commands.length; i++) { printMessage((cs() + commands[i]).parseCmdDesc()); } printBorder(); } else if (cmp(command, "lookup")) { var id = client.id(data[0]); var user = client.name(id); // for correct case if (id === -1) { printMessage("That user is not on the server!"); return; } var avatar = client.player(id).avatar; var htr = hexToRgb(client.color(id)); print("<hr>"); print(center(botHTML() + " Here's info for " + user + ":<br /><br /><img src='trainer:" + avatar + "'></img><h3><i><font color='" + client.color(id) + "'>" + user + "</font></i></h3><h4>" + "ID: " + client.id(user) + "<br />" + "Auth Level: " + client.auth(id) + "<br />" + "Ignoring?: " + (client.isIgnored(id) ? "Yes" : "No") + "<br />" + "Colour: <font color='" + client.color(id) + "'><b>" + client.color(id) + "</b></font> / " + htr + "<br />" + "Tiers: " + client.tiers(id).join(", ") + "<br />" + "Actions: <a href='po:pm/" + id + "'>PM</a>, <a href='po:info/" + id + "'>Challenge</a>" + (isPlayerBattling(id) ? ", <a href='po:watchplayer/" + id + "'>Watch Battle</a>" : "") + ", " + "<a href='po:ignore/" + id + "'>Toggle Ignore</a>, " // dont say ignore/unignore bc after you ignore 'toggle ignore' is still relevant + "<a href='po:send/" + sep + sep + "ranking " + user + "'>View Rank</a>" + "</h4>")); print("<hr>"); } else if (cmp(command, "ranking")) { if (data[0] === undefined) { acceptCommand = false; say("/ranking"); return; } var id = client.id(data[0]); if (client.getTierList().indexOf(data[0]) !== -1) { acceptCommand = false; say("/ranking " + data[0]); return; } client.seeRanking(id); } else if (cmp(command, "pm")) { var id = client.id(data[0]); if (id === -1) { printMessage("Cannot PM that player!"); return; } client.startPM(id); if (data.length > 1) { network.sendPM(id, data[1]); } } else if (cmp(command, "changename")) { var name = data[0]; client.changeName(name); } else if (cmp(command, "setcommandsymbol") || cmp(command, "setcs")) { var symbol = data[0]; if (symbol !== undefined && symbol.length === 1) { setVal("cmdSymbol", symbol); printMessage("Changed command symbol to: <b>" + symbol + "</b>"); } else { printMessage("There was something wrong with the command symbol specified. Command symbols must be one character in length! <b>You've got more sense than that, " + client.ownName() + "!</b>"); } } else if (cmp(command, "setbotname")) { var name = data[0]; if (name !== undefined && name.replace(/ /g, "").length > 0) { setVal("botName", name); printMessage("Call me " + botHTML(false, false, false) + "!"); } else { printMessage("There was something wrong with the name you specified. Make sure it's at least one non-space character!"); } } else if (cmp(command, "setbotcolor") || cmp(command, "setbotcolour")) { var color = data[0]; if (color !== undefined) { setVal("botColour", color); printMessage("Your colour was interpreted as: " + botHTML(false, false, false)); printMessage("Colour changed!"); } else { printMessage("What colour?"); } } else if (cmp(command, "eval")) { if (data[0] !== undefined) { print(eval(data[0])); } else { printMessage("Something went wrong. <b><i>It was your fault.</i></b> (What are you trying to eval?)"); } } else if (cmp(command, "emotes")) { if (data[0] === undefined || (!cmp(data[0], "on") && !cmp(data[0], "off"))) { if (cmp(getVal("emotes", "on"), "on")) { print("<hr><br>" + botHTML() + " Here's all of the emotes:<br><br>" + emotesList + "<br><hr>"); } else { printMessage("Emotes are currently off. <a href='po:send/" + sep + sep + "emotes on'>(Turn on)</a>"); } } else if (cmp(data[0], "off")) { setVal("emotes", "off"); printMessage("Emotes have been disabled. :)"); } else if (cmp(data[0], "on")) { if (sys.filesForDirectory(sys.getCurrentDir()).indexOf(emotesPath) === -1) { getEmotes(); return; } setVal("emotes", "on"); printMessage("Emotes have been enabled. :)"); } } else if (cmp(command, "update")) { checkForUpdate(); } else if (cmp(command, "doupdate")) { printMessage("Updating..."); sys.webCall(scriptUrl, function (resp) { if (resp === undefined || resp === "") { printMessage("Couldn't update! Are you connected to the internet?"); return; } printMessage("Updated! Backup at: " + sys.scriptsFolder + "backup.js"); print((center("<hr><h1><u>What's new?</u></h1><br>" + resp.substr(3, resp.substr(3).indexOf("//")).replace(/\(\(cs\)\)/g, cs()) + "<br><hr>")).withEmotes()); sys.writeToFile(sys.scriptsFolder + "backup.js", sys.getFileContent(sys.scriptsFolder + "scripts.js")); sys.changeScript(resp); sys.writeToFile(sys.scriptsFolder + "scripts.js", resp); }); } else if (cmp(command, "addstalkword")) { if (data[0] !== undefined) { var stalkwords = getVal("stalkwords", ""); if (stalkwords !== "") { if (stalkwords.indexOf(sep) === -1 || (sep + stalkwords).indexOf(sep + data[0]) === -1) { stalkwords += sep + data[0]; setVal("stalkwords", stalkwords); printMessage("\"" + data[0] + "\" was added to your stalkwords! <b>" + randomWord() + "</b>"); } else { printMessage("That's already a stalkword you peporini piza! <a href='po:send/" + sep + sep + "stalkwords'>(View stalkwords)</a>"); } } else { setVal("stalkwords", data[0]); printMessage("\"" + data[0] + "\" was added to your stalkwords! <b>" + randomWord() + "</b>"); } } else { printMessage("Go on...."); } } else if (cmp(command, "removestalkword")) { if (data[0] !== undefined) { var stalkwords = getVal("stalkwords", ""); if (stalkwords !== "") { if (!cmp(stalkwords, data[0]) && stalkwords.split(sep).indexOf(data[0]) === -1) { printMessage("That's not one of your stalkwords!!!! <a href='po:send/" + sep + sep + "stalkwords'>(View stalkwords)</a>"); return; } if (cmp(stalkwords, data[0])) { stalkwords = ""; } else { var _stalkwords = stalkwords.split(sep); _stalkwords.splice(_stalkwords.indexOf(data[0]), 1); stalkwords = _stalkwords.join(sep); } setVal("stalkwords", stalkwords); printMessage("\"" + data[0] + "\" removed from stalkwords! <b>" + randomWord() + "</b>"); } } } else if (cmp(command, "stalkwords")) { printBorder(); printMessage(header("Stalkwords:")); var stalkwords = getVal("stalkwords", ""); if (stalkwords === "") { printMessage("No stalkwords! <a href='po:setmsg" + sep + sep + "addstalkword [stalkword]'>(Add stalkword)</a>"); return; } stalkwords = stalkwords.split(sep); var _stalkwords = stalkwords; for (var i = 0; i < stalkwords.length; i++) { var stalkword = stalkwords[i]; if (stalkword === undefined || stalkword.replace(/ /g, "") === "") // just to be safe! { _stalkwords.splice(stalkwords.indexOf(stalkword), 1); continue; } printMessage("" + stalkword + " <a href='po:send/" + sep + sep + "removestalkword " + stalkword + "'>(Remove)</a>"); } setVal("stalkwords", _stalkwords.join(sep)); printBorder(); } else if (cmp(command, "enrichedtext")) { if (data[0] === undefined) { printMessage("On or off?"); return; } if (cmp(data[0], "on")) { setVal("etext", "on"); printMessage("Enriched text was enabled!"); } else if (cmp(data[0], "off")) { setVal("etext", "off"); printMessage("Enriched text was disabled!"); } else { printMessage("What? On or off?"); } } else if (cmp(command, "setas") || cmp(command, "setauthsymbol")) { if (data[0] !== undefined && data[0].replace(/ /g, "").length > 0) { if (data.length === 1) { setVal("auth1", data[0]); setVal("auth2", data[0]); setVal("auth3", data[0]); printMessage("Auth 1-3 symbol changed to: " + data[0]); } else if (data[1].length > 0) { var p = parseInt(data[1]); if (p < 0 || p > 4 || p.toString() === "NaN") { printMessage("Auth levels are 0-4."); return; } setVal("auth" + p, data[0].toString()); printMessage(data[1].toString() + "-level auth is now denoted by: " + data[0]); } } else { printMessage("<b>???</b>"); } } else if (cmp(command, "clearas") || cmp(command, "clearauthsymbol")) { if (data[0] !== undefined) { var p = parseInt(data[0]); if (p < 0 || p > 4 || p.toString() === "NaN") { printMessage("Auth levels are 0-4."); return; } setVal("auth" + p, ""); printMessage("Auth symbol for level-" + p + " auth was cleared!"); } } else if (cmp(command, "setflashcolour") || cmp(command, "setflashcolor") || cmp(command, "setfc")) { if (data[0] === undefined) { printMessage("Set it to what?!?!? <b>COME ON!</b>"); return; } setVal("flashColour", data[0]); printMessage("Flash colour changed, " + flashStyle(client.ownName()) + "!"); } else if (cmp(command, "updateemotes")) { getEmotes(true); } else if (cmp(command, "ignorechals") || cmp(command, "ignorechallenges")) { if (data[0] === undefined || (!cmp(data[0], "off") && !cmp(data[0], "on"))) { printMessage("What? <a href='po:send/" + sep + sep + "ignorechallenges on'>On</a> or <a href='po:/send" + sep + sep + "ignorechallenges off'>off</a>?"); return; } setVal("ignoreChals", data[0].toLowerCase()); printMessage("Auto-ignore challenges was turned " + data[0].toLowerCase() + "!"); } else if (cmp(command, "setsep") || cmp(command, "setseparater")) { if (data[0] === undefined) { printMessage("what"); return; } setVal("sep", data[0]); printMessage("Command parameter separater was changed to: <b>" + data[0] + "</b>"); } else if (cmp(command, "whatsnew")) { var resp = sys.getFileContent(sys.scriptsFolder + "scripts.js"); print((center("<hr><h1><u>What's new?</u></h1><br>" + resp.substr(3, resp.substr(3).indexOf("//")).replace(/\(\(cs\)\)/g, cs()) + "<br><hr>")).withEmotes()); } else if (cmp(command, "setmsg")) { if (data[0] === undefined) { return; } // fuck } else if (cmp(command, "addfriend")) { if (data[0] === undefined) { printMessage("Add who?"); return; } var friendslist = getVal("friendslist", ""); if (friendslist === "") { setVal("friendslist", data[0]); printMessage(data[0] + " was added to your friends list!"); return; } friendslist = (friendslist.indexOf(";") === -1 ? [ friendslist ] : friendslist.split(";")); if (friendslist.indexOf(data[0]) !== -1) { printMessage("That person is already on your friends list!"); return; } friendslist.push(data[0]); setVal("friendslist", friendslist.join(";")); printMessage(data[0] + " was added to your friends list!"); } else if (cmp(command, "removefriend")) { if (data[0] === undefined) { printMessage("Remove who?"); return; } var friendslist = getVal("friendslist", ""); if (friendslist === "") { printMessage("Your friends list is empty!"); return; } friendslist = (friendslist.indexOf(";") === -1 ? [ friendslist ] : friendslist.split(";")); if (friendslist.indexOf(data[0]) === -1) { printMessage("That person is not on your friends list!"); return; } friendslist = friendslist.splice(friendslist.indexOf(data[0]), 1); setVal("friendslist", (friendslist.length === 0 ? "" : (friendslist.length === 1 ? friendslist : friendslist.join(";")))); printMessage(data[0] + " was removed from your friends list!"); } else if (cmp(command, "friendslist")) { var friendslist = getVal("friendslist", ""); if (friendslist === "") { printMessage("Your friends list is empty!"); return; } friendslist = (friendslist.indexOf(";") === -1 ? [ friendslist ] : friendslist.split(";")); printBorder(); printMessage(header("Friends:")); for (var i = 0; i < friendslist.length; i++) { printMessage(friendslist[i] + " <a href='po:sendmsg/" + sep + sep + "removefriend " + friendslist[i] + "'>(Remove)</a>"); } printBorder(); } else { //printMessage("<b>" + cs() + command + "</b> is not a command! <a href='po:send/" + cs() + "commands'>View commands</a>"); acceptCommand = false; say("/" + command + (data.length > 0 ? " " + data.join(getVal("sep")) : "")); } } <file_sep>/README.md ClientScripts ============= these will be great one day i promise Info ==== credtis go to mogle and unownone for passibely helpin me to learn things How To Install ============== GO TO BUMBLE.JS GO TO RAW C/P INTO SCRIPT WINDOW VERY EASE
ce3f8b510386024394508e6f292dc37dd03b4a2e
[ "JavaScript", "Markdown" ]
2
JavaScript
SongSing/ClientScripts
56df275d425ba048a4c15d14574a99cb497f2a83
c246155f09f7666f2a4f8cc02245101aee9c18e2
refs/heads/master
<repo_name>tpodgorski91/FileSearcher<file_sep>/file_searcher.py import os import platform import psutil import subprocess from pathlib import Path from typing import List def list_drives(): system_name = platform.system() method = { "Linux": list_drives_linux, "Darwin": list_drives_mac, "Windows": list_drives_win, }[system_name] return method() def list_drives_linux() -> List[str]: """ :return: list of user drives on Linux """ drives = [ partition.mountpoint for partition in psutil.disk_partitions() ] return drives def list_drives_mac() -> List[str]: """ :return: list of user drives on either Windows or macOS """ drives = [ partition.device for partition in psutil.disk_partitions() ] return drives def list_drives_win() -> List[str]: import psutil """ :return: list of user drives on either Windows or macOS """ drives = [ partition.device for partition in psutil.disk_partitions() ] return drives def show_drives_list(): if platform.system() == "Windows" and len(list_drives()) == 1: exclude = {'New folder', 'Windows', 'Desktop', 'Program Files', 'Documents and Settings', 'Program Files (x86)', 'ProgramData', 'Quarantine', 'Recovery', 'TEMP'} for root, dirs, files in os.walk('C:\\', topdown=True): dirs[:] = [d for d in dirs if d not in exclude] return dirs else: for drive in list_drives(): print(drive) def file_pattern(): """ :return: list of files and search pattern match """ dirname = input("Please choose from above one valid directory where file is stored and type it below." "\nChoice should be exactly the same as one from above.") file_name = input("Please provide either entire or portion of file name.") if platform.system() == "Windows" and len(list_drives()) == 1: result = sorted(Path(f"C:\\{dirname}").rglob(f'*{file_name}*.*')) else: result = sorted(Path(dirname).rglob(f'*{file_name}*.*')) return result def list_files(): files_list = [] for index, file_loc in enumerate(file_pattern()): print(index, file_loc) file_loc = str(file_loc) files_list.append(file_loc) if len(files_list) == 0: print("Nothing found." "\nPlease consider your choice and try again.") file_pattern() return files_list def open_file_from_list(index): if platform.system() == "Windows": os.startfile(look_for_file[index]) elif platform.system() == "Darwin": subprocess.Popen(["open", look_for_file[index]]) else: subprocess.Popen(["xdg-open", look_for_file[index]]) def choose_index(): """ :return: opens chosen file from the list base on list index """ try: list_index = int(input("Choose index number corresponding to the file.\n")) while list_index < 0: print("Index number should equals 0 or higher.\nPlease try again.") list_index = int(input("Choose index number corresponding to the file.\n")) else: open_file_from_list(list_index) except IndexError: if len(look_for_file) != 0: print(f"Incorrect index number selected. Number should be between 0 and {(len(look_for_file)) - 1}" "\nPlease try again.") else: print("Something went wrong please try again" "\n") show_drives_list() file_pattern() choose_index() except ValueError: print("Selected index number is not a number." "\nPlease try again.") choose_index() if __name__ == '__main__': print(show_drives_list()) look_for_file = list_files() choose_index() <file_sep>/README.md # file_searcher The project goal is to open specific file in dedicated application (e.g. for Windows ".txt" files it would be "Notepad") in different OS like: Windows, macOS, Linux, based on user inputs like: drive name where file is stored file name (may be only portion of name) 1. DONE User chooses drive where would like to look for .txt, .jpg file. input()? 2. User provides either whole or part of name provided. DONE regex 3. User chooses specific file from the list of files that match the name (pattern). index 4. Program opens file. dictionary
8cd179a371401ff67828608ee2f7228d1333d4ca
[ "Markdown", "Python" ]
2
Python
tpodgorski91/FileSearcher
746f9df1cc7c4034ccef4a5219b976d4243d3499
19d7fe1f6e211e800e70a538a0a9db17f58cf787
refs/heads/master
<repo_name>WanchalermDevs/AdmissionSite2018<file_sep>/src/app/authentications/sign-in/sign-in.component.ts import { Component, OnInit } from '@angular/core'; import { FormControl, Validators, FormBuilder, FormGroup } from '@angular/forms'; import { MatInputModule } from '@angular/material'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service'; import { Http, Response, Headers, RequestOptions, HttpModule } from '@angular/http'; @Component({ selector: 'app-sign-in', templateUrl: './sign-in.component.html', styleUrls: ['./sign-in.component.css'] }) export class SignInComponent implements OnInit { loginForm: FormGroup; loginMessage: String; loginSuccessMessage: String; constructor(private user: UserService, private _router: Router, private formBuilder: FormBuilder) { this.loginForm = this.formBuilder.group({ 'username': [null, Validators.required], 'password': [null, Validators.required] }); } formLoginSubmit(post) { this.user.authenticate(post.username, post.password).then(response => { // console.log(response); if (response['operation'] == "success") { /* * เมื่อการลงชื่อเข้าใช้สำเร็จแล้วให้กำหนด session ของผู้ใช้งานไว้ */ this.loginMessage = ""; this.loginSuccessMessage = "ลงชื่อเข้าใช้สำเร็จ กรุณารอระบบประมวลผล"; window.sessionStorage.setItem("role", response['role']); window.sessionStorage.setItem("username", response['username']); window.sessionStorage.setItem("token", response['token']); window.sessionStorage.setItem("prename", response['prename']); window.sessionStorage.setItem("firstname", response['firstname']); window.sessionStorage.setItem("lastname", response['lastname']); window.sessionStorage.setItem("user_account_id", response['user_account_id']); this._router.navigateByUrl("/student/dashboard"); } else { window.sessionStorage.setItem("role", ""); window.sessionStorage.setItem("username", ""); window.sessionStorage.setItem("token", ""); window.sessionStorage.setItem("prename", ""); window.sessionStorage.setItem("firstname", ""); window.sessionStorage.setItem("lastname", ""); window.sessionStorage.setItem("user_account_id", ""); this.loginMessage = "ชื่อผู้ใช้ หรือรหัสผ่านไม่ถูกต้องกรุณาลองอีกครั้ง"; this.loginSuccessMessage = ""; } }); } ngOnInit() { } } <file_sep>/src/app/students/dashboard-student/dashboard-student.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { RESTService } from '../../service/rest.service'; @Component({ selector: 'app-dashboard-student', templateUrl: './dashboard-student.component.html', styleUrls: ['./dashboard-student.component.css'] }) export class DashboardStudentComponent implements OnInit { isThereTesterCode: boolean; status = [ { prename_th: '--ยังไม่ได้รับเอกสาร--', firstname_th: '--ยังไม่ได้รับเอกสาร--', lastname_th: '--ยังไม่ได้รับเอกสาร--', plan: '--ยังไม่ได้รับเอกสาร--', checking: '--ยังไม่ได้รับเอกสาร--', level: '--ยังไม่ได้รับเอกสาร--' } ]; token: any; received = false; constructor(private _router: Router, private _rest: RESTService) { console.log("constructor()"); this.isThereTesterCode = false; this.token = window.sessionStorage.getItem("token"); const preParamIsThereTesterCode = { topic: "isThereTesterCode", username: window.sessionStorage.getItem("username"), token: window.sessionStorage.getItem("token"), role: window.sessionStorage.getItem("role"), user_account_id: window.sessionStorage.getItem("user_account_id") }; console.log(preParamIsThereTesterCode); this._rest.RESTPost(preParamIsThereTesterCode).then(response => { console.log("is there tester code"); console.log(response); if(response['tester'] == 0){ this.isThereTesterCode = false; }else{ this.isThereTesterCode = true; } }); // getStatusAdmission const preParam = { topic: "getStatusAdmission", username: window.sessionStorage.getItem("username"), token: window.sessionStorage.getItem("token"), role: window.sessionStorage.getItem("role") }; this._rest.getStatusAdmission(preParam).then(response => { this.status['prename_th'] = response['prename_th']; this.status['firstname_th'] = response['firstname_th']; this.status['lastname_th'] = response['lastname_th']; this.status['level'] = response['level']; if (response['operation'] == "success") { this.received = true; this.status['checking'] = "ตรวจสอบแล้วผ่านคุณสมบัติ ให้นักเรียนเข้าสู่ระบบอีกครั้งในวันที่ 11 มกราคม 2561 เพื่อพิมพ์บัตรประจำตัวผู้เข้าสอบ"; if (response['level'] == 1) { if (response['plan_code'] == 1) { this.status['plan'] = "เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาไทย)"; } else if (response['plan_code'] == 2) { this.status['plan'] = "เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาอังกฤษ)"; } else if (response['plan_code'] == 3) { this.status['plan'] = "เลือกทั้งสองแผน"; } } else if (response['level'] == 4) { if (response['plan_code'] == 1) { this.status['plan'] = "เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์"; } else if (response['plan_code'] == 2) { this.status['plan'] = "เลือกแผนภาษาอังกฤษ - คณิตศาสตร์"; } } } else { this.status['prename_th'] = "--ยังไม่ได้รับเอกสาร--"; this.status['firstname_th'] = ""; this.status['lastname_th'] = ""; this.status['level'] = "--ยังไม่ได้รับเอกสาร--"; this.status['plan'] = "--ยังไม่ได้รับเอกสาร--"; this.status['checking'] = "--ยังไม่ได้รับเอกสาร--"; } }); } createATesterCode(){ /* * send a request to back-end for create a new tester code. */ const preParame = { topic: "createNewTesterCodeMyself", username: window.sessionStorage.getItem("username"), token: window.sessionStorage.getItem("token"), role: window.sessionStorage.getItem("role"), user_account_id: window.sessionStorage.getItem("user_account_id") }; this._rest.RESTPost(preParame).then(response => { console.log(response); if(response['operation'] === 'success'){ this.isThereTesterCode = true; }else{ this.isThereTesterCode = false; } }); } gotoRecived() { alert("ระบบไม่อนุญาตให้แก้ไขข้อมูลแล้ว"); } ngOnInit() { console.log("ngOnInit()"); this.status['prename_th'] = "--ยังไม่ได้รับเอกสาร--"; this.status['firstname_th'] = ""; this.status['lastname_th'] = ""; this.status['level'] = "--ยังไม่ได้รับเอกสาร--"; this.status['plan'] = "--ยังไม่ได้รับเอกสาร--"; this.status['checking'] = "--ยังไม่ได้รับเอกสาร--"; } gotoInfo() { this._router.navigateByUrl("student/info"); } printApplication() { alert("ระบบไม่อนุญาตให้ดำเนินการพิมพ์ใบใบแล้ว"); //window.location.href = "http://www.satit.nu.ac.th/2016/barcode/application.php?token=" + window.sessionStorage.getItem("token"); // window.open("http://www.satit.nu.ac.th/2016/barcode/application.php?token=" + window.sessionStorage.getItem("token"), '_blank'); } printBillPayMent() { alert("ระบบไม่อนุญาตให้ดำเนินการพิมพ์ใบแจ้งชำระเงินแล้ว"); // window.location.href = "http://www.satit.nu.ac.th/2016/barcode/billpayment.php?token=" + window.sessionStorage.getItem("token"); // window.open("http://www.satit.nu.ac.th/2016/barcode/billpayment.php?token=" + window.sessionStorage.getItem("token"), '_blank'); } printCard() { alert("1. เมื่อนักเรียนพิมพ์บัตรประจำตัวผู้เข้าสอบแล้ว ให้ตรวจสอบข้อมูล ห้องสอบ รหัสประจำตัวสอบ แล้วลงลายมือชื่อที่บัตรให้เรียบร้อย \n2. นักเรียนต้องนำบัตรนี้มาแสดงกับกรรมการคุมสอบในวันสอบ คู่กับบัตรประจำตัวประชาชน หรือบัตรนักเรียน\n 3. นักเรียนต้องปฏิบัติตามระเบียบการสอบ และข้อแนะนำอย่างเคร่งครัด"); window.open("http://www.satit.nu.ac.th/2016/admission/pdf/admission-card.php?user_account_id=" + window.sessionStorage.getItem("user_account_id"), '_blank'); } } <file_sep>/src/app/service/user.service.ts import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import { Router } from '@angular/router'; @Injectable() export class UserService { /* * ตัว แปร _host ใช้กำหนด host ที่จะใช้สื่อสาร back-end */ private _host; constructor(private _http: Http, _router: Router) { this._host = 'http://www.satit.nu.ac.th/AdmissionEngine/gateway.php'; } authenticate(username, password) { const preParam = { topic: "login", username: username, password: <PASSWORD> }; return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(preParam), { headers: headers }).map((res: Response) => { var json = res.json(); json.headers = res.headers; return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } private packParameter(param) { var _parameter = Object.keys(param).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(param[key]); }).join('&'); return _parameter; } } <file_sep>/src/app/students/infomations/infomations.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { InfomationsComponent } from './infomations.component'; describe('InfomationsComponent', () => { let component: InfomationsComponent; let fixture: ComponentFixture<InfomationsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ InfomationsComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(InfomationsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { InfomationsComponent } from './students/infomations/infomations.component'; import { DashboardStudentComponent } from './students/dashboard-student/dashboard-student.component'; import { UploadImageComponent } from './students/upload-image/upload-image.component'; import { IsOnlineGuard } from './guard/is-online.guard'; import { SignInComponent } from './authentications/sign-in/sign-in.component'; import { DialogOverviewExampleDialog } from './home/home.component'; import { HomeComponent } from './home/home.component'; const studentRoute: Routes = [ { path: 'info', component: InfomationsComponent, }, { path: 'dashboard', component: DashboardStudentComponent }, { path: 'image', component: UploadImageComponent } ]; const routes: Routes = [ { path: '', redirectTo: '/signin', pathMatch: 'full' }, { path: 'student', children: studentRoute, canActivate: [IsOnlineGuard], }, { path: 'home', component: HomeComponent }, { path: 'signin', component: SignInComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/service/rest.service.ts import { Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; @Injectable() export class RESTService { /* * ตัว แปร _host ใช้กำหนด host ที่จะใช้สื่อสาร back-end */ private _host; constructor(private _http: Http) { this._host = 'http://www.satit.nu.ac.th/AdmissionEngine/gateway.php'; } RESTPost(param) { return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(param), { headers: headers }).map((res: Response) => { console.log(res); try { var json = res.json(); json.headers = res.headers; } catch (err) { const json = { operation: "fail" }; } return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } private packParameter(param) { var _parameter = Object.keys(param).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(param[key]); }).join('&'); return _parameter; } getStatusAdmission(param) { return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(param), { headers: headers }).map((res: Response) => { // console.log(res); try { var json = res.json(); json.headers = res.headers; } catch (err) { const json = { operation: "fail" }; } return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } getAccountData(param) { return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(param), { headers: headers }).map((res: Response) => { // console.log(res); try { var json = res.json(); json.headers = res.headers; } catch (err) { const json = { operation: "fail" }; } return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } saveAccountData(param) { return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(param), { headers: headers }).map((res: Response) => { var json = res.json(); json.headers = res.headers; return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } createNewAccount(param) { return new Promise((resolve, reject) => { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); return this._http.post(this._host, this.packParameter(param), { headers: headers }).map((res: Response) => { var json = res.json(); json.headers = res.headers; return json; }).subscribe((data) => { resolve(data); }, error => { return reject(error); }); }); } } <file_sep>/src/app/top-bars/menu/menu.component.ts import { Component, OnInit } from '@angular/core'; import { IsOnlineGuard } from '../../guard/is-online.guard'; import { Router } from '@angular/router'; import { UserService } from '../../service/user.service'; import { RESTService } from '../../service/rest.service'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) export class MenuComponent implements OnInit { fullName: string; constructor(private isOnline: IsOnlineGuard, private _router: Router, private user: UserService, private rest: RESTService) { const preParam = { topic: "getAccountData", username: window.sessionStorage.getItem("username"), token: window.sessionStorage.getItem("token"), role: window.sessionStorage.getItem("role") }; // console.log(preParam); this.rest.getAccountData(preParam).then(response => { this.fullName = response['prename_th'] + response['firstname_th'] + " " + response['lastname_th']; }); } ngOnInit() { if(window.sessionStorage.getItem("prename") != null){ this.fullName = window.sessionStorage.getItem("prename") + window.sessionStorage.getItem("firstname") + " " + window.sessionStorage.getItem("lastname"); }else{ this.logout(); } } logout() { window.sessionStorage.setItem("role", ""); window.sessionStorage.setItem("username", ""); window.sessionStorage.setItem("token", ""); window.sessionStorage.setItem("prename", ""); window.sessionStorage.setItem("firstname", ""); window.sessionStorage.setItem("lastname", ""); window.sessionStorage.setItem("user_account_id", ""); this._router.navigateByUrl("/home"); } } <file_sep>/src/app/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { Inject } from '@angular/core'; import { NgModel } from '@angular/forms'; import { RESTService } from '../service/rest.service'; import { IsOnlineGuard } from '../guard/is-online.guard'; import { Router } from '@angular/router'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(public dialog: MatDialog, private rest: RESTService, private isOnline: IsOnlineGuard, private _router: Router) { } animal: string; name: string; enableDebugMode = true; personal_id: string; prename: string; firstname: string; lastname: string; birthday: string; birhtmonth: string; birthyear: string; plan_code: string; plan = []; couseM1 = [ { value: '1', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาไทย)' }, { value: '2', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาอังกฤษ)' }, { value: '3', viewValue: 'เลือกทั้งสองแผน' } ]; couseM4 = [ { value: '1', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์' }, { value: '2', viewValue: 'เลือกแผนภาษาอังกฤษ - คณิตศาสตร์' } ]; navigateDashboard() { this._router.navigateByUrl("/student/dashboard"); } openDialog(level): void { if (level == 1) { this.plan = this.couseM1; } else { this.plan = this.couseM4; } let dialogRef = this.dialog.open(DialogOverviewExampleDialog, { width: 'max-content', data: { level: level, personal_id: this.personal_id, prename: this.prename, firstname: this.firstname, lastname: this.lastname, birthday: this.birthday, birhtmonth: this.birhtmonth, birthyear: this.birthyear, plan_code: this.plan_code, plan: this.plan, topic: "createNewAccount" } }); dialogRef.afterClosed().subscribe(result => { if (result !== undefined) { if (this.enableDebugMode) { console.log("มีการบันทึกข้อมูล"); if (result.personal_id !== undefined) console.log("มีการกรอกเลขประจำตัวประชาชนจริง"); if (result.prename !== undefined) console.log("มีการเลือกคำหน้านามแล้ว จริง"); if (result.firstname !== undefined) console.log("มีการกรอกชื่อจริงมาแล้ว จริง"); if (result.lastname !== undefined) console.log("มีการกรอกนามสกุลมาแล้ว จริง"); if (result.birthday !== undefined) console.log("มีการเลือกวันที่เกิดมาแล้ว จริง"); if (result.birhtmonth !== undefined) console.log("มีการเลือกเดือนเกิดมาแล้ว จริง"); if (result.birthyear !== undefined) console.log("มีการเลือกปีเกิดมาแล้วจริง"); } if ( (result.personal_id !== undefined) && (result.prename !== undefined) && (result.firstname !== undefined) && (result.lastname !== undefined) && (result.birthday !== undefined) && (result.birhtmonth !== undefined) && (result.plan_code !== undefined) && (result.birthyear !== undefined)) { this.rest.createNewAccount(result).then(response => { console.log(response); if (response['operation'] == "success") { /* * เมื่อการลงชื่อเข้าใช้สำเร็จแล้วให้กำหนด session ของผู้ใช้งานไว้ */ window.sessionStorage.setItem("role", response['role']); window.sessionStorage.setItem("username", response['username']); window.sessionStorage.setItem("token", response['token']); window.sessionStorage.setItem("prename", response['prename']); window.sessionStorage.setItem("firstname", response['firstname']); window.sessionStorage.setItem("lastname", response['lastname']); this._router.navigateByUrl("/student/info"); // window.location.href = "./student/info"; } else { alert("มีบางอย่างพิดลาด!\n " + response['error_message']); window.sessionStorage.setItem("role", ""); window.sessionStorage.setItem("username", ""); window.sessionStorage.setItem("token", ""); window.sessionStorage.setItem("prename", ""); window.sessionStorage.setItem("firstname", ""); window.sessionStorage.setItem("lastname", ""); } }); } else { console.log(result); alert("คุณยังกรอกข้อมูลไม่ครบ"); } } else { /* * ไม่ได้กรอกข้อมูล */ console.log("ไม่ได้กรอกข้อมูล"); } }); } ngOnInit() { } } @Component({ selector: 'dialog-overview-example-dialog', templateUrl: 'dialog-overview-example-dialog.html', }) export class DialogOverviewExampleDialog { constructor( public dialogRef: MatDialogRef<DialogOverviewExampleDialog>, @Inject(MAT_DIALOG_DATA) public data: any) { } preNmaes = [ { value: 'เด็กชาย', viewValue: 'เด็กชาย' }, { value: 'เด็กหญิง', viewValue: 'เด็กหญิง' }, { value: 'นาย', viewValue: 'นาย' }, { value: 'นางสาว', viewValue: 'นางสาว' } ]; numOfDate = [ { value: '01', viewValue: '01' }, { value: '02', viewValue: '02' }, { value: '03', viewValue: '03' }, { value: '04', viewValue: '04' }, { value: '05', viewValue: '05' }, { value: '06', viewValue: '06' }, { value: '07', viewValue: '07' }, { value: '08', viewValue: '08' }, { value: '09', viewValue: '09' }, { value: '10', viewValue: '10' }, { value: '11', viewValue: '11' }, { value: '12', viewValue: '12' }, { value: '13', viewValue: '13' }, { value: '14', viewValue: '14' }, { value: '15', viewValue: '15' }, { value: '16', viewValue: '16' }, { value: '17', viewValue: '17' }, { value: '18', viewValue: '18' }, { value: '19', viewValue: '19' }, { value: '20', viewValue: '20' }, { value: '21', viewValue: '21' }, { value: '22', viewValue: '22' }, { value: '23', viewValue: '23' }, { value: '24', viewValue: '24' }, { value: '25', viewValue: '25' }, { value: '26', viewValue: '26' }, { value: '27', viewValue: '27' }, { value: '28', viewValue: '28' }, { value: '29', viewValue: '29' }, { value: '30', viewValue: '30' }, { value: '31', viewValue: '31' } ]; numOfMounts = [ { value: '01', viewValue: 'มกราคม' }, { value: '02', viewValue: 'กุมภาพันธ์' }, { value: '03', viewValue: 'มีนาคม' }, { value: '04', viewValue: 'เมษายน' }, { value: '05', viewValue: 'พฤษภาคม' }, { value: '06', viewValue: 'มิถุนายน' }, { value: '07', viewValue: 'กรกฎาคม' }, { value: '08', viewValue: 'สิงหาคม' }, { value: '09', viewValue: 'กันยายน' }, { value: '10', viewValue: 'ตุลาคม' }, { value: '11', viewValue: 'พฤศจิกายน' }, { value: '12', viewValue: 'ธันวาคม' } ]; numOfYears = [ { value: '2540', viewValue: '2540' }, { value: '2541', viewValue: '2541' }, { value: '2542', viewValue: '2542' }, { value: '2543', viewValue: '2543' }, { value: '2544', viewValue: '2544' }, { value: '2545', viewValue: '2545' }, { value: '2546', viewValue: '2546' }, { value: '2547', viewValue: '2547' }, { value: '2548', viewValue: '2548' }, { value: '2549', viewValue: '2549' }, { value: '2550', viewValue: '2550' } ]; onNoClick(): void { this.dialogRef.close(); } }<file_sep>/src/app/students/infomations/infomations.component.ts import { Component, Directive, EventEmitter, ElementRef, Renderer, HostListener, Output, Input, OnInit, OnDestroy, ChangeDetectionStrategy } from '@angular/core'; import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; import { NgModel } from '@angular/forms'; import { RESTService } from '../../service/rest.service'; import { Router } from '@angular/router'; // import { FileFilter, hookType, UploaderHook } from '@uniprank/ng2-file-uploader'; // import { FileDropModule, UploadFile, UploadEvent } from 'ngx-file-drop/lib/ngx-drop'; import { BehaviorSubject } from 'rxjs/Rx'; // import { FileManager, FileManagerOptions, FileUploader, Utils, Transfer, TransferOptions } from '@uniprank/ng2-file-uploader'; import { MenuComponent } from '../../top-bars/menu/menu.component'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/startWith'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-infomations', templateUrl: './infomations.component.html', changeDetection: ChangeDetectionStrategy.OnPush, styleUrls: ['./infomations.component.scss'], }) export class InfomationsComponent implements OnInit { // public uploader: Transfer; public hasFiles: boolean; myControl: FormControl = new FormControl(); filteredOptions: Observable<string[]>; filteredOptions4: Observable<string[]>; filter(val: string): string[] { return this.options.filter(option => option.toLowerCase().indexOf(val.toLowerCase()) === 0); } filter4(val: string): string[] { return this.prvOptions.filter(option => option.toLowerCase().indexOf(val.toLowerCase()) === 0); } isLinear = true; firstFormGroup: FormGroup; secondFormGroup: FormGroup; selectCourse: FormGroup; studentForm: FormGroup; studentImagePath: String; isShowCouseM1: boolean; isShowCorseM4: boolean; isUploadImage: boolean; studentLevel: number; studentYear: number; rand: number; checked = false; indeterminate = false; align = 'start'; disabled = false; student = {}; couses = {}; uploadStudentImage() { // window.location.href = "http://www.satit.nu.ac.th/UploadStudentImage/index.php?token=" + window.sessionStorage.getItem("token"); window.open("http://www.satit.nu.ac.th/UploadStudentImage/index.php?token=" + window.sessionStorage.getItem("token"), '_blank'); } options = []; prvOptions = []; constructor(private _formBuilder: FormBuilder, private rest: RESTService, private _router: Router, private element: ElementRef, private renderer: Renderer) { // this._files = []; this.rand = Math.random(); this.studentForm = this._formBuilder.group({ personal_id: ['', Validators.required], birthday: ['', Validators.required], birthmonth: ['', Validators.required], birthyear: ['', Validators.required], prename_th: ['', Validators.required], firstname_th: ['', Validators.required], lastname_th: ['', Validators.required], firstname_en: ['', Validators.required], lastname_en: ['', Validators.required], plan_code: ['', Validators.required], plan_code4: ['', Validators.required], ethnicity: ['', Validators.required], nationality: ['', Validators.required], religion: ['', Validators.required], phone_number: ['', Validators.required], email: ['', Validators.required], address1_a: ['', Validators.required], address1_b: ['', Validators.required], address1_c: ['', Validators.required], address1_d: ['', Validators.required], address1_e: ['', Validators.required], address1_f: ['', Validators.required], address1_g: ['', Validators.required], address1_h: ['', Validators.required], address1_i: ['', Validators.required], address2_a: ['', Validators.required], address2_b: ['', Validators.required], address2_c: ['', Validators.required], address2_d: ['', Validators.required], address2_e: ['', Validators.required], address2_f: ['', Validators.required], address2_g: ['', Validators.required], address2_h: ['', Validators.required], address2_i: ['', Validators.required], father_prename: ['', Validators.required], father_firstname: ['', Validators.required], father_lastname: ['', Validators.required], father_career: ['', Validators.required], father_income: ['', Validators.required], father_age: ['', Validators.required], father_phone: ['', Validators.required], mother_prename: ['', Validators.required], mother_firstname: ['', Validators.required], mother_lastname: ['', Validators.required], morther_career: ['', Validators.required], mother_income: ['', Validators.required], mother_age: ['', Validators.required], mother_phone: ['', Validators.required], parent_prename: ['', Validators.required], parent_firstname: ['', Validators.required], parent_lastname: ['', Validators.required], parent_career: ['', Validators.required], parent_income: ['', Validators.required], parent_age: ['', Validators.required], parent_phone: ['', Validators.required], school_b: ['', Validators.required], school_a: ['', Validators.required], school_name: ['', Validators.required], education_status: ['', Validators.required] }); const preParam = { topic: "getAccountData", username: window.sessionStorage.getItem("username"), token: window.sessionStorage.getItem("token"), role: window.sessionStorage.getItem("role") }; // console.log(preParam); this.rest.getAccountData(preParam).then(response => { // console.log(response); this.student = response; this.studentLevel = this.student['level']; this.studentYear = this.student['year']; if (this.student['level'] == 1) { this.couseM4 = null; this.studyStatusM4 = null; } else { this.couseM1 = null; this.studyStatusM1 = null; } if (this.student['isupload_image'] == 1) { this.isUploadImage = true; } else { this.isUploadImage = false; } if (this.student['school_b'] !== "") { // console.log("มีจังหวัด") console.log(this.student['school_b']); this.prvs.forEach(element => { if (element.viewValue == this.student['school_b']) { console.log("มีอำเภอ"); this.listApms = []; const _prvCode = element.prvCode; this.apms.forEach(elements => { if (elements.prvCode == _prvCode) { this.listApms.push({ value: elements.value, viewValue: elements.viewValue, prvCode: elements.prvCode }); } }); } }); } this.studentImagePath = "http://www.satit.nu.ac.th/AdmissionEngine/files/" + this.student['year'] + "/images/" + this.student['level'] + "/" + this.student['image_name']; }); // Bind FileUploader class to variable // this.uploader = new FileUploader({ // url: 'http://satit.nu.ac.th/AdmissionEngine/uploadStudentImage.php?token=' + window.sessionStorage.getItem("token"), // removeBySuccess: false, // autoUpload: true, // uniqueFiles: true, // method: "post", // // filter implementation possible // }); var delayInMilliseconds = 500; //1 second setTimeout(function () { // alert("โปรดตรวจสอบความถูกต้องของข้อมูลก่อนบันทึกข้อมูล"); window.document.getElementById("myPlan").focus(); }, delayInMilliseconds); } saveData(data) { if (this.student['plan_code'] !== undefined) { this.student['topic'] = "saveAccountData"; this.student['role'] = window.sessionStorage.getItem("role"); this.student['token'] = window.sessionStorage.getItem("token"); this.student['headers'] = null; this.student['username'] = window.sessionStorage.getItem("username"); this.rest.getAccountData(this.student).then(response => { if (response['operation'] === "success") { this._router.navigateByUrl("student/dashboard"); } else { alert("มีบางอย่างผิดพลาด ติดต่อนักพัฒนา"); } }); } else { alert("นักเรียนยังไม่ได้เลือกแผนการเรียน กรุณาเลือกแผนการเรียน"); } } copyAddress() { this.student['address2_a'] = this.student['address1_a']; this.student['address2_b'] = this.student['address1_b']; this.student['address2_c'] = this.student['address1_c']; this.student['address2_d'] = this.student['address1_d']; this.student['address2_e'] = this.student['address1_e']; this.student['address2_f'] = this.student['address1_f']; this.student['address2_g'] = this.student['address1_g']; this.student['address2_h'] = this.student['address1_h']; this.student['address2_i'] = this.student['address1_i']; } ngOnInit() { const preParam2 = { topic: 'getFindSchoolName', token: window.sessionStorage.getItem("token"), username: window.sessionStorage.getItem("username"), role: window.sessionStorage.getItem("role"), school_name: this.student['school_name'] }; this.rest.RESTPost(preParam2).then(response => { for (var k in response) { if ((response[k]['school_name'] !== "") && (response[k]['school_name'] !== undefined)) { this.options.push(response[k]['school_name']); } } }); for(var d in this.prvs){ this.prvOptions.push(this.prvs[d]['viewValue']); } this.filteredOptions = this.myControl.valueChanges .startWith(null) .map(val => val ? this.filter(val) : this.options.slice()); this.filteredOptions4 = this.myControl.valueChanges .startWith(null) .map(val => val ? this.filter4(val) : this.prvOptions.slice()); if (typeof this.maxFiles !== 'undefined') { this._limit = this.maxFiles; } // this.uploader.queue$.subscribe((data: FileManager[]) => { // this.checkClass(); // }); // this._files$.subscribe((data: FileManager[]) => { // this.imageLoaded = (data.length > 0); // }); this.firstFormGroup = this._formBuilder.group({ firstCtrl: ['', Validators.required] }); this.secondFormGroup = this._formBuilder.group({ secondCtrl: ['', Validators.required] }); this.selectCourse = this._formBuilder.group({ a: ['', Validators.required], b: ['', Validators.required] }); var div_load = document.getElementsByClassName("div-load")[0]; div_load.innerHTML = "Hello"; } prvs = [ { value: 'กรุงเทพมหานคร', viewValue: 'กรุงเทพมหานคร', prvCode: '1' }, { value: 'สมุทรปราการ', viewValue: 'สมุทรปราการ', prvCode: '2' }, { value: 'นนทบุรี', viewValue: 'นนทบุรี', prvCode: '3' }, { value: 'ปทุมธานี', viewValue: 'ปทุมธานี', prvCode: '4' }, { value: 'พระนครศรีอยุธยา', viewValue: 'พระนครศรีอยุธยา', prvCode: '5' }, { value: 'อ่างทอง', viewValue: 'อ่างทอง', prvCode: '6' }, { value: 'ลพบุรี', viewValue: 'ลพบุรี', prvCode: '7' }, { value: 'สิงห์บุรี', viewValue: 'สิงห์บุรี', prvCode: '8' }, { value: 'ชัยนาท', viewValue: 'ชัยนาท', prvCode: '9' }, { value: 'สระบุรี', viewValue: 'สระบุรี', prvCode: '10' }, { value: 'ชลบุรี', viewValue: 'ชลบุรี', prvCode: '11' }, { value: 'ระยอง', viewValue: 'ระยอง', prvCode: '12' }, { value: 'จันทบุรี', viewValue: 'จันทบุรี', prvCode: '13' }, { value: 'ตราด', viewValue: 'ตราด', prvCode: '14' }, { value: 'ฉะเชิงเทรา', viewValue: 'ฉะเชิงเทรา', prvCode: '15' }, { value: 'ปราจีนบุรี', viewValue: 'ปราจีนบุรี', prvCode: '16' }, { value: 'นครนายก', viewValue: 'นครนายก', prvCode: '17' }, { value: 'สระแก้ว', viewValue: 'สระแก้ว', prvCode: '18' }, { value: 'นครราชสีมา', viewValue: 'นครราชสีมา', prvCode: '19' }, { value: 'บุรีรัมย์', viewValue: 'บุรีรัมย์', prvCode: '20' }, { value: 'สุรินทร์', viewValue: 'สุรินทร์', prvCode: '21' }, { value: 'ศรีสะเกษ', viewValue: 'ศรีสะเกษ', prvCode: '22' }, { value: 'อุบลราชธานี', viewValue: 'อุบลราชธานี', prvCode: '23' }, { value: 'ยโสธร', viewValue: 'ยโสธร', prvCode: '24' }, { value: 'ชัยภูมิ', viewValue: 'ชัยภูมิ', prvCode: '25' }, { value: 'อำนาจเจริญ', viewValue: 'อำนาจเจริญ', prvCode: '26' }, { value: 'หนองบัวลำภู', viewValue: 'หนองบัวลำภู', prvCode: '27' }, { value: 'ขอนแก่น', viewValue: 'ขอนแก่น', prvCode: '28' }, { value: 'อุดรธานี', viewValue: 'อุดรธานี', prvCode: '29' }, { value: 'เลย', viewValue: 'เลย', prvCode: '30' }, { value: 'หนองคาย', viewValue: 'หนองคาย', prvCode: '31' }, { value: 'มหาสารคาม', viewValue: 'มหาสารคาม', prvCode: '32' }, { value: 'ร้อยเอ็ด', viewValue: 'ร้อยเอ็ด', prvCode: '33' }, { value: 'กาฬสินธุ์', viewValue: 'กาฬสินธุ์', prvCode: '34' }, { value: 'สกลนคร', viewValue: 'สกลนคร', prvCode: '35' }, { value: 'นครพนม', viewValue: 'นครพนม', prvCode: '36' }, { value: 'มุกดาหาร', viewValue: 'มุกดาหาร', prvCode: '37' }, { value: 'เชียงใหม่', viewValue: 'เชียงใหม่', prvCode: '38' }, { value: 'ลำพูน', viewValue: 'ลำพูน', prvCode: '39' }, { value: 'ลำปาง', viewValue: 'ลำปาง', prvCode: '40' }, { value: 'อุตรดิตถ์', viewValue: 'อุตรดิตถ์', prvCode: '41' }, { value: 'แพร่', viewValue: 'แพร่', prvCode: '42' }, { value: 'น่าน', viewValue: 'น่าน', prvCode: '43' }, { value: 'พะเยา', viewValue: 'พะเยา', prvCode: '44' }, { value: 'เชียงราย', viewValue: 'เชียงราย', prvCode: '45' }, { value: 'แม่ฮ่องสอน', viewValue: 'แม่ฮ่องสอน', prvCode: '46' }, { value: 'นครสวรรค์', viewValue: 'นครสวรรค์', prvCode: '47' }, { value: 'อุทัยธานี', viewValue: 'อุทัยธานี', prvCode: '48' }, { value: 'กำแพงเพชร', viewValue: 'กำแพงเพชร', prvCode: '49' }, { value: 'ตาก', viewValue: 'ตาก', prvCode: '50' }, { value: 'สุโขทัย', viewValue: 'สุโขทัย', prvCode: '51' }, { value: 'พิษณุโลก', viewValue: 'พิษณุโลก', prvCode: '52' }, { value: 'พิจิตร', viewValue: 'พิจิตร', prvCode: '53' }, { value: 'เพชรบูรณ์', viewValue: 'เพชรบูรณ์', prvCode: '54' }, { value: 'ราชบุรี', viewValue: 'ราชบุรี', prvCode: '55' }, { value: 'กาญจนบุรี', viewValue: 'กาญจนบุรี', prvCode: '56' }, { value: 'สุพรรณบุรี', viewValue: 'สุพรรณบุรี', prvCode: '57' }, { value: 'นครปฐม', viewValue: 'นครปฐม', prvCode: '58' }, { value: 'สมุทรสาคร', viewValue: 'สมุทรสาคร', prvCode: '59' }, { value: 'สมุทรสงคราม', viewValue: 'สมุทรสงคราม', prvCode: '60' }, { value: 'เพชรบุรี', viewValue: 'เพชรบุรี', prvCode: '61' }, { value: 'ประจวบคีรีขันธ์', viewValue: 'ประจวบคีรีขันธ์', prvCode: '62' }, { value: 'นครศรีธรรมราช', viewValue: 'นครศรีธรรมราช', prvCode: '63' }, { value: 'กระบี่', viewValue: 'กระบี่', prvCode: '64' }, { value: 'พังงา', viewValue: 'พังงา', prvCode: '65' }, { value: 'ภูเก็ต', viewValue: 'ภูเก็ต', prvCode: '66' }, { value: 'สุราษฎร์ธานี', viewValue: 'สุราษฎร์ธานี', prvCode: '67' }, { value: 'ระนอง', viewValue: 'ระนอง', prvCode: '68' }, { value: 'ชุมพร', viewValue: 'ชุมพร', prvCode: '69' }, { value: 'สงขลา', viewValue: 'สงขลา', prvCode: '70' }, { value: 'สตูล', viewValue: 'สตูล', prvCode: '71' }, { value: 'ตรัง', viewValue: 'ตรัง', prvCode: '72' }, { value: 'พัทลุง', viewValue: 'พัทลุง', prvCode: '73' }, { value: 'ปัตตานี', viewValue: 'ปัตตานี', prvCode: '74' }, { value: 'ยะลา', viewValue: 'ยะลา', prvCode: '75' }, { value: 'นราธิวาส', viewValue: 'นราธิวาส', prvCode: '76' }, { value: 'บึงกาฬ', viewValue: 'บึงกาฬ', prvCode: '77' } ]; setApms(_prvCode) { console.log(_prvCode); this.listApms = []; this.apms.forEach(element => { if (element.prvCode == _prvCode) { this.listApms.push({ value: element.value, viewValue: element.viewValue, prvCode: element.prvCode }); } }); } listApms = []; apms = [ { value: 'เขตพระนคร', viewValue: 'เขตพระนคร', prvCode: '1' }, { value: 'เขตดุสิต', viewValue: 'เขตดุสิต', prvCode: '1' }, { value: 'เขตหนองจอก', viewValue: 'เขตหนองจอก', prvCode: '1' }, { value: 'เขตบางรัก', viewValue: 'เขตบางรัก', prvCode: '1' }, { value: 'เขตบางเขน', viewValue: 'เขตบางเขน', prvCode: '1' }, { value: 'เขตบางกะปิ', viewValue: 'เขตบางกะปิ', prvCode: '1' }, { value: 'เขตปทุมวัน', viewValue: 'เขตปทุมวัน', prvCode: '1' }, { value: 'เขตป้อมปราบศัตรูพ่าย', viewValue: 'เขตป้อมปราบศัตรูพ่าย', prvCode: '1' }, { value: 'เขตพระโขนง', viewValue: 'เขตพระโขนง', prvCode: '1' }, { value: 'เขตมีนบุรี', viewValue: 'เขตมีนบุรี', prvCode: '1' }, { value: 'เขตลาดกระบัง', viewValue: 'เขตลาดกระบัง', prvCode: '1' }, { value: 'เขตยานนาวา', viewValue: 'เขตยานนาวา', prvCode: '1' }, { value: 'เขตสัมพันธวงศ์', viewValue: 'เขตสัมพันธวงศ์', prvCode: '1' }, { value: 'เขตพญาไท', viewValue: 'เขตพญาไท', prvCode: '1' }, { value: 'เขตธนบุรี', viewValue: 'เขตธนบุรี', prvCode: '1' }, { value: 'เขตบางกอกใหญ่', viewValue: 'เขตบางกอกใหญ่', prvCode: '1' }, { value: 'เขตห้วยขวาง', viewValue: 'เขตห้วยขวาง', prvCode: '1' }, { value: 'เขตคลองสาน', viewValue: 'เขตคลองสาน', prvCode: '1' }, { value: 'เขตตลิ่งชัน', viewValue: 'เขตตลิ่งชัน', prvCode: '1' }, { value: 'เขตบางกอกน้อย', viewValue: 'เขตบางกอกน้อย', prvCode: '1' }, { value: 'เขตบางขุนเทียน', viewValue: 'เขตบางขุนเทียน', prvCode: '1' }, { value: 'เขตภาษีเจริญ', viewValue: 'เขตภาษีเจริญ', prvCode: '1' }, { value: 'เขตหนองแขม', viewValue: 'เขตหนองแขม', prvCode: '1' }, { value: 'เขตราษฎร์บูรณะ', viewValue: 'เขตราษฎร์บูรณะ', prvCode: '1' }, { value: 'เขตบางพลัด', viewValue: 'เขตบางพลัด', prvCode: '1' }, { value: 'เขตดินแดง', viewValue: 'เขตดินแดง', prvCode: '1' }, { value: 'เขตบึงกุ่ม', viewValue: 'เขตบึงกุ่ม', prvCode: '1' }, { value: 'เขตสาทร', viewValue: 'เขตสาทร', prvCode: '1' }, { value: 'เขตบางซื่อ', viewValue: 'เขตบางซื่อ', prvCode: '1' }, { value: 'เขตจตุจักร', viewValue: 'เขตจตุจักร', prvCode: '1' }, { value: 'เขตบางคอแหลม', viewValue: 'เขตบางคอแหลม', prvCode: '1' }, { value: 'เขตประเวศ', viewValue: 'เขตประเวศ', prvCode: '1' }, { value: 'เขตคลองเตย', viewValue: 'เขตคลองเตย', prvCode: '1' }, { value: 'เขตสวนหลวง', viewValue: 'เขตสวนหลวง', prvCode: '1' }, { value: 'เขตจอมทอง', viewValue: 'เขตจอมทอง', prvCode: '1' }, { value: 'เขตดอนเมือง', viewValue: 'เขตดอนเมือง', prvCode: '1' }, { value: 'เขตราชเทวี', viewValue: 'เขตราชเทวี', prvCode: '1' }, { value: 'เขตลาดพร้าว', viewValue: 'เขตลาดพร้าว', prvCode: '1' }, { value: 'เขตวัฒนา', viewValue: 'เขตวัฒนา', prvCode: '1' }, { value: 'เขตบางแค', viewValue: 'เขตบางแค', prvCode: '1' }, { value: 'เขตหลักสี่', viewValue: 'เขตหลักสี่', prvCode: '1' }, { value: 'เขตสายไหม', viewValue: 'เขตสายไหม', prvCode: '1' }, { value: 'เขตคันนายาว', viewValue: 'เขตคันนายาว', prvCode: '1' }, { value: 'เขตสะพานสูง', viewValue: 'เขตสะพานสูง', prvCode: '1' }, { value: 'เขตวังทองหลาง', viewValue: 'เขตวังทองหลาง', prvCode: '1' }, { value: 'เขตคลองสามวา', viewValue: 'เขตคลองสามวา', prvCode: '1' }, { value: 'เขตบางนา', viewValue: 'เขตบางนา', prvCode: '1' }, { value: 'เขตทวีวัฒนา', viewValue: 'เขตทวีวัฒนา', prvCode: '1' }, { value: 'เขตทุ่งครุ', viewValue: 'เขตทุ่งครุ', prvCode: '1' }, { value: 'เขตบางบอน', viewValue: 'เขตบางบอน', prvCode: '1' }, { value: '*บ้านทะวาย', viewValue: '*บ้านทะวาย', prvCode: '1' }, { value: 'เมืองสมุทรปราการ', viewValue: 'เมืองสมุทรปราการ', prvCode: '2' }, { value: 'บางบ่อ', viewValue: 'บางบ่อ', prvCode: '2' }, { value: 'บางพลี', viewValue: 'บางพลี', prvCode: '2' }, { value: 'พระประแดง', viewValue: 'พระประแดง', prvCode: '2' }, { value: 'พระสมุทรเจดีย์', viewValue: 'พระสมุทรเจดีย์', prvCode: '2' }, { value: 'บางเสาธง', viewValue: 'บางเสาธง', prvCode: '2' }, { value: 'เมืองนนทบุรี', viewValue: 'เมืองนนทบุรี', prvCode: '3' }, { value: 'บางกรวย', viewValue: 'บางกรวย', prvCode: '3' }, { value: 'บางใหญ่', viewValue: 'บางใหญ่', prvCode: '3' }, { value: 'บางบัวทอง', viewValue: 'บางบัวทอง', prvCode: '3' }, { value: 'ไทรน้อย', viewValue: 'ไทรน้อย', prvCode: '3' }, { value: 'ปากเกร็ด', viewValue: 'ปากเกร็ด', prvCode: '3' }, { value: 'เทศบาลนครนนทบุรี (สาขาแขวงท่าทราย)*', viewValue: 'เทศบาลนครนนทบุรี (สาขาแขวงท่าทราย)*', prvCode: '3' }, { value: 'เทศบาลเมืองปากเกร็ด*', viewValue: 'เทศบาลเมืองปากเกร็ด*', prvCode: '3' }, { value: 'เมืองปทุมธานี', viewValue: 'เมืองปทุมธานี', prvCode: '4' }, { value: 'คลองหลวง', viewValue: 'คลองหลวง', prvCode: '4' }, { value: 'ธัญบุรี', viewValue: 'ธัญบุรี', prvCode: '4' }, { value: 'หนองเสือ', viewValue: 'หนองเสือ', prvCode: '4' }, { value: 'ลาดหลุมแก้ว', viewValue: 'ลาดหลุมแก้ว', prvCode: '4' }, { value: 'ลำลูกกา', viewValue: 'ลำลูกกา', prvCode: '4' }, { value: 'สามโคก', viewValue: 'สามโคก', prvCode: '4' }, { value: 'ลำลูกกา (สาขาตำบลคูคต)*', viewValue: 'ลำลูกกา (สาขาตำบลคูคต)*', prvCode: '4' }, { value: 'พระนครศรีอยุธยา', viewValue: 'พระนครศรีอยุธยา', prvCode: '5' }, { value: 'ท่าเรือ', viewValue: 'ท่าเรือ', prvCode: '5' }, { value: 'นครหลวง', viewValue: 'นครหลวง', prvCode: '5' }, { value: 'บางไทร', viewValue: 'บางไทร', prvCode: '5' }, { value: 'บางบาล', viewValue: 'บางบาล', prvCode: '5' }, { value: 'บางปะอิน', viewValue: 'บางปะอิน', prvCode: '5' }, { value: 'บางปะหัน', viewValue: 'บางปะหัน', prvCode: '5' }, { value: 'ผักไห่', viewValue: 'ผักไห่', prvCode: '5' }, { value: 'ภาชี', viewValue: 'ภาชี', prvCode: '5' }, { value: 'ลาดบัวหลวง', viewValue: 'ลาดบัวหลวง', prvCode: '5' }, { value: 'วังน้อย', viewValue: 'วังน้อย', prvCode: '5' }, { value: 'เสนา', viewValue: 'เสนา', prvCode: '5' }, { value: 'บางซ้าย', viewValue: 'บางซ้าย', prvCode: '5' }, { value: 'อุทัย', viewValue: 'อุทัย', prvCode: '5' }, { value: 'มหาราช', viewValue: 'มหาราช', prvCode: '5' }, { value: 'บ้านแพรก', viewValue: 'บ้านแพรก', prvCode: '5' }, { value: 'เมืองอ่างทอง', viewValue: 'เมืองอ่างทอง', prvCode: '6' }, { value: 'ไชโย', viewValue: 'ไชโย', prvCode: '6' }, { value: 'ป่าโมก', viewValue: 'ป่าโมก', prvCode: '6' }, { value: 'โพธิ์ทอง', viewValue: 'โพธิ์ทอง', prvCode: '6' }, { value: 'แสวงหา', viewValue: 'แสวงหา', prvCode: '6' }, { value: 'วิเศษชัยชาญ', viewValue: 'วิเศษชัยชาญ', prvCode: '6' }, { value: 'สามโก้', viewValue: 'สามโก้', prvCode: '6' }, { value: 'เมืองลพบุรี', viewValue: 'เมืองลพบุรี', prvCode: '7' }, { value: 'พัฒนานิคม', viewValue: 'พัฒนานิคม', prvCode: '7' }, { value: 'โคกสำโรง', viewValue: 'โคกสำโรง', prvCode: '7' }, { value: 'ชัยบาดาล', viewValue: 'ชัยบาดาล', prvCode: '7' }, { value: 'ท่าวุ้ง', viewValue: 'ท่าวุ้ง', prvCode: '7' }, { value: 'บ้านหมี่', viewValue: 'บ้านหมี่', prvCode: '7' }, { value: 'ท่าหลวง', viewValue: 'ท่าหลวง', prvCode: '7' }, { value: 'สระโบสถ์', viewValue: 'สระโบสถ์', prvCode: '7' }, { value: 'โคกเจริญ', viewValue: 'โคกเจริญ', prvCode: '7' }, { value: 'ลำสนธิ', viewValue: 'ลำสนธิ', prvCode: '7' }, { value: 'หนองม่วง', viewValue: 'หนองม่วง', prvCode: '7' }, { value: '*อ.บ้านเช่า จ.ลพบุรี', viewValue: '*อ.บ้านเช่า จ.ลพบุรี', prvCode: '7' }, { value: 'เมืองสิงห์บุรี', viewValue: 'เมืองสิงห์บุรี', prvCode: '8' }, { value: 'บางระจัน', viewValue: 'บางระจัน', prvCode: '8' }, { value: 'ค่ายบางระจัน', viewValue: 'ค่ายบางระจัน', prvCode: '8' }, { value: 'พรหมบุรี', viewValue: 'พรหมบุรี', prvCode: '8' }, { value: 'ท่าช้าง', viewValue: 'ท่าช้าง', prvCode: '8' }, { value: 'อินทร์บุรี', viewValue: 'อินทร์บุรี', prvCode: '8' }, { value: 'เมืองชัยนาท', viewValue: 'เมืองชัยนาท', prvCode: '9' }, { value: 'มโนรมย์', viewValue: 'มโนรมย์', prvCode: '9' }, { value: 'วัดสิงห์', viewValue: 'วัดสิงห์', prvCode: '9' }, { value: 'สรรพยา', viewValue: 'สรรพยา', prvCode: '9' }, { value: 'สรรคบุรี', viewValue: 'สรรคบุรี', prvCode: '9' }, { value: 'หันคา', viewValue: 'หันคา', prvCode: '9' }, { value: 'หนองมะโมง', viewValue: 'หนองมะโมง', prvCode: '9' }, { value: 'เนินขาม', viewValue: 'เนินขาม', prvCode: '9' }, { value: 'เมืองสระบุรี', viewValue: 'เมืองสระบุรี', prvCode: '10' }, { value: 'แก่งคอย', viewValue: 'แก่งคอย', prvCode: '10' }, { value: 'หนองแค', viewValue: 'หนองแค', prvCode: '10' }, { value: 'วิหารแดง', viewValue: 'วิหารแดง', prvCode: '10' }, { value: 'หนองแซง', viewValue: 'หนองแซง', prvCode: '10' }, { value: 'บ้านหมอ', viewValue: 'บ้านหมอ', prvCode: '10' }, { value: 'ดอนพุด', viewValue: 'ดอนพุด', prvCode: '10' }, { value: 'หนองโดน', viewValue: 'หนองโดน', prvCode: '10' }, { value: 'พระพุทธบาท', viewValue: 'พระพุทธบาท', prvCode: '10' }, { value: 'เสาไห้', viewValue: 'เสาไห้', prvCode: '10' }, { value: 'มวกเหล็ก', viewValue: 'มวกเหล็ก', prvCode: '10' }, { value: 'วังม่วง', viewValue: 'วังม่วง', prvCode: '10' }, { value: 'เฉลิมพระเกียรติ', viewValue: 'เฉลิมพระเกียรติ', prvCode: '10' }, { value: 'เมืองชลบุรี', viewValue: 'เมืองชลบุรี', prvCode: '11' }, { value: 'บ้านบึง', viewValue: 'บ้านบึง', prvCode: '11' }, { value: 'หนองใหญ่', viewValue: 'หนองใหญ่', prvCode: '11' }, { value: 'บางละมุง', viewValue: 'บางละมุง', prvCode: '11' }, { value: 'พานทอง', viewValue: 'พานทอง', prvCode: '11' }, { value: 'พนัสนิคม', viewValue: 'พนัสนิคม', prvCode: '11' }, { value: 'ศรีราชา', viewValue: 'ศรีราชา', prvCode: '11' }, { value: 'เกาะสีชัง', viewValue: 'เกาะสีชัง', prvCode: '11' }, { value: 'สัตหีบ', viewValue: 'สัตหีบ', prvCode: '11' }, { value: 'บ่อทอง', viewValue: 'บ่อทอง', prvCode: '11' }, { value: 'เกาะจันทร์', viewValue: 'เกาะจันทร์', prvCode: '11' }, { value: 'สัตหีบ (สาขาตำบลบางเสร่)*', viewValue: 'สัตหีบ (สาขาตำบลบางเสร่)*', prvCode: '11' }, { value: 'ท้องถิ่นเทศบาลเมืองหนองปรือ*', viewValue: 'ท้องถิ่นเทศบาลเมืองหนองปรือ*', prvCode: '11' }, { value: 'เทศบาลตำบลแหลมฉบัง*', viewValue: 'เทศบาลตำบลแหลมฉบัง*', prvCode: '11' }, { value: 'เทศบาลเมืองชลบุรี*', viewValue: 'เทศบาลเมืองชลบุรี*', prvCode: '11' }, { value: 'เมืองระยอง', viewValue: 'เมืองระยอง', prvCode: '12' }, { value: 'บ้านฉาง', viewValue: 'บ้านฉาง', prvCode: '12' }, { value: 'แกลง', viewValue: 'แกลง', prvCode: '12' }, { value: 'วังจันทร์', viewValue: 'วังจันทร์', prvCode: '12' }, { value: 'บ้านค่าย', viewValue: 'บ้านค่าย', prvCode: '12' }, { value: 'ปลวกแดง', viewValue: 'ปลวกแดง', prvCode: '12' }, { value: 'เขาชะเมา', viewValue: 'เขาชะเมา', prvCode: '12' }, { value: 'นิคมพัฒนา', viewValue: 'นิคมพัฒนา', prvCode: '12' }, { value: 'สาขาตำบลมาบข่า*', viewValue: 'สาขาตำบลมาบข่า*', prvCode: '12' }, { value: 'เมืองจันทบุรี', viewValue: 'เมืองจันทบุรี', prvCode: '13' }, { value: 'ขลุง', viewValue: 'ขลุง', prvCode: '13' }, { value: 'ท่าใหม่', viewValue: 'ท่าใหม่', prvCode: '13' }, { value: 'โป่งน้ำร้อน', viewValue: 'โป่งน้ำร้อน', prvCode: '13' }, { value: 'มะขาม', viewValue: 'มะขาม', prvCode: '13' }, { value: 'แหลมสิงห์', viewValue: 'แหลมสิงห์', prvCode: '13' }, { value: 'สอยดาว', viewValue: 'สอยดาว', prvCode: '13' }, { value: 'แก่งหางแมว', viewValue: 'แก่งหางแมว', prvCode: '13' }, { value: 'นายายอาม', viewValue: 'นายายอาม', prvCode: '13' }, { value: 'เขาคิชฌกูฏ', viewValue: 'เขาคิชฌกูฏ', prvCode: '13' }, { value: '*กิ่ง อ.กำพุธ จ.จันทบุรี', viewValue: '*กิ่ง อ.กำพุธ จ.จันทบุรี', prvCode: '13' }, { value: 'เมืองตราด', viewValue: 'เมืองตราด', prvCode: '14' }, { value: 'คลองใหญ่', viewValue: 'คลองใหญ่', prvCode: '14' }, { value: 'เขาสมิง', viewValue: 'เขาสมิง', prvCode: '14' }, { value: 'บ่อไร่', viewValue: 'บ่อไร่', prvCode: '14' }, { value: 'แหลมงอบ', viewValue: 'แหลมงอบ', prvCode: '14' }, { value: 'เกาะกูด', viewValue: 'เกาะกูด', prvCode: '14' }, { value: 'เกาะช้าง', viewValue: 'เกาะช้าง', prvCode: '14' }, { value: 'เมืองฉะเชิงเทรา', viewValue: 'เมืองฉะเชิงเทรา', prvCode: '15' }, { value: 'บางคล้า', viewValue: 'บางคล้า', prvCode: '15' }, { value: 'บางน้ำเปรี้ยว', viewValue: 'บางน้ำเปรี้ยว', prvCode: '15' }, { value: 'บางปะกง', viewValue: 'บางปะกง', prvCode: '15' }, { value: 'บ้านโพธิ์', viewValue: 'บ้านโพธิ์', prvCode: '15' }, { value: 'พนมสารคาม', viewValue: 'พนมสารคาม', prvCode: '15' }, { value: 'ราชสาส์น', viewValue: 'ราชสาส์น', prvCode: '15' }, { value: 'สนามชัยเขต', viewValue: 'สนามชัยเขต', prvCode: '15' }, { value: 'แปลงยาว', viewValue: 'แปลงยาว', prvCode: '15' }, { value: 'ท่าตะเกียบ', viewValue: 'ท่าตะเกียบ', prvCode: '15' }, { value: 'คลองเขื่อน', viewValue: 'คลองเขื่อน', prvCode: '15' }, { value: 'เมืองปราจีนบุรี', viewValue: 'เมืองปราจีนบุรี', prvCode: '16' }, { value: 'กบินทร์บุรี', viewValue: 'กบินทร์บุรี', prvCode: '16' }, { value: 'นาดี', viewValue: 'นาดี', prvCode: '16' }, { value: '*สระแก้ว', viewValue: '*สระแก้ว', prvCode: '16' }, { value: '*วังน้ำเย็น', viewValue: '*วังน้ำเย็น', prvCode: '16' }, { value: 'บ้านสร้าง', viewValue: 'บ้านสร้าง', prvCode: '16' }, { value: 'ประจันตคาม', viewValue: 'ประจันตคาม', prvCode: '16' }, { value: 'ศรีมหาโพธิ', viewValue: 'ศรีมหาโพธิ', prvCode: '16' }, { value: 'ศรีมโหสถ', viewValue: 'ศรีมโหสถ', prvCode: '16' }, { value: '*อรัญประเทศ', viewValue: '*อรัญประเทศ', prvCode: '16' }, { value: '*ตาพระยา', viewValue: '*ตาพระยา', prvCode: '16' }, { value: '*วัฒนานคร', viewValue: '*วัฒนานคร', prvCode: '16' }, { value: '*คลองหาด', viewValue: '*คลองหาด', prvCode: '16' }, { value: 'เมืองนครนายก', viewValue: 'เมืองนครนายก', prvCode: '17' }, { value: 'ปากพลี', viewValue: 'ปากพลี', prvCode: '17' }, { value: 'บ้านนา', viewValue: 'บ้านนา', prvCode: '17' }, { value: 'องครักษ์', viewValue: 'องครักษ์', prvCode: '17' }, { value: 'เมืองสระแก้ว', viewValue: 'เมืองสระแก้ว', prvCode: '18' }, { value: 'คลองหาด', viewValue: 'คลองหาด', prvCode: '18' }, { value: 'ตาพระยา', viewValue: 'ตาพระยา', prvCode: '18' }, { value: 'วังน้ำเย็น', viewValue: 'วังน้ำเย็น', prvCode: '18' }, { value: 'วัฒนานคร', viewValue: 'วัฒนานคร', prvCode: '18' }, { value: 'อรัญประเทศ', viewValue: 'อรัญประเทศ', prvCode: '18' }, { value: 'เขาฉกรรจ์', viewValue: 'เขาฉกรรจ์', prvCode: '18' }, { value: 'โคกสูง', viewValue: 'โคกสูง', prvCode: '18' }, { value: 'วังสมบูรณ์', viewValue: 'วังสมบูรณ์', prvCode: '18' }, { value: 'เมืองนครราชสีมา', viewValue: 'เมืองนครราชสีมา', prvCode: '19' }, { value: 'ครบุรี', viewValue: 'ครบุรี', prvCode: '19' }, { value: 'เสิงสาง', viewValue: 'เสิงสาง', prvCode: '19' }, { value: 'คง', viewValue: 'คง', prvCode: '19' }, { value: 'บ้านเหลื่อม', viewValue: 'บ้านเหลื่อม', prvCode: '19' }, { value: 'จักราช', viewValue: 'จักราช', prvCode: '19' }, { value: 'โชคชัย', viewValue: 'โชคชัย', prvCode: '19' }, { value: 'ด่านขุนทด', viewValue: 'ด่านขุนทด', prvCode: '19' }, { value: 'โนนไทย', viewValue: 'โนนไทย', prvCode: '19' }, { value: 'โนนสูง', viewValue: 'โนนสูง', prvCode: '19' }, { value: 'ขามสะแกแสง', viewValue: 'ขามสะแกแสง', prvCode: '19' }, { value: 'บัวใหญ่', viewValue: 'บัวใหญ่', prvCode: '19' }, { value: 'ประทาย', viewValue: 'ประทาย', prvCode: '19' }, { value: 'ปักธงชัย', viewValue: 'ปักธงชัย', prvCode: '19' }, { value: 'พิมาย', viewValue: 'พิมาย', prvCode: '19' }, { value: 'ห้วยแถลง', viewValue: 'ห้วยแถลง', prvCode: '19' }, { value: 'ชุมพวง', viewValue: 'ชุมพวง', prvCode: '19' }, { value: 'สูงเนิน', viewValue: 'สูงเนิน', prvCode: '19' }, { value: 'ขามทะเลสอ', viewValue: 'ขามทะเลสอ', prvCode: '19' }, { value: 'สีคิ้ว', viewValue: 'สีคิ้ว', prvCode: '19' }, { value: 'ปากช่อง', viewValue: 'ปากช่อง', prvCode: '19' }, { value: 'หนองบุญมาก', viewValue: 'หนองบุญมาก', prvCode: '19' }, { value: 'แก้งสนามนาง', viewValue: 'แก้งสนามนาง', prvCode: '19' }, { value: 'โนนแดง', viewValue: 'โนนแดง', prvCode: '19' }, { value: 'วังน้ำเขียว', viewValue: 'วังน้ำเขียว', prvCode: '19' }, { value: 'เทพารักษ์', viewValue: 'เทพารักษ์', prvCode: '19' }, { value: 'เมืองยาง', viewValue: 'เมืองยาง', prvCode: '19' }, { value: 'พระทองคำ', viewValue: 'พระทองคำ', prvCode: '19' }, { value: 'ลำทะเมนชัย', viewValue: 'ลำทะเมนชัย', prvCode: '19' }, { value: 'บัวลาย', viewValue: 'บัวลาย', prvCode: '19' }, { value: 'สีดา', viewValue: 'สีดา', prvCode: '19' }, { value: 'เฉลิมพระเกียรติ', viewValue: 'เฉลิมพระเกียรติ', prvCode: '19' }, { value: 'ท้องถิ่นเทศบาลตำบลโพธิ์กลาง*', viewValue: 'ท้องถิ่นเทศบาลตำบลโพธิ์กลาง*', prvCode: '19' }, { value: 'สาขาตำบลมะค่า-พลสงคราม*', viewValue: 'สาขาตำบลมะค่า-พลสงคราม*', prvCode: '19' }, { value: '*โนนลาว', viewValue: '*โนนลาว', prvCode: '19' }, { value: 'เมืองบุรีรัมย์', viewValue: 'เมืองบุรีรัมย์', prvCode: '20' }, { value: 'คูเมือง', viewValue: 'คูเมือง', prvCode: '20' }, { value: 'กระสัง', viewValue: 'กระสัง', prvCode: '20' }, { value: 'นางรอง', viewValue: 'นางรอง', prvCode: '20' }, { value: 'หนองกี่', viewValue: 'หนองกี่', prvCode: '20' }, { value: 'ละหานทราย', viewValue: 'ละหานทราย', prvCode: '20' }, { value: 'ประโคนชัย', viewValue: 'ประโคนชัย', prvCode: '20' }, { value: 'บ้านกรวด', viewValue: 'บ้านกรวด', prvCode: '20' }, { value: 'พุทไธสง', viewValue: 'พุทไธสง', prvCode: '20' }, { value: 'ลำปลายมาศ', viewValue: 'ลำปลายมาศ', prvCode: '20' }, { value: 'สตึก', viewValue: 'สตึก', prvCode: '20' }, { value: 'ปะคำ', viewValue: 'ปะคำ', prvCode: '20' }, { value: 'นาโพธิ์', viewValue: 'นาโพธิ์', prvCode: '20' }, { value: 'หนองหงส์', viewValue: 'หนองหงส์', prvCode: '20' }, { value: 'พลับพลาชัย', viewValue: 'พลับพลาชัย', prvCode: '20' }, { value: 'ห้วยราช', viewValue: 'ห้วยราช', prvCode: '20' }, { value: 'โนนสุวรรณ', viewValue: 'โนนสุวรรณ', prvCode: '20' }, { value: 'ชำนิ', viewValue: 'ชำนิ', prvCode: '20' }, { value: 'บ้านใหม่ไชยพจน์', viewValue: 'บ้านใหม่ไชยพจน์', prvCode: '20' }, { value: 'โนนดินแดง', viewValue: 'โนนดินแดง', prvCode: '20' }, { value: 'บ้านด่าน', viewValue: 'บ้านด่าน', prvCode: '20' }, { value: 'แคนดง', viewValue: 'แคนดง', prvCode: '20' }, { value: 'เฉลิมพระเกียรติ', viewValue: 'เฉลิมพระเกียรติ', prvCode: '20' }, { value: 'เมืองสุรินทร์', viewValue: 'เมืองสุรินทร์', prvCode: '21' }, { value: 'ชุมพลบุรี', viewValue: 'ชุมพลบุรี', prvCode: '21' }, { value: 'ท่าตูม', viewValue: 'ท่าตูม', prvCode: '21' }, { value: 'จอมพระ', viewValue: 'จอมพระ', prvCode: '21' }, { value: 'ปราสาท', viewValue: 'ปราสาท', prvCode: '21' }, { value: 'กาบเชิง', viewValue: 'กาบเชิง', prvCode: '21' }, { value: 'รัตนบุรี', viewValue: 'รัตนบุรี', prvCode: '21' }, { value: 'สนม', viewValue: 'สนม', prvCode: '21' }, { value: 'ศีขรภูมิ', viewValue: 'ศีขรภูมิ', prvCode: '21' }, { value: 'สังขะ', viewValue: 'สังขะ', prvCode: '21' }, { value: 'ลำดวน', viewValue: 'ลำดวน', prvCode: '21' }, { value: 'สำโรงทาบ', viewValue: 'สำโรงทาบ', prvCode: '21' }, { value: 'บัวเชด', viewValue: 'บัวเชด', prvCode: '21' }, { value: 'พนมดงรัก', viewValue: 'พนมดงรัก', prvCode: '21' }, { value: 'ศรีณรงค์', viewValue: 'ศรีณรงค์', prvCode: '21' }, { value: 'เขวาสินรินทร์', viewValue: 'เขวาสินรินทร์', prvCode: '21' }, { value: 'โนนนารายณ์', viewValue: 'โนนนารายณ์', prvCode: '21' }, { value: 'เมืองศรีสะเกษ', viewValue: 'เมืองศรีสะเกษ', prvCode: '22' }, { value: 'ยางชุมน้อย', viewValue: 'ยางชุมน้อย', prvCode: '22' }, { value: 'กันทรารมย์', viewValue: 'กันทรารมย์', prvCode: '22' }, { value: 'กันทรลักษ์', viewValue: 'กันทรลักษ์', prvCode: '22' }, { value: 'ขุขันธ์', viewValue: 'ขุขันธ์', prvCode: '22' }, { value: 'ไพรบึง', viewValue: 'ไพรบึง', prvCode: '22' }, { value: 'ปรางค์กู่', viewValue: 'ปรางค์กู่', prvCode: '22' }, { value: 'ขุนหาญ', viewValue: 'ขุนหาญ', prvCode: '22' }, { value: 'ราษีไศล', viewValue: 'ราษีไศล', prvCode: '22' }, { value: 'อุทุมพรพิสัย', viewValue: 'อุทุมพรพิสัย', prvCode: '22' }, { value: 'บึงบูรพ์', viewValue: 'บึงบูรพ์', prvCode: '22' }, { value: 'ห้วยทับทัน', viewValue: 'ห้วยทับทัน', prvCode: '22' }, { value: 'โนนคูณ', viewValue: 'โนนคูณ', prvCode: '22' }, { value: 'ศรีรัตนะ', viewValue: 'ศรีรัตนะ', prvCode: '22' }, { value: 'น้ำเกลี้ยง', viewValue: 'น้ำเกลี้ยง', prvCode: '22' }, { value: 'วังหิน', viewValue: 'วังหิน', prvCode: '22' }, { value: 'ภูสิงห์', viewValue: 'ภูสิงห์', prvCode: '22' }, { value: 'เมืองจันทร์', viewValue: 'เมืองจันทร์', prvCode: '22' }, { value: 'เบญจลักษ์', viewValue: 'เบญจลักษ์', prvCode: '22' }, { value: 'พยุห์', viewValue: 'พยุห์', prvCode: '22' }, { value: 'โพธิ์ศรีสุวรรณ', viewValue: 'โพธิ์ศรีสุวรรณ', prvCode: '22' }, { value: 'ศิลาลาด', viewValue: 'ศิลาลาด', prvCode: '22' }, { value: 'เมืองอุบลราชธานี', viewValue: 'เมืองอุบลราชธานี', prvCode: '23' }, { value: 'ศรีเมืองใหม่', viewValue: 'ศรีเมืองใหม่', prvCode: '23' }, { value: 'โขงเจียม', viewValue: 'โขงเจียม', prvCode: '23' }, { value: 'เขื่องใน', viewValue: 'เขื่องใน', prvCode: '23' }, { value: 'เขมราฐ', viewValue: 'เขมราฐ', prvCode: '23' }, { value: '*ชานุมาน', viewValue: '*ชานุมาน', prvCode: '23' }, { value: 'เดชอุดม', viewValue: 'เดชอุดม', prvCode: '23' }, { value: 'นาจะหลวย', viewValue: 'นาจะหลวย', prvCode: '23' }, { value: 'น้ำยืน', viewValue: 'น้ำยืน', prvCode: '23' }, { value: 'บุณฑริก', viewValue: 'บุณฑริก', prvCode: '23' }, { value: 'ตระการพืชผล', viewValue: 'ตระการพืชผล', prvCode: '23' }, { value: 'กุดข้าวปุ้น', viewValue: 'กุดข้าวปุ้น', prvCode: '23' }, { value: '*พนา', viewValue: '*พนา', prvCode: '23' }, { value: 'ม่วงสามสิบ', viewValue: 'ม่วงสามสิบ', prvCode: '23' }, { value: 'วารินชำราบ', viewValue: 'วารินชำราบ', prvCode: '23' }, { value: '*อำนาจเจริญ', viewValue: '*อำนาจเจริญ', prvCode: '23' }, { value: '*เสนางคนิคม', viewValue: '*เสนางคนิคม', prvCode: '23' }, { value: '*หัวตะพาน', viewValue: '*หัวตะพาน', prvCode: '23' }, { value: 'พิบูลมังสาหาร', viewValue: 'พิบูลมังสาหาร', prvCode: '23' }, { value: 'ตาลสุม', viewValue: 'ตาลสุม', prvCode: '23' }, { value: 'โพธิ์ไทร', viewValue: 'โพธิ์ไทร', prvCode: '23' }, { value: 'สำโรง', viewValue: 'สำโรง', prvCode: '23' }, { value: '*กิ่งอำเภอลืออำนาจ', viewValue: '*กิ่งอำเภอลืออำนาจ', prvCode: '23' }, { value: 'ดอนมดแดง', viewValue: 'ดอนมดแดง', prvCode: '23' }, { value: 'สิรินธร', viewValue: 'สิรินธร', prvCode: '23' }, { value: 'ทุ่งศรีอุดม', viewValue: 'ทุ่งศรีอุดม', prvCode: '23' }, { value: '*ปทุมราชวงศา', viewValue: '*ปทุมราชวงศา', prvCode: '23' }, { value: '*กิ่งอำเภอศรีหลักชัย', viewValue: '*กิ่งอำเภอศรีหลักชัย', prvCode: '23' }, { value: 'นาเยีย', viewValue: 'นาเยีย', prvCode: '23' }, { value: 'นาตาล', viewValue: 'นาตาล', prvCode: '23' }, { value: 'เหล่าเสือโก้ก', viewValue: 'เหล่าเสือโก้ก', prvCode: '23' }, { value: 'สว่างวีระวงศ์', viewValue: 'สว่างวีระวงศ์', prvCode: '23' }, { value: 'น้ำขุ่น', viewValue: 'น้ำขุ่น', prvCode: '23' }, { value: '*อ.สุวรรณวารี จ.อุบลราชธานี', viewValue: '*อ.สุวรรณวารี จ.อุบลราชธานี', prvCode: '23' }, { value: 'เมืองยโสธร', viewValue: 'เมืองยโสธร', prvCode: '24' }, { value: 'ทรายมูล', viewValue: 'ทรายมูล', prvCode: '24' }, { value: 'กุดชุม', viewValue: 'กุดชุม', prvCode: '24' }, { value: 'คำเขื่อนแก้ว', viewValue: 'คำเขื่อนแก้ว', prvCode: '24' }, { value: 'ป่าติ้ว', viewValue: 'ป่าติ้ว', prvCode: '24' }, { value: 'มหาชนะชัย', viewValue: 'มหาชนะชัย', prvCode: '24' }, { value: 'ค้อวัง', viewValue: 'ค้อวัง', prvCode: '24' }, { value: 'เลิงนกทา', viewValue: 'เลิงนกทา', prvCode: '24' }, { value: 'ไทยเจริญ', viewValue: 'ไทยเจริญ', prvCode: '24' }, { value: 'เมืองชัยภูมิ', viewValue: 'เมืองชัยภูมิ', prvCode: '25' }, { value: 'บ้านเขว้า', viewValue: 'บ้านเขว้า', prvCode: '25' }, { value: 'คอนสวรรค์', viewValue: 'คอนสวรรค์', prvCode: '25' }, { value: 'เกษตรสมบูรณ์', viewValue: 'เกษตรสมบูรณ์', prvCode: '25' }, { value: 'หนองบัวแดง', viewValue: 'หนองบัวแดง', prvCode: '25' }, { value: 'จัตุรัส', viewValue: 'จัตุรัส', prvCode: '25' }, { value: 'บำเหน็จณรงค์', viewValue: 'บำเหน็จณรงค์', prvCode: '25' }, { value: 'หนองบัวระเหว', viewValue: 'หนองบัวระเหว', prvCode: '25' }, { value: 'เทพสถิต', viewValue: 'เทพสถิต', prvCode: '25' }, { value: 'ภูเขียว', viewValue: 'ภูเขียว', prvCode: '25' }, { value: 'บ้านแท่น', viewValue: 'บ้านแท่น', prvCode: '25' }, { value: 'แก้งคร้อ', viewValue: 'แก้งคร้อ', prvCode: '25' }, { value: 'คอนสาร', viewValue: 'คอนสาร', prvCode: '25' }, { value: 'ภักดีชุมพล', viewValue: 'ภักดีชุมพล', prvCode: '25' }, { value: 'เนินสง่า', viewValue: 'เนินสง่า', prvCode: '25' }, { value: 'ซับใหญ่', viewValue: 'ซับใหญ่', prvCode: '25' }, { value: 'เมืองชัยภูมิ (สาขาตำบลโนนสำราญ)*', viewValue: 'เมืองชัยภูมิ (สาขาตำบลโนนสำราญ)*', prvCode: '25' }, { value: 'สาขาตำบลบ้านหว่าเฒ่า*', viewValue: 'สาขาตำบลบ้านหว่าเฒ่า*', prvCode: '25' }, { value: 'หนองบัวแดง (สาขาตำบลวังชมภู)*', viewValue: 'หนองบัวแดง (สาขาตำบลวังชมภู)*', prvCode: '25' }, { value: 'กิ่งอำเภอซับใหญ่ (สาขาตำบลซับใหญ่)*', viewValue: 'กิ่งอำเภอซับใหญ่ (สาขาตำบลซับใหญ่)*', prvCode: '25' }, { value: 'สาขาตำบลโคกเพชร*', viewValue: 'สาขาตำบลโคกเพชร*', prvCode: '25' }, { value: 'เทพสถิต (สาขาตำบลนายางกลัก)*', viewValue: 'เทพสถิต (สาขาตำบลนายางกลัก)*', prvCode: '25' }, { value: 'บ้านแท่น (สาขาตำบลบ้านเต่า)*', viewValue: 'บ้านแท่น (สาขาตำบลบ้านเต่า)*', prvCode: '25' }, { value: 'แก้งคร้อ (สาขาตำบลท่ามะไฟหวาน)*', viewValue: 'แก้งคร้อ (สาขาตำบลท่ามะไฟหวาน)*', prvCode: '25' }, { value: 'คอนสาร (สาขาตำบลโนนคูณ)*', viewValue: 'คอนสาร (สาขาตำบลโนนคูณ)*', prvCode: '25' }, { value: 'เมืองอำนาจเจริญ', viewValue: 'เมืองอำนาจเจริญ', prvCode: '26' }, { value: 'ชานุมาน', viewValue: 'ชานุมาน', prvCode: '26' }, { value: 'ปทุมราชวงศา', viewValue: 'ปทุมราชวงศา', prvCode: '26' }, { value: 'พนา', viewValue: 'พนา', prvCode: '26' }, { value: 'เสนางคนิคม', viewValue: 'เสนางคนิคม', prvCode: '26' }, { value: 'หัวตะพาน', viewValue: 'หัวตะพาน', prvCode: '26' }, { value: 'ลืออำนาจ', viewValue: 'ลืออำนาจ', prvCode: '26' }, { value: 'เมืองหนองบัวลำภู', viewValue: 'เมืองหนองบัวลำภู', prvCode: '27' }, { value: 'นากลาง', viewValue: 'นากลาง', prvCode: '27' }, { value: 'โนนสัง', viewValue: 'โนนสัง', prvCode: '27' }, { value: 'ศรีบุญเรือง', viewValue: 'ศรีบุญเรือง', prvCode: '27' }, { value: 'สุวรรณคูหา', viewValue: 'สุวรรณคูหา', prvCode: '27' }, { value: 'นาวัง', viewValue: 'นาวัง', prvCode: '27' }, { value: 'เมืองขอนแก่น', viewValue: 'เมืองขอนแก่น', prvCode: '28' }, { value: 'บ้านฝาง', viewValue: 'บ้านฝาง', prvCode: '28' }, { value: 'พระยืน', viewValue: 'พระยืน', prvCode: '28' }, { value: 'หนองเรือ', viewValue: 'หนองเรือ', prvCode: '28' }, { value: 'ชุมแพ', viewValue: 'ชุมแพ', prvCode: '28' }, { value: 'สีชมพู', viewValue: 'สีชมพู', prvCode: '28' }, { value: 'น้ำพอง', viewValue: 'น้ำพอง', prvCode: '28' }, { value: 'อุบลรัตน์', viewValue: 'อุบลรัตน์', prvCode: '28' }, { value: 'กระนวน', viewValue: 'กระนวน', prvCode: '28' }, { value: 'บ้านไผ่', viewValue: 'บ้านไผ่', prvCode: '28' }, { value: 'เปือยน้อย', viewValue: 'เปือยน้อย', prvCode: '28' }, { value: 'พล', viewValue: 'พล', prvCode: '28' }, { value: 'แวงใหญ่', viewValue: 'แวงใหญ่', prvCode: '28' }, { value: 'แวงน้อย', viewValue: 'แวงน้อย', prvCode: '28' }, { value: 'หนองสองห้อง', viewValue: 'หนองสองห้อง', prvCode: '28' }, { value: 'ภูเวียง', viewValue: 'ภูเวียง', prvCode: '28' }, { value: 'มัญจาคีรี', viewValue: 'มัญจาคีรี', prvCode: '28' }, { value: 'ชนบท', viewValue: 'ชนบท', prvCode: '28' }, { value: 'เขาสวนกวาง', viewValue: 'เขาสวนกวาง', prvCode: '28' }, { value: 'ภูผาม่าน', viewValue: 'ภูผาม่าน', prvCode: '28' }, { value: 'ซำสูง', viewValue: 'ซำสูง', prvCode: '28' }, { value: 'โคกโพธิ์ไชย', viewValue: 'โคกโพธิ์ไชย', prvCode: '28' }, { value: 'หนองนาคำ', viewValue: 'หนองนาคำ', prvCode: '28' }, { value: 'บ้านแฮด', viewValue: 'บ้านแฮด', prvCode: '28' }, { value: 'โนนศิลา', viewValue: 'โนนศิลา', prvCode: '28' }, { value: 'เวียงเก่า', viewValue: 'เวียงเก่า', prvCode: '28' }, { value: 'ท้องถิ่นเทศบาลตำบลบ้านเป็ด*', viewValue: 'ท้องถิ่นเทศบาลตำบลบ้านเป็ด*', prvCode: '28' }, { value: 'เทศบาลตำบลเมืองพล*', viewValue: 'เทศบาลตำบลเมืองพล*', prvCode: '28' }, { value: 'เมืองอุดรธานี', viewValue: 'เมืองอุดรธานี', prvCode: '29' }, { value: 'กุดจับ', viewValue: 'กุดจับ', prvCode: '29' }, { value: 'หนองวัวซอ', viewValue: 'หนองวัวซอ', prvCode: '29' }, { value: 'กุมภวาปี', viewValue: 'กุมภวาปี', prvCode: '29' }, { value: 'โนนสะอาด', viewValue: 'โนนสะอาด', prvCode: '29' }, { value: 'หนองหาน', viewValue: 'หนองหาน', prvCode: '29' }, { value: 'ทุ่งฝน', viewValue: 'ทุ่งฝน', prvCode: '29' }, { value: 'ไชยวาน', viewValue: 'ไชยวาน', prvCode: '29' }, { value: 'ศรีธาตุ', viewValue: 'ศรีธาตุ', prvCode: '29' }, { value: 'วังสามหมอ', viewValue: 'วังสามหมอ', prvCode: '29' }, { value: 'บ้านดุง', viewValue: 'บ้านดุง', prvCode: '29' }, { value: '*หนองบัวลำภู', viewValue: '*หนองบัวลำภู', prvCode: '29' }, { value: '*ศรีบุญเรือง', viewValue: '*ศรีบุญเรือง', prvCode: '29' }, { value: '*นากลาง', viewValue: '*นากลาง', prvCode: '29' }, { value: '*สุวรรณคูหา', viewValue: '*สุวรรณคูหา', prvCode: '29' }, { value: '*โนนสัง', viewValue: '*โนนสัง', prvCode: '29' }, { value: 'บ้านผือ', viewValue: 'บ้านผือ', prvCode: '29' }, { value: 'น้ำโสม', viewValue: 'น้ำโสม', prvCode: '29' }, { value: 'เพ็ญ', viewValue: 'เพ็ญ', prvCode: '29' }, { value: 'สร้างคอม', viewValue: 'สร้างคอม', prvCode: '29' }, { value: 'หนองแสง', viewValue: 'หนองแสง', prvCode: '29' }, { value: 'นายูง', viewValue: 'นายูง', prvCode: '29' }, { value: 'พิบูลย์รักษ์', viewValue: 'พิบูลย์รักษ์', prvCode: '29' }, { value: 'กู่แก้ว', viewValue: 'กู่แก้ว', prvCode: '29' }, { value: 'ประจักษ์ศิลปาคม', viewValue: 'ประจักษ์ศิลปาคม', prvCode: '29' }, { value: 'เมืองเลย', viewValue: 'เมืองเลย', prvCode: '30' }, { value: 'นาด้วง', viewValue: 'นาด้วง', prvCode: '30' }, { value: 'เชียงคาน', viewValue: 'เชียงคาน', prvCode: '30' }, { value: 'ปากชม', viewValue: 'ปากชม', prvCode: '30' }, { value: 'ด่านซ้าย', viewValue: 'ด่านซ้าย', prvCode: '30' }, { value: 'นาแห้ว', viewValue: 'นาแห้ว', prvCode: '30' }, { value: 'ภูเรือ', viewValue: 'ภูเรือ', prvCode: '30' }, { value: 'ท่าลี่', viewValue: 'ท่าลี่', prvCode: '30' }, { value: 'วังสะพุง', viewValue: 'วังสะพุง', prvCode: '30' }, { value: 'ภูกระดึง', viewValue: 'ภูกระดึง', prvCode: '30' }, { value: 'ภูหลวง', viewValue: 'ภูหลวง', prvCode: '30' }, { value: 'ผาขาว', viewValue: 'ผาขาว', prvCode: '30' }, { value: 'เอราวัณ', viewValue: 'เอราวัณ', prvCode: '30' }, { value: 'หนองหิน', viewValue: 'หนองหิน', prvCode: '30' }, { value: 'เมืองหนองคาย', viewValue: 'เมืองหนองคาย', prvCode: '31' }, { value: 'ท่าบ่อ', viewValue: 'ท่าบ่อ', prvCode: '31' }, { value: 'เมืองบึงกาฬ', viewValue: 'เมืองบึงกาฬ', prvCode: '97' }, { value: 'พรเจริญ', viewValue: 'พรเจริญ', prvCode: '97' }, { value: 'โพนพิสัย', viewValue: 'โพนพิสัย', prvCode: '31' }, { value: 'โซ่พิสัย', viewValue: 'โซ่พิสัย', prvCode: '97' }, { value: 'ศรีเชียงใหม่', viewValue: 'ศรีเชียงใหม่', prvCode: '31' }, { value: 'สังคม', viewValue: 'สังคม', prvCode: '31' }, { value: 'เซกา', viewValue: 'เซกา', prvCode: '97' }, { value: 'ปากคาด', viewValue: 'ปากคาด', prvCode: '97' }, { value: 'บึงโขงหลง', viewValue: 'บึงโขงหลง', prvCode: '97' }, { value: 'ศรีวิไล', viewValue: 'ศรีวิไล', prvCode: '97' }, { value: 'บุ่งคล้า', viewValue: 'บุ่งคล้า', prvCode: '97' }, { value: 'สระใคร', viewValue: 'สระใคร', prvCode: '31' }, { value: 'เฝ้าไร่', viewValue: 'เฝ้าไร่', prvCode: '31' }, { value: 'รัตนวาปี', viewValue: 'รัตนวาปี', prvCode: '31' }, { value: 'โพธิ์ตาก', viewValue: 'โพธิ์ตาก', prvCode: '31' }, { value: 'เมืองมหาสารคาม', viewValue: 'เมืองมหาสารคาม', prvCode: '32' }, { value: 'แกดำ', viewValue: 'แกดำ', prvCode: '32' }, { value: 'โกสุมพิสัย', viewValue: 'โกสุมพิสัย', prvCode: '32' }, { value: 'กันทรวิชัย', viewValue: 'กันทรวิชัย', prvCode: '32' }, { value: 'เชียงยืน', viewValue: 'เชียงยืน', prvCode: '32' }, { value: 'บรบือ', viewValue: 'บรบือ', prvCode: '32' }, { value: 'นาเชือก', viewValue: 'นาเชือก', prvCode: '32' }, { value: 'พยัคฆภูมิพิสัย', viewValue: 'พยัคฆภูมิพิสัย', prvCode: '32' }, { value: 'วาปีปทุม', viewValue: 'วาปีปทุม', prvCode: '32' }, { value: 'นาดูน', viewValue: 'นาดูน', prvCode: '32' }, { value: 'ยางสีสุราช', viewValue: 'ยางสีสุราช', prvCode: '32' }, { value: 'กุดรัง', viewValue: 'กุดรัง', prvCode: '32' }, { value: 'ชื่นชม', viewValue: 'ชื่นชม', prvCode: '32' }, { value: '*หลุบ', viewValue: '*หลุบ', prvCode: '32' }, { value: 'เมืองร้อยเอ็ด', viewValue: 'เมืองร้อยเอ็ด', prvCode: '33' }, { value: 'เกษตรวิสัย', viewValue: 'เกษตรวิสัย', prvCode: '33' }, { value: 'ปทุมรัตต์', viewValue: 'ปทุมรัตต์', prvCode: '33' }, { value: 'จตุรพักตรพิมาน', viewValue: 'จตุรพักตรพิมาน', prvCode: '33' }, { value: 'ธวัชบุรี', viewValue: 'ธวัชบุรี', prvCode: '33' }, { value: 'พนมไพร', viewValue: 'พนมไพร', prvCode: '33' }, { value: 'โพนทอง', viewValue: 'โพนทอง', prvCode: '33' }, { value: 'โพธิ์ชัย', viewValue: 'โพธิ์ชัย', prvCode: '33' }, { value: 'หนองพอก', viewValue: 'หนองพอก', prvCode: '33' }, { value: 'เสลภูมิ', viewValue: 'เสลภูมิ', prvCode: '33' }, { value: 'สุวรรณภูมิ', viewValue: 'สุวรรณภูมิ', prvCode: '33' }, { value: 'เมืองสรวง', viewValue: 'เมืองสรวง', prvCode: '33' }, { value: 'โพนทราย', viewValue: 'โพนทราย', prvCode: '33' }, { value: 'อาจสามารถ', viewValue: 'อาจสามารถ', prvCode: '33' }, { value: 'เมยวดี', viewValue: 'เมยวดี', prvCode: '33' }, { value: 'ศรีสมเด็จ', viewValue: 'ศรีสมเด็จ', prvCode: '33' }, { value: 'จังหาร', viewValue: 'จังหาร', prvCode: '33' }, { value: 'เชียงขวัญ', viewValue: 'เชียงขวัญ', prvCode: '33' }, { value: 'หนองฮี', viewValue: 'หนองฮี', prvCode: '33' }, { value: 'ทุ่งเขาหลวง', viewValue: 'ทุ่งเขาหลวง', prvCode: '33' }, { value: 'เมืองกาฬสินธุ์', viewValue: 'เมืองกาฬสินธุ์', prvCode: '34' }, { value: 'นามน', viewValue: 'นามน', prvCode: '34' }, { value: 'กมลาไสย', viewValue: 'กมลาไสย', prvCode: '34' }, { value: 'ร่องคำ', viewValue: 'ร่องคำ', prvCode: '34' }, { value: 'กุฉินารายณ์', viewValue: 'กุฉินารายณ์', prvCode: '34' }, { value: 'เขาวง', viewValue: 'เขาวง', prvCode: '34' }, { value: 'ยางตลาด', viewValue: 'ยางตลาด', prvCode: '34' }, { value: 'ห้วยเม็ก', viewValue: 'ห้วยเม็ก', prvCode: '34' }, { value: 'สหัสขันธ์', viewValue: 'สหัสขันธ์', prvCode: '34' }, { value: 'คำม่วง', viewValue: 'คำม่วง', prvCode: '34' }, { value: 'ท่าคันโท', viewValue: 'ท่าคันโท', prvCode: '34' }, { value: 'หนองกุงศรี', viewValue: 'หนองกุงศรี', prvCode: '34' }, { value: 'สมเด็จ', viewValue: 'สมเด็จ', prvCode: '34' }, { value: 'ห้วยผึ้ง', viewValue: 'ห้วยผึ้ง', prvCode: '34' }, { value: 'สามชัย', viewValue: 'สามชัย', prvCode: '34' }, { value: 'นาคู', viewValue: 'นาคู', prvCode: '34' }, { value: 'ดอนจาน', viewValue: 'ดอนจาน', prvCode: '34' }, { value: 'ฆ้องชัย', viewValue: 'ฆ้องชัย', prvCode: '34' }, { value: 'เมืองสกลนคร', viewValue: 'เมืองสกลนคร', prvCode: '35' }, { value: 'กุสุมาลย์', viewValue: 'กุสุมาลย์', prvCode: '35' }, { value: 'กุดบาก', viewValue: 'กุดบาก', prvCode: '35' }, { value: 'พรรณานิคม', viewValue: 'พรรณานิคม', prvCode: '35' }, { value: 'พังโคน', viewValue: 'พังโคน', prvCode: '35' }, { value: 'วาริชภูมิ', viewValue: 'วาริชภูมิ', prvCode: '35' }, { value: 'นิคมน้ำอูน', viewValue: 'นิคมน้ำอูน', prvCode: '35' }, { value: 'วานรนิวาส', viewValue: 'วานรนิวาส', prvCode: '35' }, { value: 'คำตากล้า', viewValue: 'คำตากล้า', prvCode: '35' }, { value: 'บ้านม่วง', viewValue: 'บ้านม่วง', prvCode: '35' }, { value: 'อากาศอำนวย', viewValue: 'อากาศอำนวย', prvCode: '35' }, { value: 'สว่างแดนดิน', viewValue: 'สว่างแดนดิน', prvCode: '35' }, { value: 'ส่องดาว', viewValue: 'ส่องดาว', prvCode: '35' }, { value: 'เต่างอย', viewValue: 'เต่างอย', prvCode: '35' }, { value: 'โคกศรีสุพรรณ', viewValue: 'โคกศรีสุพรรณ', prvCode: '35' }, { value: 'เจริญศิลป์', viewValue: 'เจริญศิลป์', prvCode: '35' }, { value: 'โพนนาแก้ว', viewValue: 'โพนนาแก้ว', prvCode: '35' }, { value: 'ภูพาน', viewValue: 'ภูพาน', prvCode: '35' }, { value: 'วานรนิวาส (สาขาตำบลกุดเรือคำ)*', viewValue: 'วานรนิวาส (สาขาตำบลกุดเรือคำ)*', prvCode: '35' }, { value: '*อ.บ้านหัน จ.สกลนคร', viewValue: '*อ.บ้านหัน จ.สกลนคร', prvCode: '35' }, { value: 'เมืองนครพนม', viewValue: 'เมืองนครพนม', prvCode: '36' }, { value: 'ปลาปาก', viewValue: 'ปลาปาก', prvCode: '36' }, { value: 'ท่าอุเทน', viewValue: 'ท่าอุเทน', prvCode: '36' }, { value: 'บ้านแพง', viewValue: 'บ้านแพง', prvCode: '36' }, { value: 'ธาตุพนม', viewValue: 'ธาตุพนม', prvCode: '36' }, { value: 'เรณูนคร', viewValue: 'เรณูนคร', prvCode: '36' }, { value: 'นาแก', viewValue: 'นาแก', prvCode: '36' }, { value: 'ศรีสงคราม', viewValue: 'ศรีสงคราม', prvCode: '36' }, { value: 'นาหว้า', viewValue: 'นาหว้า', prvCode: '36' }, { value: 'โพนสวรรค์', viewValue: 'โพนสวรรค์', prvCode: '36' }, { value: 'นาทม', viewValue: 'นาทม', prvCode: '36' }, { value: 'วังยาง', viewValue: 'วังยาง', prvCode: '36' }, { value: 'เมืองมุกดาหาร', viewValue: 'เมืองมุกดาหาร', prvCode: '37' }, { value: 'นิคมคำสร้อย', viewValue: 'นิคมคำสร้อย', prvCode: '37' }, { value: 'ดอนตาล', viewValue: 'ดอนตาล', prvCode: '37' }, { value: 'ดงหลวง', viewValue: 'ดงหลวง', prvCode: '37' }, { value: 'คำชะอี', viewValue: 'คำชะอี', prvCode: '37' }, { value: 'หว้านใหญ่', viewValue: 'หว้านใหญ่', prvCode: '37' }, { value: 'หนองสูง', viewValue: 'หนองสูง', prvCode: '37' }, { value: 'เมืองเชียงใหม่', viewValue: 'เมืองเชียงใหม่', prvCode: '38' }, { value: 'จอมทอง', viewValue: 'จอมทอง', prvCode: '38' }, { value: 'แม่แจ่ม', viewValue: 'แม่แจ่ม', prvCode: '38' }, { value: 'เชียงดาว', viewValue: 'เชียงดาว', prvCode: '38' }, { value: 'ดอยสะเก็ด', viewValue: 'ดอยสะเก็ด', prvCode: '38' }, { value: 'แม่แตง', viewValue: 'แม่แตง', prvCode: '38' }, { value: 'แม่ริม', viewValue: 'แม่ริม', prvCode: '38' }, { value: 'สะเมิง', viewValue: 'สะเมิง', prvCode: '38' }, { value: 'ฝาง', viewValue: 'ฝาง', prvCode: '38' }, { value: 'แม่อาย', viewValue: 'แม่อาย', prvCode: '38' }, { value: 'พร้าว', viewValue: 'พร้าว', prvCode: '38' }, { value: 'สันป่าตอง', viewValue: 'สันป่าตอง', prvCode: '38' }, { value: 'สันกำแพง', viewValue: 'สันกำแพง', prvCode: '38' }, { value: 'สันทราย', viewValue: 'สันทราย', prvCode: '38' }, { value: 'หางดง', viewValue: 'หางดง', prvCode: '38' }, { value: 'ฮอด', viewValue: 'ฮอด', prvCode: '38' }, { value: 'ดอยเต่า', viewValue: 'ดอยเต่า', prvCode: '38' }, { value: 'อมก๋อย', viewValue: 'อมก๋อย', prvCode: '38' }, { value: 'สารภี', viewValue: 'สารภี', prvCode: '38' }, { value: 'เวียงแหง', viewValue: 'เวียงแหง', prvCode: '38' }, { value: 'ไชยปราการ', viewValue: 'ไชยปราการ', prvCode: '38' }, { value: 'แม่วาง', viewValue: 'แม่วาง', prvCode: '38' }, { value: 'แม่ออน', viewValue: 'แม่ออน', prvCode: '38' }, { value: 'ดอยหล่อ', viewValue: 'ดอยหล่อ', prvCode: '38' }, { value: 'เทศบาลนครเชียงใหม่ (สาขาแขวงกาลวิละ)*', viewValue: 'เทศบาลนครเชียงใหม่ (สาขาแขวงกาลวิละ)*', prvCode: '38' }, { value: 'เทศบาลนครเชียงใหม่ (สาขาแขวงศรีวิชั)*', viewValue: 'เทศบาลนครเชียงใหม่ (สาขาแขวงศรีวิชั)*', prvCode: '38' }, { value: 'เทศบาลนครเชียงใหม่ (สาขาเม็งราย)*', viewValue: 'เทศบาลนครเชียงใหม่ (สาขาเม็งราย)*', prvCode: '38' }, { value: 'เมืองลำพูน', viewValue: 'เมืองลำพูน', prvCode: '39' }, { value: 'แม่ทา', viewValue: 'แม่ทา', prvCode: '39' }, { value: 'บ้านโฮ่ง', viewValue: 'บ้านโฮ่ง', prvCode: '39' }, { value: 'ลี้', viewValue: 'ลี้', prvCode: '39' }, { value: 'ทุ่งหัวช้าง', viewValue: 'ทุ่งหัวช้าง', prvCode: '39' }, { value: 'ป่าซาง', viewValue: 'ป่าซาง', prvCode: '39' }, { value: 'บ้านธิ', viewValue: 'บ้านธิ', prvCode: '39' }, { value: 'เวียงหนองล่อง', viewValue: 'เวียงหนองล่อง', prvCode: '39' }, { value: 'เมืองลำปาง', viewValue: 'เมืองลำปาง', prvCode: '40' }, { value: 'แม่เมาะ', viewValue: 'แม่เมาะ', prvCode: '40' }, { value: 'เกาะคา', viewValue: 'เกาะคา', prvCode: '40' }, { value: 'เสริมงาม', viewValue: 'เสริมงาม', prvCode: '40' }, { value: 'งาว', viewValue: 'งาว', prvCode: '40' }, { value: 'แจ้ห่ม', viewValue: 'แจ้ห่ม', prvCode: '40' }, { value: 'วังเหนือ', viewValue: 'วังเหนือ', prvCode: '40' }, { value: 'เถิน', viewValue: 'เถิน', prvCode: '40' }, { value: 'แม่พริก', viewValue: 'แม่พริก', prvCode: '40' }, { value: 'แม่ทะ', viewValue: 'แม่ทะ', prvCode: '40' }, { value: 'สบปราบ', viewValue: 'สบปราบ', prvCode: '40' }, { value: 'ห้างฉัตร', viewValue: 'ห้างฉัตร', prvCode: '40' }, { value: 'เมืองปาน', viewValue: 'เมืองปาน', prvCode: '40' }, { value: 'เมืองอุตรดิตถ์', viewValue: 'เมืองอุตรดิตถ์', prvCode: '41' }, { value: 'ตรอน', viewValue: 'ตรอน', prvCode: '41' }, { value: 'ท่าปลา', viewValue: 'ท่าปลา', prvCode: '41' }, { value: 'น้ำปาด', viewValue: 'น้ำปาด', prvCode: '41' }, { value: 'ฟากท่า', viewValue: 'ฟากท่า', prvCode: '41' }, { value: 'บ้านโคก', viewValue: 'บ้านโคก', prvCode: '41' }, { value: 'พิชัย', viewValue: 'พิชัย', prvCode: '41' }, { value: 'ลับแล', viewValue: 'ลับแล', prvCode: '41' }, { value: 'ทองแสนขัน', viewValue: 'ทองแสนขัน', prvCode: '41' }, { value: 'เมืองแพร่', viewValue: 'เมืองแพร่', prvCode: '42' }, { value: 'ร้องกวาง', viewValue: 'ร้องกวาง', prvCode: '42' }, { value: 'ลอง', viewValue: 'ลอง', prvCode: '42' }, { value: 'สูงเม่น', viewValue: 'สูงเม่น', prvCode: '42' }, { value: 'เด่นชัย', viewValue: 'เด่นชัย', prvCode: '42' }, { value: 'สอง', viewValue: 'สอง', prvCode: '42' }, { value: 'วังชิ้น', viewValue: 'วังชิ้น', prvCode: '42' }, { value: 'หนองม่วงไข่', viewValue: 'หนองม่วงไข่', prvCode: '42' }, { value: 'เมืองน่าน', viewValue: 'เมืองน่าน', prvCode: '43' }, { value: 'แม่จริม', viewValue: 'แม่จริม', prvCode: '43' }, { value: 'บ้านหลวง', viewValue: 'บ้านหลวง', prvCode: '43' }, { value: 'นาน้อย', viewValue: 'นาน้อย', prvCode: '43' }, { value: 'ปัว', viewValue: 'ปัว', prvCode: '43' }, { value: 'ท่าวังผา', viewValue: 'ท่าวังผา', prvCode: '43' }, { value: 'เวียงสา', viewValue: 'เวียงสา', prvCode: '43' }, { value: 'ทุ่งช้าง', viewValue: 'ทุ่งช้าง', prvCode: '43' }, { value: 'เชียงกลาง', viewValue: 'เชียงกลาง', prvCode: '43' }, { value: 'นาหมื่น', viewValue: 'นาหมื่น', prvCode: '43' }, { value: 'สันติสุข', viewValue: 'สันติสุข', prvCode: '43' }, { value: 'บ่อเกลือ', viewValue: 'บ่อเกลือ', prvCode: '43' }, { value: 'สองแคว', viewValue: 'สองแคว', prvCode: '43' }, { value: 'ภูเพียง', viewValue: 'ภูเพียง', prvCode: '43' }, { value: 'เฉลิมพระเกียรติ', viewValue: 'เฉลิมพระเกียรติ', prvCode: '43' }, { value: 'เมืองพะเยา', viewValue: 'เมืองพะเยา', prvCode: '44' }, { value: 'จุน', viewValue: 'จุน', prvCode: '44' }, { value: 'เชียงคำ', viewValue: 'เชียงคำ', prvCode: '44' }, { value: 'เชียงม่วน', viewValue: 'เชียงม่วน', prvCode: '44' }, { value: 'ดอกคำใต้', viewValue: 'ดอกคำใต้', prvCode: '44' }, { value: 'ปง', viewValue: 'ปง', prvCode: '44' }, { value: 'แม่ใจ', viewValue: 'แม่ใจ', prvCode: '44' }, { value: 'ภูซาง', viewValue: 'ภูซาง', prvCode: '44' }, { value: 'ภูกามยาว', viewValue: 'ภูกามยาว', prvCode: '44' }, { value: 'เมืองเชียงราย', viewValue: 'เมืองเชียงราย', prvCode: '45' }, { value: 'เวียงชัย', viewValue: 'เวียงชัย', prvCode: '45' }, { value: 'เชียงของ', viewValue: 'เชียงของ', prvCode: '45' }, { value: 'เทิง', viewValue: 'เทิง', prvCode: '45' }, { value: 'พาน', viewValue: 'พาน', prvCode: '45' }, { value: 'ป่าแดด', viewValue: 'ป่าแดด', prvCode: '45' }, { value: 'แม่จัน', viewValue: 'แม่จัน', prvCode: '45' }, { value: 'เชียงแสน', viewValue: 'เชียงแสน', prvCode: '45' }, { value: 'แม่สาย', viewValue: 'แม่สาย', prvCode: '45' }, { value: 'แม่สรวย', viewValue: 'แม่สรวย', prvCode: '45' }, { value: 'เวียงป่าเป้า', viewValue: 'เวียงป่าเป้า', prvCode: '45' }, { value: 'พญาเม็งราย', viewValue: 'พญาเม็งราย', prvCode: '45' }, { value: 'เวียงแก่น', viewValue: 'เวียงแก่น', prvCode: '45' }, { value: 'ขุนตาล', viewValue: 'ขุนตาล', prvCode: '45' }, { value: 'แม่ฟ้าหลวง', viewValue: 'แม่ฟ้าหลวง', prvCode: '45' }, { value: 'แม่ลาว', viewValue: 'แม่ลาว', prvCode: '45' }, { value: 'เวียงเชียงรุ้ง', viewValue: 'เวียงเชียงรุ้ง', prvCode: '45' }, { value: 'ดอยหลวง', viewValue: 'ดอยหลวง', prvCode: '45' }, { value: 'เมืองแม่ฮ่องสอน', viewValue: 'เมืองแม่ฮ่องสอน', prvCode: '46' }, { value: 'ขุนยวม', viewValue: 'ขุนยวม', prvCode: '46' }, { value: 'ปาย', viewValue: 'ปาย', prvCode: '46' }, { value: 'แม่สะเรียง', viewValue: 'แม่สะเรียง', prvCode: '46' }, { value: 'แม่ลาน้อย', viewValue: 'แม่ลาน้อย', prvCode: '46' }, { value: 'สบเมย', viewValue: 'สบเมย', prvCode: '46' }, { value: 'ปางมะผ้า', viewValue: 'ปางมะผ้า', prvCode: '46' }, { value: '*อ.ม่วยต่อ จ.แม่ฮ่องสอน', viewValue: '*อ.ม่วยต่อ จ.แม่ฮ่องสอน', prvCode: '46' }, { value: 'เมืองนครสวรรค์', viewValue: 'เมืองนครสวรรค์', prvCode: '47' }, { value: 'โกรกพระ', viewValue: 'โกรกพระ', prvCode: '47' }, { value: 'ชุมแสง', viewValue: 'ชุมแสง', prvCode: '47' }, { value: 'หนองบัว', viewValue: 'หนองบัว', prvCode: '47' }, { value: 'บรรพตพิสัย', viewValue: 'บรรพตพิสัย', prvCode: '47' }, { value: 'เก้าเลี้ยว', viewValue: 'เก้าเลี้ยว', prvCode: '47' }, { value: 'ตาคลี', viewValue: 'ตาคลี', prvCode: '47' }, { value: 'ท่าตะโก', viewValue: 'ท่าตะโก', prvCode: '47' }, { value: 'ไพศาลี', viewValue: 'ไพศาลี', prvCode: '47' }, { value: 'พยุหะคีรี', viewValue: 'พยุหะคีรี', prvCode: '47' }, { value: 'ลาดยาว', viewValue: 'ลาดยาว', prvCode: '47' }, { value: 'ตากฟ้า', viewValue: 'ตากฟ้า', prvCode: '47' }, { value: 'แม่วงก์', viewValue: 'แม่วงก์', prvCode: '47' }, { value: 'แม่เปิน', viewValue: 'แม่เปิน', prvCode: '47' }, { value: 'ชุมตาบง', viewValue: 'ชุมตาบง', prvCode: '47' }, { value: 'สาขาตำบลห้วยน้ำหอม*', viewValue: 'สาขาตำบลห้วยน้ำหอม*', prvCode: '47' }, { value: 'กิ่งอำเภอชุมตาบง (สาขาตำบลชุมตาบง)*', viewValue: 'กิ่งอำเภอชุมตาบง (สาขาตำบลชุมตาบง)*', prvCode: '47' }, { value: 'แม่วงก์ (สาขาตำบลแม่เล่ย์)*', viewValue: 'แม่วงก์ (สาขาตำบลแม่เล่ย์)*', prvCode: '47' }, { value: 'เมืองอุทัยธานี', viewValue: 'เมืองอุทัยธานี', prvCode: '48' }, { value: 'ทัพทัน', viewValue: 'ทัพทัน', prvCode: '48' }, { value: 'สว่างอารมณ์', viewValue: 'สว่างอารมณ์', prvCode: '48' }, { value: 'หนองฉาง', viewValue: 'หนองฉาง', prvCode: '48' }, { value: 'หนองขาหย่าง', viewValue: 'หนองขาหย่าง', prvCode: '48' }, { value: 'บ้านไร่', viewValue: 'บ้านไร่', prvCode: '48' }, { value: 'ลานสัก', viewValue: 'ลานสัก', prvCode: '48' }, { value: 'ห้วยคต', viewValue: 'ห้วยคต', prvCode: '48' }, { value: 'เมืองกำแพงเพชร', viewValue: 'เมืองกำแพงเพชร', prvCode: '49' }, { value: 'ไทรงาม', viewValue: 'ไทรงาม', prvCode: '49' }, { value: 'คลองลาน', viewValue: 'คลองลาน', prvCode: '49' }, { value: 'ขาณุวรลักษบุรี', viewValue: 'ขาณุวรลักษบุรี', prvCode: '49' }, { value: 'คลองขลุง', viewValue: 'คลองขลุง', prvCode: '49' }, { value: 'พรานกระต่าย', viewValue: 'พรานกระต่าย', prvCode: '49' }, { value: 'ลานกระบือ', viewValue: 'ลานกระบือ', prvCode: '49' }, { value: 'ทรายทองวัฒนา', viewValue: 'ทรายทองวัฒนา', prvCode: '49' }, { value: 'ปางศิลาทอง', viewValue: 'ปางศิลาทอง', prvCode: '49' }, { value: 'บึงสามัคคี', viewValue: 'บึงสามัคคี', prvCode: '49' }, { value: 'โกสัมพีนคร', viewValue: 'โกสัมพีนคร', prvCode: '49' }, { value: 'เมืองตาก', viewValue: 'เมืองตาก', prvCode: '50' }, { value: 'บ้านตาก', viewValue: 'บ้านตาก', prvCode: '50' }, { value: 'สามเงา', viewValue: 'สามเงา', prvCode: '50' }, { value: 'แม่ระมาด', viewValue: 'แม่ระมาด', prvCode: '50' }, { value: 'ท่าสองยาง', viewValue: 'ท่าสองยาง', prvCode: '50' }, { value: 'แม่สอด', viewValue: 'แม่สอด', prvCode: '50' }, { value: 'พบพระ', viewValue: 'พบพระ', prvCode: '50' }, { value: 'อุ้มผาง', viewValue: 'อุ้มผาง', prvCode: '50' }, { value: 'วังเจ้า', viewValue: 'วังเจ้า', prvCode: '50' }, { value: '*กิ่ง อ.ท่าปุย จ.ตาก', viewValue: '*กิ่ง อ.ท่าปุย จ.ตาก', prvCode: '50' }, { value: 'เมืองสุโขทัย', viewValue: 'เมืองสุโขทัย', prvCode: '51' }, { value: 'บ้านด่านลานหอย', viewValue: 'บ้านด่านลานหอย', prvCode: '51' }, { value: 'คีรีมาศ', viewValue: 'คีรีมาศ', prvCode: '51' }, { value: 'กงไกรลาศ', viewValue: 'กงไกรลาศ', prvCode: '51' }, { value: 'ศรีสัชนาลัย', viewValue: 'ศรีสัชนาลัย', prvCode: '51' }, { value: 'ศรีสำโรง', viewValue: 'ศรีสำโรง', prvCode: '51' }, { value: 'สวรรคโลก', viewValue: 'สวรรคโลก', prvCode: '51' }, { value: 'ศรีนคร', viewValue: 'ศรีนคร', prvCode: '51' }, { value: 'ทุ่งเสลี่ยม', viewValue: 'ทุ่งเสลี่ยม', prvCode: '51' }, { value: 'เมืองพิษณุโลก', viewValue: 'เมืองพิษณุโลก', prvCode: '52' }, { value: 'นครไทย', viewValue: 'นครไทย', prvCode: '52' }, { value: 'ชาติตระการ', viewValue: 'ชาติตระการ', prvCode: '52' }, { value: 'บางระกำ', viewValue: 'บางระกำ', prvCode: '52' }, { value: 'บางกระทุ่ม', viewValue: 'บางกระทุ่ม', prvCode: '52' }, { value: 'พรหมพิราม', viewValue: 'พรหมพิราม', prvCode: '52' }, { value: 'วัดโบสถ์', viewValue: 'วัดโบสถ์', prvCode: '52' }, { value: 'วังทอง', viewValue: 'วังทอง', prvCode: '52' }, { value: 'เนินมะปราง', viewValue: 'เนินมะปราง', prvCode: '52' }, { value: 'เมืองพิจิตร', viewValue: 'เมืองพิจิตร', prvCode: '53' }, { value: 'วังทรายพูน', viewValue: 'วังทรายพูน', prvCode: '53' }, { value: 'โพธิ์ประทับช้าง', viewValue: 'โพธิ์ประทับช้าง', prvCode: '53' }, { value: 'ตะพานหิน', viewValue: 'ตะพานหิน', prvCode: '53' }, { value: 'บางมูลนาก', viewValue: 'บางมูลนาก', prvCode: '53' }, { value: 'โพทะเล', viewValue: 'โพทะเล', prvCode: '53' }, { value: 'สามง่าม', viewValue: 'สามง่าม', prvCode: '53' }, { value: 'ทับคล้อ', viewValue: 'ทับคล้อ', prvCode: '53' }, { value: 'สากเหล็ก', viewValue: 'สากเหล็ก', prvCode: '53' }, { value: 'บึงนาราง', viewValue: 'บึงนาราง', prvCode: '53' }, { value: 'ดงเจริญ', viewValue: 'ดงเจริญ', prvCode: '53' }, { value: 'วชิรบารมี', viewValue: 'วชิรบารมี', prvCode: '53' }, { value: 'เมืองเพชรบูรณ์', viewValue: 'เมืองเพชรบูรณ์', prvCode: '54' }, { value: 'ชนแดน', viewValue: 'ชนแดน', prvCode: '54' }, { value: 'หล่มสัก', viewValue: 'หล่มสัก', prvCode: '54' }, { value: 'หล่มเก่า', viewValue: 'หล่มเก่า', prvCode: '54' }, { value: 'วิเชียรบุรี', viewValue: 'วิเชียรบุรี', prvCode: '54' }, { value: 'ศรีเทพ', viewValue: 'ศรีเทพ', prvCode: '54' }, { value: 'หนองไผ่', viewValue: 'หนองไผ่', prvCode: '54' }, { value: 'บึงสามพัน', viewValue: 'บึงสามพัน', prvCode: '54' }, { value: 'น้ำหนาว', viewValue: 'น้ำหนาว', prvCode: '54' }, { value: 'วังโป่ง', viewValue: 'วังโป่ง', prvCode: '54' }, { value: 'เขาค้อ', viewValue: 'เขาค้อ', prvCode: '54' }, { value: 'เมืองราชบุรี', viewValue: 'เมืองราชบุรี', prvCode: '55' }, { value: 'จอมบึง', viewValue: 'จอมบึง', prvCode: '55' }, { value: 'สวนผึ้ง', viewValue: 'สวนผึ้ง', prvCode: '55' }, { value: 'ดำเนินสะดวก', viewValue: 'ดำเนินสะดวก', prvCode: '55' }, { value: 'บ้านโป่ง', viewValue: 'บ้านโป่ง', prvCode: '55' }, { value: 'บางแพ', viewValue: 'บางแพ', prvCode: '55' }, { value: 'โพธาราม', viewValue: 'โพธาราม', prvCode: '55' }, { value: 'ปากท่อ', viewValue: 'ปากท่อ', prvCode: '55' }, { value: 'วัดเพลง', viewValue: 'วัดเพลง', prvCode: '55' }, { value: 'บ้านคา', viewValue: 'บ้านคา', prvCode: '55' }, { value: 'ท้องถิ่นเทศบาลตำบลบ้านฆ้อง', viewValue: 'ท้องถิ่นเทศบาลตำบลบ้านฆ้อง', prvCode: '55' }, { value: 'เมืองกาญจนบุรี', viewValue: 'เมืองกาญจนบุรี', prvCode: '56' }, { value: 'ไทรโยค', viewValue: 'ไทรโยค', prvCode: '56' }, { value: 'บ่อพลอย', viewValue: 'บ่อพลอย', prvCode: '56' }, { value: 'ศรีสวัสดิ์', viewValue: 'ศรีสวัสดิ์', prvCode: '56' }, { value: 'ท่ามะกา', viewValue: 'ท่ามะกา', prvCode: '56' }, { value: 'ท่าม่วง', viewValue: 'ท่าม่วง', prvCode: '56' }, { value: 'ทองผาภูมิ', viewValue: 'ทองผาภูมิ', prvCode: '56' }, { value: 'สังขละบุรี', viewValue: 'สังขละบุรี', prvCode: '56' }, { value: 'พนมทวน', viewValue: 'พนมทวน', prvCode: '56' }, { value: 'เลาขวัญ', viewValue: 'เลาขวัญ', prvCode: '56' }, { value: 'ด่านมะขามเตี้ย', viewValue: 'ด่านมะขามเตี้ย', prvCode: '56' }, { value: 'หนองปรือ', viewValue: 'หนองปรือ', prvCode: '56' }, { value: 'ห้วยกระเจา', viewValue: 'ห้วยกระเจา', prvCode: '56' }, { value: 'สาขาตำบลท่ากระดาน*', viewValue: 'สาขาตำบลท่ากระดาน*', prvCode: '56' }, { value: '*บ้านทวน จ.กาญจนบุรี', viewValue: '*บ้านทวน จ.กาญจนบุรี', prvCode: '56' }, { value: 'เมืองสุพรรณบุรี', viewValue: 'เมืองสุพรรณบุรี', prvCode: '57' }, { value: 'เดิมบางนางบวช', viewValue: 'เดิมบางนางบวช', prvCode: '57' }, { value: 'ด่านช้าง', viewValue: 'ด่านช้าง', prvCode: '57' }, { value: 'บางปลาม้า', viewValue: 'บางปลาม้า', prvCode: '57' }, { value: 'ศรีประจันต์', viewValue: 'ศรีประจันต์', prvCode: '57' }, { value: 'ดอนเจดีย์', viewValue: 'ดอนเจดีย์', prvCode: '57' }, { value: 'สองพี่น้อง', viewValue: 'สองพี่น้อง', prvCode: '57' }, { value: 'สามชุก', viewValue: 'สามชุก', prvCode: '57' }, { value: 'อู่ทอง', viewValue: 'อู่ทอง', prvCode: '57' }, { value: 'หนองหญ้าไซ', viewValue: 'หนองหญ้าไซ', prvCode: '57' }, { value: 'เมืองนครปฐม', viewValue: 'เมืองนครปฐม', prvCode: '58' }, { value: 'กำแพงแสน', viewValue: 'กำแพงแสน', prvCode: '58' }, { value: 'นครชัยศรี', viewValue: 'นครชัยศรี', prvCode: '58' }, { value: 'ดอนตูม', viewValue: 'ดอนตูม', prvCode: '58' }, { value: 'บางเลน', viewValue: 'บางเลน', prvCode: '58' }, { value: 'สามพราน', viewValue: 'สามพราน', prvCode: '58' }, { value: 'พุทธมณฑล', viewValue: 'พุทธมณฑล', prvCode: '58' }, { value: 'เมืองสมุทรสาคร', viewValue: 'เมืองสมุทรสาคร', prvCode: '59' }, { value: 'กระทุ่มแบน', viewValue: 'กระทุ่มแบน', prvCode: '59' }, { value: 'บ้านแพ้ว', viewValue: 'บ้านแพ้ว', prvCode: '59' }, { value: 'เมืองสมุทรสงคราม', viewValue: 'เมืองสมุทรสงคราม', prvCode: '60' }, { value: 'บางคนที', viewValue: 'บางคนที', prvCode: '60' }, { value: 'อัมพวา', viewValue: 'อัมพวา', prvCode: '60' }, { value: 'เมืองเพชรบุรี', viewValue: 'เมืองเพชรบุรี', prvCode: '61' }, { value: 'เขาย้อย', viewValue: 'เขาย้อย', prvCode: '61' }, { value: 'หนองหญ้าปล้อง', viewValue: 'หนองหญ้าปล้อง', prvCode: '61' }, { value: 'ชะอำ', viewValue: 'ชะอำ', prvCode: '61' }, { value: 'ท่ายาง', viewValue: 'ท่ายาง', prvCode: '61' }, { value: 'บ้านลาด', viewValue: 'บ้านลาด', prvCode: '61' }, { value: 'บ้านแหลม', viewValue: 'บ้านแหลม', prvCode: '61' }, { value: 'แก่งกระจาน', viewValue: 'แก่งกระจาน', prvCode: '61' }, { value: 'เมืองประจวบคีรีขันธ์', viewValue: 'เมืองประจวบคีรีขันธ์', prvCode: '62' }, { value: 'กุยบุรี', viewValue: 'กุยบุรี', prvCode: '62' }, { value: 'ทับสะแก', viewValue: 'ทับสะแก', prvCode: '62' }, { value: 'บางสะพาน', viewValue: 'บางสะพาน', prvCode: '62' }, { value: 'บางสะพานน้อย', viewValue: 'บางสะพานน้อย', prvCode: '62' }, { value: 'ปราณบุรี', viewValue: 'ปราณบุรี', prvCode: '62' }, { value: 'หัวหิน', viewValue: 'หัวหิน', prvCode: '62' }, { value: 'สามร้อยยอด', viewValue: 'สามร้อยยอด', prvCode: '62' }, { value: 'เมืองนครศรีธรรมราช', viewValue: 'เมืองนครศรีธรรมราช', prvCode: '63' }, { value: 'พรหมคีรี', viewValue: 'พรหมคีรี', prvCode: '63' }, { value: 'ลานสกา', viewValue: 'ลานสกา', prvCode: '63' }, { value: 'ฉวาง', viewValue: 'ฉวาง', prvCode: '63' }, { value: 'พิปูน', viewValue: 'พิปูน', prvCode: '63' }, { value: 'เชียรใหญ่', viewValue: 'เชียรใหญ่', prvCode: '63' }, { value: 'ชะอวด', viewValue: 'ชะอวด', prvCode: '63' }, { value: 'ท่าศาลา', viewValue: 'ท่าศาลา', prvCode: '63' }, { value: 'ทุ่งสง', viewValue: 'ทุ่งสง', prvCode: '63' }, { value: 'นาบอน', viewValue: 'นาบอน', prvCode: '63' }, { value: 'ทุ่งใหญ่', viewValue: 'ทุ่งใหญ่', prvCode: '63' }, { value: 'ปากพนัง', viewValue: 'ปากพนัง', prvCode: '63' }, { value: 'ร่อนพิบูลย์', viewValue: 'ร่อนพิบูลย์', prvCode: '63' }, { value: 'สิชล', viewValue: 'สิชล', prvCode: '63' }, { value: 'ขนอม', viewValue: 'ขนอม', prvCode: '63' }, { value: 'หัวไทร', viewValue: 'หัวไทร', prvCode: '63' }, { value: 'บางขัน', viewValue: 'บางขัน', prvCode: '63' }, { value: 'ถ้ำพรรณรา', viewValue: 'ถ้ำพรรณรา', prvCode: '63' }, { value: 'จุฬาภรณ์', viewValue: 'จุฬาภรณ์', prvCode: '63' }, { value: 'พระพรหม', viewValue: 'พระพรหม', prvCode: '63' }, { value: 'นบพิตำ', viewValue: 'นบพิตำ', prvCode: '63' }, { value: 'ช้างกลาง', viewValue: 'ช้างกลาง', prvCode: '63' }, { value: 'เฉลิมพระเกียรติ', viewValue: 'เฉลิมพระเกียรติ', prvCode: '63' }, { value: 'เชียรใหญ่ (สาขาตำบลเสือหึง)*', viewValue: 'เชียรใหญ่ (สาขาตำบลเสือหึง)*', prvCode: '63' }, { value: 'สาขาตำบลสวนหลวง**', viewValue: 'สาขาตำบลสวนหลวง**', prvCode: '63' }, { value: 'ร่อนพิบูลย์ (สาขาตำบลหินตก)*', viewValue: 'ร่อนพิบูลย์ (สาขาตำบลหินตก)*', prvCode: '63' }, { value: 'หัวไทร (สาขาตำบลควนชะลิก)*', viewValue: 'หัวไทร (สาขาตำบลควนชะลิก)*', prvCode: '63' }, { value: 'ทุ่งสง (สาขาตำบลกะปาง)*', viewValue: 'ทุ่งสง (สาขาตำบลกะปาง)*', prvCode: '63' }, { value: 'เมืองกระบี่', viewValue: 'เมืองกระบี่', prvCode: '64' }, { value: 'เขาพนม', viewValue: 'เขาพนม', prvCode: '64' }, { value: 'เกาะลันตา', viewValue: 'เกาะลันตา', prvCode: '64' }, { value: 'คลองท่อม', viewValue: 'คลองท่อม', prvCode: '64' }, { value: 'อ่าวลึก', viewValue: 'อ่าวลึก', prvCode: '64' }, { value: 'ปลายพระยา', viewValue: 'ปลายพระยา', prvCode: '64' }, { value: 'ลำทับ', viewValue: 'ลำทับ', prvCode: '64' }, { value: 'เหนือคลอง', viewValue: 'เหนือคลอง', prvCode: '64' }, { value: 'เมืองพังงา', viewValue: 'เมืองพังงา', prvCode: '65' }, { value: 'เกาะยาว', viewValue: 'เกาะยาว', prvCode: '65' }, { value: 'กะปง', viewValue: 'กะปง', prvCode: '65' }, { value: 'ตะกั่วทุ่ง', viewValue: 'ตะกั่วทุ่ง', prvCode: '65' }, { value: 'ตะกั่วป่า', viewValue: 'ตะกั่วป่า', prvCode: '65' }, { value: 'คุระบุรี', viewValue: 'คุระบุรี', prvCode: '65' }, { value: 'ทับปุด', viewValue: 'ทับปุด', prvCode: '65' }, { value: 'ท้ายเหมือง', viewValue: 'ท้ายเหมือง', prvCode: '65' }, { value: 'เมืองภูเก็ต', viewValue: 'เมืองภูเก็ต', prvCode: '66' }, { value: 'กะทู้', viewValue: 'กะทู้', prvCode: '66' }, { value: 'ถลาง', viewValue: 'ถลาง', prvCode: '66' }, { value: '*ทุ่งคา', viewValue: '*ทุ่งคา', prvCode: '66' }, { value: 'เมืองสุราษฎร์ธานี', viewValue: 'เมืองสุราษฎร์ธานี', prvCode: '67' }, { value: 'กาญจนดิษฐ์', viewValue: 'กาญจนดิษฐ์', prvCode: '67' }, { value: 'ดอนสัก', viewValue: 'ดอนสัก', prvCode: '67' }, { value: 'เกาะสมุย', viewValue: 'เกาะสมุย', prvCode: '67' }, { value: 'เกาะพะงัน', viewValue: 'เกาะพะงัน', prvCode: '67' }, { value: 'ไชยา', viewValue: 'ไชยา', prvCode: '67' }, { value: 'ท่าชนะ', viewValue: 'ท่าชนะ', prvCode: '67' }, { value: 'คีรีรัฐนิคม', viewValue: 'คีรีรัฐนิคม', prvCode: '67' }, { value: 'บ้านตาขุน', viewValue: 'บ้านตาขุน', prvCode: '67' }, { value: 'พนม', viewValue: 'พนม', prvCode: '67' }, { value: 'ท่าฉาง', viewValue: 'ท่าฉาง', prvCode: '67' }, { value: 'บ้านนาสาร', viewValue: 'บ้านนาสาร', prvCode: '67' }, { value: 'บ้านนาเดิม', viewValue: 'บ้านนาเดิม', prvCode: '67' }, { value: 'เคียนซา', viewValue: 'เคียนซา', prvCode: '67' }, { value: 'เวียงสระ', viewValue: 'เวียงสระ', prvCode: '67' }, { value: 'พระแสง', viewValue: 'พระแสง', prvCode: '67' }, { value: 'พุนพิน', viewValue: 'พุนพิน', prvCode: '67' }, { value: 'ชัยบุรี', viewValue: 'ชัยบุรี', prvCode: '67' }, { value: 'วิภาวดี', viewValue: 'วิภาวดี', prvCode: '67' }, { value: 'เกาะพงัน (สาขาตำบลเกาะเต่า)*', viewValue: 'เกาะพงัน (สาขาตำบลเกาะเต่า)*', prvCode: '67' }, { value: '*อ.บ้านดอน จ.สุราษฎร์ธานี', viewValue: '*อ.บ้านดอน จ.สุราษฎร์ธานี', prvCode: '67' }, { value: 'เมืองระนอง', viewValue: 'เมืองระนอง', prvCode: '68' }, { value: 'ละอุ่น', viewValue: 'ละอุ่น', prvCode: '68' }, { value: 'กะเปอร์', viewValue: 'กะเปอร์', prvCode: '68' }, { value: 'กระบุรี', viewValue: 'กระบุรี', prvCode: '68' }, { value: 'สุขสำราญ', viewValue: 'สุขสำราญ', prvCode: '68' }, { value: 'เมืองชุมพร', viewValue: 'เมืองชุมพร', prvCode: '69' }, { value: 'ท่าแซะ', viewValue: 'ท่าแซะ', prvCode: '69' }, { value: 'ปะทิว', viewValue: 'ปะทิว', prvCode: '69' }, { value: 'หลังสวน', viewValue: 'หลังสวน', prvCode: '69' }, { value: 'ละแม', viewValue: 'ละแม', prvCode: '69' }, { value: 'พะโต๊ะ', viewValue: 'พะโต๊ะ', prvCode: '69' }, { value: 'สวี', viewValue: 'สวี', prvCode: '69' }, { value: 'ทุ่งตะโก', viewValue: 'ทุ่งตะโก', prvCode: '69' }, { value: 'เมืองสงขลา', viewValue: 'เมืองสงขลา', prvCode: '70' }, { value: 'สทิงพระ', viewValue: 'สทิงพระ', prvCode: '70' }, { value: 'จะนะ', viewValue: 'จะนะ', prvCode: '70' }, { value: 'นาทวี', viewValue: 'นาทวี', prvCode: '70' }, { value: 'เทพา', viewValue: 'เทพา', prvCode: '70' }, { value: 'สะบ้าย้อย', viewValue: 'สะบ้าย้อย', prvCode: '70' }, { value: 'ระโนด', viewValue: 'ระโนด', prvCode: '70' }, { value: 'กระแสสินธุ์', viewValue: 'กระแสสินธุ์', prvCode: '70' }, { value: 'รัตภูมิ', viewValue: 'รัตภูมิ', prvCode: '70' }, { value: 'สะเดา', viewValue: 'สะเดา', prvCode: '70' }, { value: 'หาดใหญ่', viewValue: 'หาดใหญ่', prvCode: '70' }, { value: 'นาหม่อม', viewValue: 'นาหม่อม', prvCode: '70' }, { value: 'ควนเนียง', viewValue: 'ควนเนียง', prvCode: '70' }, { value: 'บางกล่ำ', viewValue: 'บางกล่ำ', prvCode: '70' }, { value: 'สิงหนคร', viewValue: 'สิงหนคร', prvCode: '70' }, { value: 'คลองหอยโข่ง', viewValue: 'คลองหอยโข่ง', prvCode: '70' }, { value: 'ท้องถิ่นเทศบาลตำบลสำนักขาม', viewValue: 'ท้องถิ่นเทศบาลตำบลสำนักขาม', prvCode: '70' }, { value: 'เทศบาลตำบลบ้านพรุ*', viewValue: 'เทศบาลตำบลบ้านพรุ*', prvCode: '70' }, { value: 'เมืองสตูล', viewValue: 'เมืองสตูล', prvCode: '71' }, { value: 'ควนโดน', viewValue: 'ควนโดน', prvCode: '71' }, { value: 'ควนกาหลง', viewValue: 'ควนกาหลง', prvCode: '71' }, { value: 'ท่าแพ', viewValue: 'ท่าแพ', prvCode: '71' }, { value: 'ละงู', viewValue: 'ละงู', prvCode: '71' }, { value: 'ทุ่งหว้า', viewValue: 'ทุ่งหว้า', prvCode: '71' }, { value: 'มะนัง', viewValue: 'มะนัง', prvCode: '71' }, { value: 'เมืองตรัง', viewValue: 'เมืองตรัง', prvCode: '72' }, { value: 'กันตัง', viewValue: 'กันตัง', prvCode: '72' }, { value: 'ย่านตาขาว', viewValue: 'ย่านตาขาว', prvCode: '72' }, { value: 'ปะเหลียน', viewValue: 'ปะเหลียน', prvCode: '72' }, { value: 'สิเกา', viewValue: 'สิเกา', prvCode: '72' }, { value: 'ห้วยยอด', viewValue: 'ห้วยยอด', prvCode: '72' }, { value: 'วังวิเศษ', viewValue: 'วังวิเศษ', prvCode: '72' }, { value: 'นาโยง', viewValue: 'นาโยง', prvCode: '72' }, { value: 'รัษฎา', viewValue: 'รัษฎา', prvCode: '72' }, { value: 'หาดสำราญ', viewValue: 'หาดสำราญ', prvCode: '72' }, { value: 'อำเภอเมืองตรัง(สาขาคลองเต็ง)**', viewValue: 'อำเภอเมืองตรัง(สาขาคลองเต็ง)**', prvCode: '72' }, { value: 'เมืองพัทลุง', viewValue: 'เมืองพัทลุง', prvCode: '73' }, { value: 'กงหรา', viewValue: 'กงหรา', prvCode: '73' }, { value: 'เขาชัยสน', viewValue: 'เขาชัยสน', prvCode: '73' }, { value: 'ตะโหมด', viewValue: 'ตะโหมด', prvCode: '73' }, { value: 'ควนขนุน', viewValue: 'ควนขนุน', prvCode: '73' }, { value: 'ปากพะยูน', viewValue: 'ปากพะยูน', prvCode: '73' }, { value: 'ศรีบรรพต', viewValue: 'ศรีบรรพต', prvCode: '73' }, { value: 'ป่าบอน', viewValue: 'ป่าบอน', prvCode: '73' }, { value: 'บางแก้ว', viewValue: 'บางแก้ว', prvCode: '73' }, { value: 'ป่าพะยอม', viewValue: 'ป่าพะยอม', prvCode: '73' }, { value: 'ศรีนครินทร์', viewValue: 'ศรีนครินทร์', prvCode: '73' }, { value: 'เมืองปัตตานี', viewValue: 'เมืองปัตตานี', prvCode: '74' }, { value: 'โคกโพธิ์', viewValue: 'โคกโพธิ์', prvCode: '74' }, { value: 'หนองจิก', viewValue: 'หนองจิก', prvCode: '74' }, { value: 'ปะนาเระ', viewValue: 'ปะนาเระ', prvCode: '74' }, { value: 'มายอ', viewValue: 'มายอ', prvCode: '74' }, { value: 'ทุ่งยางแดง', viewValue: 'ทุ่งยางแดง', prvCode: '74' }, { value: 'สายบุรี', viewValue: 'สายบุรี', prvCode: '74' }, { value: 'ไม้แก่น', viewValue: 'ไม้แก่น', prvCode: '74' }, { value: 'ยะหริ่ง', viewValue: 'ยะหริ่ง', prvCode: '74' }, { value: 'ยะรัง', viewValue: 'ยะรัง', prvCode: '74' }, { value: 'กะพ้อ', viewValue: 'กะพ้อ', prvCode: '74' }, { value: 'แม่ลาน', viewValue: 'แม่ลาน', prvCode: '74' }, { value: 'เมืองยะลา', viewValue: 'เมืองยะลา', prvCode: '75' }, { value: 'เบตง', viewValue: 'เบตง', prvCode: '75' }, { value: 'บันนังสตา', viewValue: 'บันนังสตา', prvCode: '75' }, { value: 'ธารโต', viewValue: 'ธารโต', prvCode: '75' }, { value: 'ยะหา', viewValue: 'ยะหา', prvCode: '75' }, { value: 'รามัน', viewValue: 'รามัน', prvCode: '75' }, { value: 'กาบัง', viewValue: 'กาบัง', prvCode: '75' }, { value: 'กรงปินัง', viewValue: 'กรงปินัง', prvCode: '75' }, { value: 'เมืองนราธิวาส', viewValue: 'เมืองนราธิวาส', prvCode: '76' }, { value: 'ตากใบ', viewValue: 'ตากใบ', prvCode: '76' }, { value: 'บาเจาะ', viewValue: 'บาเจาะ', prvCode: '76' }, { value: 'ยี่งอ', viewValue: 'ยี่งอ', prvCode: '76' }, { value: 'ระแงะ', viewValue: 'ระแงะ', prvCode: '76' }, { value: 'รือเสาะ', viewValue: 'รือเสาะ', prvCode: '76' }, { value: 'ศรีสาคร', viewValue: 'ศรีสาคร', prvCode: '76' }, { value: 'แว้ง', viewValue: 'แว้ง', prvCode: '76' }, { value: 'สุคิริน', viewValue: 'สุคิริน', prvCode: '76' }, { value: 'สุไหงโก-ลก', viewValue: 'สุไหงโก-ลก', prvCode: '76' }, { value: 'สุไหงปาดี', viewValue: 'สุไหงปาดี', prvCode: '76' }, { value: 'จะแนะ', viewValue: 'จะแนะ', prvCode: '76' }, { value: 'เจาะไอร้อง', viewValue: 'เจาะไอร้อง', prvCode: '76' }, { value: '*อ.บางนรา จ.นราธิวาส', viewValue: '*อ.บางนรา จ.นราธิวาส', prvCode: '76' } ]; income = [ { value: '1', viewValue: 'น้อยกว่า 150,000 บาทต่อปี' }, { value: '3', viewValue: 'ตั้งแต่ 150,000 - 300,000 บาทต่อปี' }, { value: '4', viewValue: 'ตั้งแต่ 300,000- 450,000 บาทต่อปี' }, { value: '5', viewValue: 'ตั้งแต่ 450,000 - 600,000 บาทต่อปี' }, { value: '6', viewValue: 'ตั้งแต่ 600,000 - 1,000,000 บาทต่อปี' }, { value: '6', viewValue: 'ตั้งแต่ 1,000,000 - 3,000,000 บาทต่อปี' }, { value: '6', viewValue: 'มากกว่า 3,000,000 บาทต่อปี' }, ]; career = [ { value: '1', viewValue: 'ข้าราชการ' }, { value: '2', viewValue: 'พนักงานหน่วยงานรัฐ' }, { value: '3', viewValue: 'พนักงานรัฐวิสาหกิจ' }, { value: '4', viewValue: 'นักธุรกิจ' }, { value: '5', viewValue: 'ค้าขาย' }, { value: '6', viewValue: 'เกษตรกร' }, { value: '7', viewValue: 'ไม่ได้ประกอบอาชีพ' }, { value: '8', viewValue: 'อื่นๆ' } ]; studyStatusM1 = [ { value: '1', viewValue: 'กำลังศึกษาอยู่ชั้นประถมศึกษาปีที่ 6' }, { value: '2', viewValue: 'สำเร็จการศึกษาระดับชั้นประถมศึกษาปีที่ 6 แล้ว' }, ]; studyStatusM4 = [ { value: '1', viewValue: 'กำลังศึกษาอยู่ระดับชั้นมัธยมศึกษาปีที่ 3' }, { value: '2', viewValue: 'สำเร็จการศึกษาระดับชั้นมัธยมศึกษาปีที่ 3 แล้ว' }, ]; couseM1 = [ { value: '1', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาไทย)' }, { value: '2', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์ (ภาษาอังกฤษ)' }, { value: '3', viewValue: 'เลือกทั้งสองแผน' } ]; couseM4 = [ { value: '1', viewValue: 'เลือกแผนวิทยาศาสตร์ - คณิตศาสตร์' }, { value: '2', viewValue: 'เลือกแผนภาษาอังกฤษ - คณิตศาสตร์' } ]; preNmaes = [ { value: 'เด็กชาย', viewValue: 'เด็กชาย' }, { value: 'เด็กหญิง', viewValue: 'เด็กหญิง' }, { value: 'นาย', viewValue: 'นาย' }, { value: 'นางสาว', viewValue: 'นางสาว' } ]; numOfDate = [ { value: '01', viewValue: '01' }, { value: '02', viewValue: '02' }, { value: '03', viewValue: '03' }, { value: '04', viewValue: '04' }, { value: '05', viewValue: '05' }, { value: '06', viewValue: '06' }, { value: '07', viewValue: '07' }, { value: '08', viewValue: '08' }, { value: '09', viewValue: '09' }, { value: '10', viewValue: '10' }, { value: '11', viewValue: '11' }, { value: '12', viewValue: '12' }, { value: '13', viewValue: '13' }, { value: '14', viewValue: '14' }, { value: '15', viewValue: '15' }, { value: '16', viewValue: '16' }, { value: '17', viewValue: '17' }, { value: '18', viewValue: '18' }, { value: '19', viewValue: '19' }, { value: '20', viewValue: '20' }, { value: '21', viewValue: '21' }, { value: '22', viewValue: '22' }, { value: '23', viewValue: '23' }, { value: '24', viewValue: '24' }, { value: '25', viewValue: '25' }, { value: '26', viewValue: '26' }, { value: '27', viewValue: '27' }, { value: '28', viewValue: '28' }, { value: '29', viewValue: '29' }, { value: '30', viewValue: '30' }, { value: '31', viewValue: '31' } ]; numOfMounts = [ { value: '01', viewValue: 'มกราคม' }, { value: '02', viewValue: 'กุมภาพันธ์' }, { value: '03', viewValue: 'มีนาคม' }, { value: '04', viewValue: 'เมษายน' }, { value: '05', viewValue: 'พฤษภาคม' }, { value: '06', viewValue: 'มิถุนายน' }, { value: '07', viewValue: 'กรกฎาคม' }, { value: '08', viewValue: 'สิงหาคม' }, { value: '09', viewValue: 'กันยายน' }, { value: '10', viewValue: 'ตุลาคม' }, { value: '11', viewValue: 'พฤศจิกายน' }, { value: '12', viewValue: 'ธันวาคม' } ]; numOfYears = [ { value: '2540', viewValue: '2540' }, { value: '2541', viewValue: '2541' }, { value: '2542', viewValue: '2542' }, { value: '2543', viewValue: '2543' }, { value: '2544', viewValue: '2544' }, { value: '2545', viewValue: '2545' }, { value: '2546', viewValue: '2546' }, { value: '2547', viewValue: '2547' }, { value: '2548', viewValue: '2548' }, { value: '2549', viewValue: '2549' }, { value: '2550', viewValue: '2550' } ]; @Output() public fileHoverStart: EventEmitter<any> = new EventEmitter<any>(); @Output() public fileHoverEnd: EventEmitter<any> = new EventEmitter<any>(); @Output() // public fileAccepted: EventEmitter<FileManager[]> = new EventEmitter<FileManager[]>(); @Output() public fileRejected: EventEmitter<Error> = new EventEmitter<Error>(); @Output() public progress: EventEmitter<number> = new EventEmitter<number>(); @Input() // public fileOptions: FileManagerOptions; @Input() public maxFiles: number; public imageLoaded: boolean = false; private _limit: number = -1; // private _files: FileManager[]; // private _lastFile$: BehaviorSubject<FileManager> = new BehaviorSubject(null); // private _files$: BehaviorSubject<FileManager[]> = new BehaviorSubject([]); // public get files(): any { // let files = this._files$.getValue(); // return files; // } // public get latestFile(): any { // return Utils.asObservable(this._lastFile$); // } // public onFileHoverStart(event: any): void { // this.fileHoverStart.emit(event); // } // public onFileHoverEnd(event: any): void { // this.fileHoverEnd.emit(event); // } // public onFileAccepted(event: any): void { // if (event.length > 0) { // this.imageLoaded = true; // } // this._files$.next(event); // this.checkClass(); // this.fileAccepted.emit(event); // } // public onFileRejected(event: any): void { // this.fileRejected.emit(event); // } // public onProgress(event: number): void { // this.progress.emit(event); // } // private checkClass(): void { // (this._files.length > 0) ? // this.renderer.setElementClass(this.element.nativeElement, 'has-files', true) : // this.renderer.setElementClass(this.element.nativeElement, 'has-files', false); // this.cleanUp(); // } // private cleanUp(): void { // let files = this._files$.getValue(); // for (let key in files) { // if (files.hasOwnProperty(key)) { // let file = files[key]; // (!file.inQueue) && files.splice(+key, 1); // } // } // (files.length > 0) && this._lastFile$.next(files[files.length - 1]); // (files.length === 0) && this._lastFile$.next(null); // this._files$.next(files); // } }
9da693bfb0a2768843306d0cfc83cdf4d7b0ba79
[ "TypeScript" ]
9
TypeScript
WanchalermDevs/AdmissionSite2018
ba471db5af279d8dcd09e8fea94f929fc1b9c39d
14a3fe71f6d41491a6328041aa408b019fcbf255
refs/heads/master
<file_sep># # Cookbook Name:: hrpsys-base # Recipe:: default # # Copyright 2014, <NAME> # # 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. # include_recipe 'build-essential' include_recipe 'python' include_recipe 'subversion::client' include_recipe 'omniorb' include_recipe 'collada-dom' include_recipe 'openrtm-aist' include_recipe 'openhrp' pkgs = value_for_platform_family( ['debian'] => %w(libqhull-dev libirrlicht-dev libsdl1.2-dev freeglut3-dev libxmu-dev libglew-dev libopencv-dev libgtest-dev libboost-python-dev ipython python-tk) ) pkgs.each do |pkg| package pkg do action :install end end bash 'compile_hrpsys-base' do cwd "#{Chef::Config['file_cache_path']}/hrpsys-base" code <<-EOH sed -i "s/boost_system-mt/boost_system/g" lib/util/CMakeLists.txt sed -i "s/boost_thread-mt/boost_thread/g" lib/util/CMakeLists.txt ln -s /usr/include/opencv2 /usr/include/opencv ln -s /usr/include/opencv2/opencv.hpp /usr/include/opencv/cv.h ln -s /usr/include/opencv2/highgui/highgui.hpp /usr/include/opencv/highgui.h cmake . -DCOMPILE_JAVA_STUFF=OFF -DENABLE_DOXYGEN=OFF make clean && make && make install ldconfig EOH action :nothing end subversion 'hrpsys-base' do repository 'http://hrpsys-base.googlecode.com/svn/trunk/' revision 'HEAD' destination "#{Chef::Config[:file_cache_path]}/hrpsys-base" action :sync notifies :run, 'bash[compile_hrpsys-base]', :immediately end <file_sep>site :opscode metadata cookbook 'omniorb', git: 'https://github.com/devrt/chef-omniorb.git' cookbook 'collada-dom', git: 'https://github.com/devrt/chef-collada-dom.git' cookbook 'openrtm-aist', git: 'https://github.com/devrt/chef-openrtm-aist.git' cookbook 'openhrp', git: 'https://github.com/devrt/chef-openhrp.git' <file_sep>hrpsys-base Cookbook ================ This cookbook will install hrpsys-base simulator frontend. [![Build Status](http://ci.devrt.tk/job/chef-hrpsys-base/badge/icon)](http://ci.devrt.tk/job/chef-hrpsys-base/) Requirements ------------ - `build-essential` - hrpsys-base requires c++ compiler. - `python` - hrpsys-base requires python. - `omniorb` - hrpsys-base requires omniORB. - `collada-d0m` - hrpsys-base requires collada-dom. - `openrtm-aist` - hrpsys-base requires OpenRTM-aist. - `openhrp` - hrpsys-base requires OpenHRP. Attributes ---------- No attributes yet. Usage ----- Just include `hrpsys-base` in your node's `run_list`: ```json { "name":"my_node", "run_list": [ "recipe[hrpsys-base]" ] } ``` Contributing ------------ 1. Fork the repository on Github 2. Create a named feature branch (like `add_component_x`) 3. Write your change 4. Write tests for your change (if applicable) 5. Run the tests, ensuring they all pass 6. Submit a Pull Request using Github License and Authors ------------------- Apache 2.0 Authors: <NAME>
d6914996d56f614b33898a8b854e54d32255e129
[ "Markdown", "Ruby" ]
3
Ruby
devrt/chef-hrpsys-base
6968f33f47ae55bacba8819cff7b9db6427f99ce
c9350af406415b03689e1a70cd36f04d59f61c21
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Vip; use App\Http\Controllers\Controller; use App\Model\App; use App\Model\Folder; use App\Model\Vip; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Qiniu\Storage; class AppController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * create app * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * create app (include infomation) diy * * @return \Illuminate\Http\Response */ public function appCreate() { return view('vip.app.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function appStore(Request $request) { // $listkey = 'LIST:ARTICLE'; // $hashkey = 'HASH:ARTICLE:'; // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); $appname = $request->input('app_name'); $appurl = $request->input('app_url'); $appver = $request->input('app_version'); $appsort = $request->input('app_sort'); $appplat = $request->input('app_plat'); $apploc = $request->input('art_thumb'); $appdoc = $request->input('app_doc'); $fid = $request->input('app_path'); // 查看用户输入的id是否存在 $folder = Folder::find($fid); if(empty($folder) and $fid != 0) { return back()->with('errors','存放位置不合法'); } // 判断app_path是否属于当前操作对象的 if($fid){ $userfolder = DB::table('vipuser_folder as a') ->where(function ($q) use($fid){ $q->where('a.folder_id','=',$fid); }) ->where(function ($q) use($currentUser){ $q->where('a.user_id','=',$currentUser->user_id); }) ->get(); if(empty($userfolder)){ return back()->with('errors','存放位置不合法'); } } // 添加到数据库app表 $res = App::create(['app_name'=>$appname, 'app_url'=>$appurl, 'app_version'=>$appver, 'app_sort'=>$appsort, 'app_platform'=>$appplat, 'app_location'=>$apploc, 'app_doc'=>$appdoc, 'app_userid'=>$currentUser->user_id]); // 获取新建app的id号码 $currentApp = App::where('app_location',$apploc)->where('app_userid',$currentUser->user_id)->first(); // 添加到数据库folder_app表 \DB::table('folder_app')->insert(['app_id'=>$currentApp->app_id,'folder_id'=>$fid]); if($res){ // 如果添加成功,更新redis // \Redis::rpush($listkey,$res->art_id); // \Redis::hMset($hashkey.$res->art_id,$res->toArray()); return redirect('vip/app/{app}/create')->with('errors','操作成功'); }else{ return back()->with('errors','操作失败'); } } /** * 本地上传到指定临时文件夹 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ //文章上传 public function upload(Request $request) { //获取上传文件 $file = $request->file('app'); //判断上传文件是否成功 if(!$file->isValid()){ return response()->json(['ServerNo'=>'400','ResultData'=>'无效的上传文件','OriginalName'=>'上传失败,请重新上传']); } //获取原文件扩展名 $ext = $file->getClientOriginalExtension(); //文件拓展名 $name = $file->getClientOriginalName(); //原文件名 // dd($name); //新文件名 $newfile = md5(time().rand(1000,9999)).'.'.$ext; //设置软件存放路径 $path = public_path('app_cache'); //1.本地目录:将文件从临时目录移动到本地指定目录 if(! $file->move($path,$newfile)){ return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败','OriginalName'=>'上传失败,请重新上传']); } return response()->json(['ServerNo'=>'200','ResultData'=>$newfile,'OriginalName'=>$name]); // 2. 将文件上传到OSS的指定仓库 // $osskey : 文件上传到oss仓库后的新文件名 // $filePath:要上传的文件资源 // $res = OSS::upload($newfile, $file->getRealPath()); //// 3. 将文件上传到七牛云存储的指定仓库 //// $qiniu = Storage::disk('qiniu'); // // $res = \Storage::disk('qiniu')->writeStream($newfile, fopen($file->getRealPath(), 'r')); // // //// $res = Image::make($file)->resize(100,100)->save($path.'/'.$newfile); // // if($res){ // // 如果上传成功 // return response()->json(['ServerNo'=>'200','ResultData'=>$newfile]); // }else{ // return response()->json(['ServerNo'=>'400','ResultData'=>'上传文件失败']); // } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $app = App::find($id); return view('vip.app.show',compact('app')); } /** * move app to special folder * * @param int $id * @return \Illuminate\Http\Response */ public function appMove(Request $request,$id) { $app = App::find($id); return view('vip.app.move',compact('app')); } /** * app move data operation * * @param int $id * @return \Illuminate\Http\Response */ public function appMoveUpdate(Request $request,$id) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); $app = App::find($id); $toFolderid = $request->input('toFolderid'); // 1.判断用户输入的id是否存在且是自己的 $toFolder = DB::table('folder as a') ->where(function ($q) use($toFolderid){ $q->where('folder_id','=',$toFolderid); }) ->where(function ($q) use($currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',0); })->get(); if(!count($toFolder)) { $data = 3; return $data; } // 3.修改数据库中相应值 $res1 = \DB::table('folder_app')->where('app_id',$id)->delete(); $res2 = \DB::table('folder_app')->insert(['folder_id'=>$toFolderid,'app_id'=>$id]); if($res1 and $res2){ $data = 0; }else{ $data = 1; } return $data; } /** * modify the loaded app * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $appid = $id; return view('vip.app.edit',compact('appid')); } /** * upload again * * @param int $id * @return \Illuminate\Http\Response */ public function uploadAgain(Request $request,$id) { //获取上传文件 $file = $request->file('app'); //判断上传文件是否成功 if(!$file->isValid()){ return response()->json(['ServerNo'=>'400','ResultData'=>'无效的上传文件','OriginalName'=>'上传失败,请重新上传']); } //获取原文件扩展名 $ext = $file->getClientOriginalExtension(); //文件拓展名 $name = $file->getClientOriginalName(); //原文件名 // dd($name); //新文件名 $newfile = md5(time().rand(1000,9999)).'.'.$ext; //设置软件存放路径 $path = public_path('app_cache'); //1.本地目录:将文件从临时目录移动到本地指定目录 if(! $file->move($path,$newfile)){ return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败','OriginalName'=>'上传失败,请重新上传']); } return response()->json(['ServerNo'=>'200','ResultData'=>$newfile,'OriginalName'=>$name]); } public function storeAgain(Request $request,$id) { // $listkey = 'LIST:ARTICLE'; // $hashkey = 'HASH:ARTICLE:'; // 获取当前app $app = App::find($id); //// 获取当前登录用户 // $currentUser = Vip::find(session()->get('vip')->user_id); $appname = $request->input('app_name'); $appurl = $request->input('app_url'); $appver = $request->input('app_version'); $appsort = $request->input('app_sort'); $appplat = $request->input('app_plat'); $apploc = $request->input('art_thumb'); $appdoc = $request->input('app_doc'); // 删除之前存的东西通过文件名 // // 取到磁盘实例 // $disk = \Illuminate\Support\Facades\Storage::disk('local'); // $disk->delete($app->); // 修改数据库中相应值 $app->app_name = $appname; $app->app_url = $appurl; $app->app_version = $appver; $app->app_sort = $appsort; $app->app_platform = $appplat; $app->app_location = $apploc; $app->app_doc = $appdoc; $res = $app->save(); if($res){ // 如果添加成功,更新redis // \Redis::rpush($listkey,$res->art_id); // \Redis::hMset($hashkey.$res->art_id,$res->toArray()); return redirect('vip/app/{app}/edit')->with('errors','操作成功'); }else{ return back()->with('errors','操作失败'); } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $app = App::find($id); $res1 = $app->delete(); $res2 = DB::table('folder_app')->where('app_id',$app->app_id)->delete(); if($res1 and $res2){ $data = 0; }else{ $data = 1; } return $data; } /** * aside show the app as founction * * @param int $id * @return \Illuminate\Http\Response */ public function asideShow($id) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); if($id>=0 and $id<=7) { $appitem = DB::table('app')->where('app_userid',$currentUser->user_id)->get(); $app = []; foreach ($appitem as $v){ if($v->app_sort == $id){ $app[] = $v; } } } else if($id == 8 or $id == 9){ $appitem = DB::table('app')->where('app_userid',$currentUser->user_id)->get(); $app = []; foreach ($appitem as $v){ if($v->app_platform == $id-8){ $app[] = $v; } } }else { } return view('vip.app.sort',compact('app')); } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class Folder extends Model { // 1.关联的数据表 public $table = 'folder'; // 2.主键 public $primaryKey = 'folder_id'; // 3.允许批量操作的字段 public $guarded = []; // 4.是否维护created_at和update_at字段 public $timestamps = false; // 5.添加动态属性,关联权限模型 public function app(){ return $this->belongsToMany('App\Model\App','folder_app','folder_id','app_id'); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use App\Model\User; use App\Model\Role; use App\Model\Permission; class IsPermission { /** * 处理用户:根据用户是否有权限取得某些路由酌情操作. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { // 1.获取当前请求路由的控制器及方法,即Route::get('role/{id}/auth','RoleController@auth');的Action部分 $url = \Route::current()->getActionName(); // 2.获取当前用户拥有的所有权限 $user = User::find(session()->get('user')->user_id); $roles = $user->role; // $pres放用户拥有所有权限的url集合(可能存在重复权限) $pres = []; foreach ($roles as $v){ $ps = $v->permission; foreach ($ps as $p){ $pres[] = $p->pre_url; } } // 3.权限去重 $pres = array_unique($pres); // 4.根据当前用户是否拥有对当前页面访问的权限给予合理操作 if(in_array($url,$pres)){ //满足条件,给予权限 return $next($request); }else{ return redirect('admin/noaccess'); } } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; //use App\User; use App\Model\Role; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use App\Model\User; use Illuminate\Support\Facades\DB; class UserController extends Controller { /** * 返回后台用户列表页 * * @return \Illuminate\Http\Response */ public function index(Request $request) { // 1.获取提取的请求参数 // $input = $request->all(); // dd($input); $user = User::orderBy('user_id','asc') ->where(function ($query) use ($request){ $username = $request->input('username'); if(!empty($username)){ $query->where('user_name','like','%'.$username.'%'); } }) ->paginate($request->input('num')?$request->input('num'):10); // $user = User::get(); // $user = User::paginate(2); return view('admin.user.list',compact('user','request')); } /** * 返回后台用户添加页面 * * @return \Illuminate\Http\Response */ public function create() { return view('admin.user.add'); } /** * 执行添加操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // 1.接收前台传来的表单数据 $input = $request->all(); // 查看已添加的用户名是否重复 $username = $input['username']; $nameagain = DB::table('adminuser')->where('user_name',$username)->first(); if($nameagain){ $data = 2; return $data; } // 3.添加到数据库user表 $email = $input['email']; $pass = Crypt::encrypt($input['pass']); $status = $input['status']; $res = User::create(['user_name'=>$username,'user_email'=>$email,'user_pass'=>$pass,'status'=>$status]); // 4.根据是否成功,给客户端一个Json格式反馈 if($res){ // $data = [ // 'status'=>'0', // 'message'=>'添加成功' // ]; $data = 0; }else{ // $data = [ // 'status'=>'1', // 'message'=>'添加失败' // ]; $data = 1; } return $data; } /** * 返回单条数据 * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // 1.获取当前用户拥有的所有权限 // $user = User::find(session()->get('user')->user_id); $user = User::find($id); $role = $user->role; // $roles放用户拥有所有角色的name集合 $roles = []; foreach ($role as $r){ $roles[] = $r->role_name; } // $pres放用户拥有所有权限的name集合(可能存在重复权限) $pres = []; foreach ($role as $v){ $ps = $v->permission; foreach ($ps as $p){ $pres[] = $p->pre_name; } } // 2.权限去重 $pres = array_unique($pres); return view('admin.user.show',compact('user','roles','pres')); } /** * 返回修改页面 * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::find($id); return view('admin.user.edit',compact('user')); } /** * 执行修改操作 * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // 1.根据ID获取要修改的记录 $user = User::find($id); // 2.获取要修改的其他信息 $useremail = $request->input('email'); $userpass = $request->input('pass'); $status = $request->input('status'); // 3.修改数据库中相应值 $user->user_email = $useremail; $user->user_pass = Crypt::encrypt($userpass); $user->status = $status; // 给到前台作为修改编辑页面未改动时的原密码展示 // $pass = Crypt::decrypt($user->user_pass); $res = $user->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * 执行删除操作 * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $user = User::find($id); $res1 = 1; $res2 = 1; // if(is_array($id)){ // foreach ($user as $v){ // $res1 = \DB::table('adminuser_role')->where('user_id',$v->user_id)->delete() and $res1; // $res2 = $v->delete() and $res2; // } // }else{ //// if(!empty(\DB::table('adminuser_role')->where('user_id',$user->user_id)->get())){ //// //// } // $res1 = \DB::table('adminuser_role')->where('user_id',$user->user_id)->delete(); // $res2 = $user->delete(); // } $res = \DB::table('adminuser_role')->where('user_id',$user->user_id)->get(); // dd(count($res)); if(count($res)!=0){ $res1 = \DB::table('adminuser_role')->where('user_id',$user->user_id)->delete(); } $res2 = $user->delete(); if($res1 and $res2){ $data = 0; }else{ $data = 1; } return $data; } /** * 执行批量删除操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function delAll(Request $request) { $input = $request->input('ids'); // $user = User::find($input); // dd($input); $res = User::destroy($input); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * 获取用户授权(角色)的页面 * * @param int $id * @return \Illuminate\Http\Response */ public function auth($id) { // 1.获取当前角色 $user = User::find($id); // 2.获取全部角色列表 $role = Role::get(); // 3.获取当前用户所拥有的角色 $user_role = $user->role; // 4.当前角色拥有的权限ID $role_ids = []; foreach ($user_role as $v){ $role_ids[] = $v->role_id; } return view('admin.user.auth',compact('user','role','role_ids')); } /** * 执行用户授权(角色)操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function doAuth(Request $request) { // 1.获取前台参数 $input = $request->except('_token'); // dd($input); // 2.删除adminuser_role表的原有权限 \DB::table('adminuser_role')->where('user_id',$input['user_id'])->delete(); // 3.存入前台勾选的用户权限记录 if(!empty($input['role_id'])){ foreach ($input['role_id'] as $v){ \DB::table('adminuser_role')->insert(['user_id'=>$input['user_id'],'role_id'=>$v]); } } // 重定向是一条路由,用'.'。 return redirect('admin/user'); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //后台模块 //无需中间件配置组 Route::group(['prefix'=>'admin','namespace'=>'Admin'],function(){ //后台登录路由 Route::get('login','LoginController@login'); //后台验证码路由 Route::get('code','LoginController@code'); //处理后台登录的路由 Route::post('dologin','LoginController@doLogin'); //加密路由lock Route::get('encrypt','LoginController@lock'); }); //配置中间件,路由分组 Route::group(['prefix'=>'admin','namespace'=>'Admin','middleware'=>['isLogin','isPermission']],function(){ //后台首页模块路由 Route::get('index','LoginController@index'); //后台欢迎页路由 Route::get('welcome','LoginController@welcome'); //后台用户模块路由 Route::get('user/{id}/auth','UserController@auth'); Route::post('user/doauth','UserController@doAuth'); Route::get('user/del','UserController@delAll'); Route::resource('user','UserController'); //后台角色模块路由 Route::get('role/{id}/auth','RoleController@auth'); Route::post('role/doauth','RoleController@doAuth'); Route::get('role/del','RoleController@delAll'); Route::resource('role','RoleController'); //后台权限模块路由 Route::get('permission/del','PermissionController@delAll'); Route::resource('permission','PermissionController'); }); //中间件IsPermission访问无效提示页面 Route::get('admin/noaccess','Admin\LoginController@noAccess'); //后台退出登录路由 Route::get('admin/logout','Admin\LoginController@logout'); //后台unicode图标参考路由 Route::get('admin/unicode','Admin\LoginController@unicode'); //前台模块 //前台VIP用户模块路由 Route::get('vip/vipUser/del','Vip\VipController@delAll'); Route::resource('vip/vipUser','Vip\VipController'); //前台登录路由 Route::get('vip/login','Vip\LoginController@login'); Route::post('vip/dologin','Vip\LoginController@doLogin'); Route::get('vip/logout','Vip\LoginController@logout'); //前台vip密码找回 Route::get('vip/forget','Vip\RegisterController@forget'); //密码找回处理 Route::post('vip/doforget','Vip\RegisterController@doforget'); //重置密码 Route::get('vip/reset','Vip\RegisterController@reset'); //重置密码处理 Route::post('vip/doreset','Vip\RegisterController@doreset'); //手机号码注册 Route::get('vip/phoneregister','Vip\RegisterController@phoneReg'); //发送手机验证码处理 Route::get('vip/sendcode','Vip\RegisterController@sendCode'); Route::post('vip/dophoneregister','Vip\RegisterController@doPhoneRegister'); ////邮箱注册激活路由 //Route::get('vip/emailregister','Vip\RegisterController@register'); //Route::post('vip/doregister','Vip\RegisterController@doRegister'); //Route::get('vip/active','Vip\RegisterController@active'); //前台首页 Route::get('vip/index','Vip\IndexController@index')->name('index'); Route::get('vip/welcome','Vip\IndexController@welcome'); Route::get('vip/find','Vip\FolderController@findItem'); //前台文件夹路由模块 Route::resource('vip/folder','Vip\FolderController'); //新建文件夹路由 Route::get('vip/folder/{folder}/create','Vip\FolderController@folderCreate'); Route::post('vip/folder/{folder}/store','Vip\FolderController@folderStore'); //移动文件夹路由 Route::get('vip/folder/{folder}/move','Vip\FolderController@folderMove'); Route::put('vip/folder/{folder}/moveUpdate','Vip\FolderController@folderMoveUpdate'); //前台软件路由模块 Route::resource('vip/app','Vip\AppController'); //上传(添加app详细信息及安装教程)软件路由 Route::get('vip/app/{app}/create','Vip\AppController@appCreate'); Route::post('vip/app/store','Vip\AppController@appStore'); Route::post('vip/app/upload','Vip\AppController@upload'); //软件移动 Route::get('vip/app/{folder}/move','Vip\AppController@appMove'); Route::put('vip/app/{folder}/moveUpdate','Vip\AppController@appMoveUpdate'); //软件修改重新上传路由 Route::post('vip/app/{app}/uploadagain','Vip\AppController@uploadAgain'); Route::post('vip/app/{app}/storeagain','Vip\AppController@storeAgain'); //侧边栏软件大类展示路由 Route::get('vip/app/{app}/sortShow','Vip\AppController@asideShow'); <file_sep><?php namespace App\Http\Controllers\Vip; use App\Http\Controllers\Controller; use App\Model\App; use App\Model\Folder; use App\Model\Vip; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use function PHPSTORM_META\type; class FolderController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // 分页显示 // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); $cF_id = 0; // 文件夹部分 $folder = DB::table('folder as a') ->where(function ($q) use($cF_id){ $q->where('folder_parentid','=',$cF_id); }) ->where(function ($q) use($cF_id,$currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',$cF_id); }) ->paginate($request->input('num')?$request->input('num'):15); // 软件部分 // 获取当前目录下所有的app在folder_app中的记录 $appitem = DB::table('folder_app')->where('folder_id',$cF_id)->get(); // 遍历$app $app = []; foreach ($appitem as $v){ $apptemp = App::find($v->app_id); if($apptemp->app_userid == $currentUser->user_id){ $app[] = $apptemp; } } return view('vip.folder.list',compact('folder','request','cF_id','app')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function folderCreate($id) { $folder_id = $id; return view('vip.folder.add',compact('folder_id')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function folderStore(Request $request, $id) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); // 接收前台传来的表单数据 $foldername = $request->input('foldername'); $folderpid = $id; // 对新建文件夹做判重处理 $folder = DB::table('folder as a') ->where(function ($q) use($folderpid){ $q->where('folder_parentid','=',$folderpid); }) ->where(function ($q) use($foldername){ $q->where('folder_name','=',$foldername); }) ->where(function ($q) use($currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',0); })->get(); // $folder = DB::table('folder')->where('folder_name',$foldername)->get(); if(count($folder)!=0){ $data = 2; return $data; } // dd($foldername); // 添加到数据库folder表 $res = Folder::create(['folder_name'=>$foldername, 'folder_parentid'=>$folderpid, 'folder_original'=>1, 'folder_userid'=>$currentUser->user_id]); // 获取新建文件夹的id号码 $currentFid = Folder::where('folder_name',$foldername)->where('folder_parentid',$folderpid)->first(); // dd($currentFid->folder_id); // 添加到数据库vipuser_folder表 \DB::table('vipuser_folder')->insert(['user_id'=>$currentUser->user_id,'folder_id'=>$currentFid->folder_id]); // 根据是否成功,给客户端一个Json格式反馈 if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Find from allWhere. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function findItem(Request $request) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); $name = $request->input('name'); // dd($name); // 文件夹打开部分 $folder = DB::table('folder as a') ->where(function ($q) use($name){ $q->where('folder_name','like','%'.$name.'%'); }) ->where(function ($q) use($currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',0); }) ->paginate($request->input('num')?$request->input('num'):15); // 软件打开部分 $app = DB::table('app as a') ->where(function ($q) use($name){ $q->where('app_name','like','%'.$name.'%'); }) ->where(function ($q) use($currentUser){ $q->where('app_userid','=',$currentUser->user_id); }) ->paginate($request->input('num')?$request->input('num'):15); return view('vip.folder.find',compact('folder', 'request','app')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request, $id) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); // 当前文件夹id,后续传回前台,方便新建文件夹等使用 $cF_id = $id; // 文件夹打开部分 $folder = DB::table('folder as a') ->where(function ($q) use($cF_id){ $q->where('folder_parentid','=',$cF_id); }) ->where(function ($q) use($cF_id,$currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',0); }) ->paginate($request->input('num')?$request->input('num'):15); // 软件打开部分 // 获取当前目录下所有的app在folder_app中的记录 $appitem = DB::table('folder_app')->where('folder_id',$cF_id)->get(); // 遍历$app $app = []; foreach ($appitem as $v){ $apptemp = App::find($v->app_id); if($apptemp->app_userid == $currentUser->user_id){ $app[] = $apptemp; } } return view('vip.folder.list',compact('folder', 'request','cF_id','app')); } /** * move the folder. * * @param int Request $request,$id * @return \Illuminate\Http\Response */ public function folderMove(Request $request, $id) { $folder = Folder::find($id); return view('vip.folder.move',compact('folder')); } /** * moveUpdate the folder. * * @param int Request $request,$id * @return \Illuminate\Http\Response */ public function folderMoveUpdate(Request $request, $id) { // 获取当前登录用户 $currentUser = Vip::find(session()->get('vip')->user_id); $folder = Folder::find($id); $toFolderid = $request->input('toFolderid'); // 1.判断是否为系统文件夹 if(!$folder->folder_original){ $data = 2; return $data; } // 2.判断用户输入的id是否存在且是自己的 $toFolder = DB::table('folder as a') ->where(function ($q) use($toFolderid){ $q->where('folder_id','=',$toFolderid); }) ->where(function ($q) use($currentUser){ $q->orwhere('folder_userid','=',$currentUser->user_id) ->orwhere('folder_userid','=',0); })->get(); // dd(count($toFolder)); // $toFolder = Folder::find($toFolderid); if(!count($toFolder)) { $data = 3; return $data; } // 3.修改数据库中相应值 $folder->folder_parentid = $toFolderid; $res = $folder->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $folder = Folder::find($id); return view('vip.folder.edit',compact('folder')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // 根据ID获取要修改的文件夹original属性 $folder_id = Folder::where('folder_id',$id)->value('folder_original'); if(!$folder_id) { $data = 2; return $data; } // 1.获取所选文件夹记录 $folder = Folder::find($id); // 2.获取要修改的其他信息 $foldername = $request->input('foldername'); // 3.修改数据库中相应值 $folder->folder_name = $foldername; $res = $folder->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // 根据ID获取要删除的文件夹original属性 $folder_id = Folder::where('folder_id',$id)->value('folder_original'); // dd($folder_id); // 判断是否为系统文件夹(系统文件夹不允许删除) if(!$folder_id) { $data = 2; return $data; } $folder = Folder::find($id); $res1 = $folder->delete(); $res2 = DB::table('vipuser_folder')->where('folder_id',$folder->folder_id)->delete(); $appitem = DB::table('folder_app')->where('folder_id',$id)->get(); foreach ($appitem as $v){ DB::table('app')->where('app_id',$v->app_id)->delete(); } DB::table('folder_app')->where('folder_id',$id)->delete(); if($res1 and $res2){ $data = 0; }else{ $data = 1; } return $data; } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class Role extends Model { // 1.关联的数据表 public $table = 'role'; // 2.主键 public $primaryKey = 'role_id'; // 3.允许批量操作的字段 public $guarded = []; // 4.是否维护created_at和update_at字段 public $timestamps = false; // 5.添加动态属性,关联权限模型 public function permission(){ return $this->belongsToMany('App\Model\Permission','role_permission','role_id','pre_id'); } //// 6.添加动态属性,关联用户模型 // public function user(){ // return $this->belongsToMany('App\Model\User','adminuser_role','role_id','user_id'); // } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Model\Permission; use Illuminate\Http\Request; class PermissionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $permission = Permission::orderBy('pre_id','asc') ->where(function ($query) use ($request){ $prename = $request->input('prename'); if(!empty($prename)){ $query->where('pre_name','like','%'.$prename.'%'); } }) ->paginate($request->input('num')?$request->input('num'):10); // $user = User::get(); // $user = User::paginate(2); return view('admin.permission.list',compact('permission','request')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.permission.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // 1.获取表单提交数据 $input = $request->except('_token'); // dd($input); // 2.进行表单验证 // 3.将数据存入role表 $res = Permission::create($input); if($res){ return redirect('admin/permission/create')->with('msg','添加成功'); }else{ return back()->with('msg','添加失败'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $permission = Permission::find($id); return view('admin.permission.edit',compact('permission')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // 1.根据ID获取要修改的记录 $permission = Permission::find($id); // 2.获取要修改的其他信息 $prename = $request->input('pre_name'); $predescription = $request->input('pre_description'); $preurl = $request->input('pre_url'); // 3.修改数据库中相应值 $permission->pre_name = $prename; $permission->pre_description = $predescription; $permission->pre_url = $preurl; $res = $permission->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $permission = Permission::find($id); $res1 = \DB::table('role_permission')->where('pre_id',$permission->pre_id)->delete(); $res2 = $permission->delete(); if($res1 and $res2){ $data = 0; }else{ $data = 1; } return $data; } /** * 执行批量删除操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function delAll(Request $request) { $res = 1; $input = $request->input('ids'); if (!empty($input)){ $res = Permission::destroy($input); } if($res){ $data = 0; }else{ $data = 1; } return $data; } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Model\User; use Illuminate\Http\Request; use App\Org\code\Code; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Crypt; class LoginController extends Controller { //返回后台登录页面 public function login() { return view('admin.login'); } //返回验证码 public function code() { $code = new Code(); return $code->make(); } //处理用户登录方法(后台表单验证) public function doLogin(Request $request) { // 1.接受表单提交的数据 $input = $request->except('_token'); // 2.进行表单验证 // $validator = Validator::make('需要验证的表单数据','验证规则','错误提示信息') $rule = [ 'username'=>'required|between:4,18', 'password'=>'required|between:4,18|alpha_num' ]; $msg = [ 'username.required'=>'请输入用户名', 'username.between'=>'用户名长度要求4-18位之间', 'password.required'=>'请输入密码', 'password.between'=>'密码长度要求4-18位之间', 'password.alpha_num'=>'密码要求包含数字、字母' ]; // 用validator门面进行后台表单验证 $validator = Validator::make($input,$rule,$msg); if ($validator->fails()) { return redirect('admin/login') ->withErrors($validator) ->withInput(); } // 3.验证此用户是否存在(验证码、用户名、密码) if(strtolower($input['code']) != strtolower(session()->get('code'))){ return redirect('admin/login')->with('errors','验证码错误'); } $user = User::where('user_name',$input['username'])->first(); if(!$user){ return redirect('admin/login')->with('errors','用户名错误'); } if (!$user->status){ return redirect('admin/login')->with('errors','该账户未启用'); } if($input['password'] != Crypt::decrypt($user->user_pass)){ return redirect('admin/login')->with('errors','密码错误'); } // 4.保存用户信息到session session()->put('user',$user); // 5.重定向到index return redirect('admin/index'); } //加密算法MD5,Hash(65bit每次生成的都不一样),Encrypted public function lock(){ $str = '123456'; $en_str = '<KEY>'; $crypt_str = Crypt::encrypt($str); return $crypt_str; } //返回后台首页 public function index(){ // 从session中获取当前用户,传回前台 $currentUser = User::find(session()->get('user')->user_id); return view('admin.index',compact('currentUser')); } //返回后台首页中的欢迎页 public function welcome(){ // 从session中获取当前用户,传回前台 $currentUser = User::find(session()->get('user')->user_id); return view('admin.welcome',compact('currentUser')); } //返回后台退出登录页面 public function logout() { // 1.清空session session()->flush(); // 2.重定向到登录页面 return redirect('admin/login'); } //中间件IsPermission控制“用户无相关路由访问权限时提醒”处理 public function noAccess() { // 获取无权错误提醒 return view('tip.noaccess'); } //后台Unicode参考获取 public function unicode() { // 获取unicode参考页面 return view('admin.public.unicode'); } } <file_sep><?php namespace App\Http\Controllers\Vip; use App\Http\Controllers\Controller; use App\Model\Vip; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\DB; class VipController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // 1.获取提取的请求参数 // $input = $request->all(); // dd($input); $vip = Vip::orderBy('user_id','asc') ->where(function ($query) use ($request){ $username = $request->input('username'); if(!empty($username)){ $query->where('user_name','like','%'.$username.'%'); } }) ->paginate($request->input('num')?$request->input('num'):10); return view('vip.vipUser.list',compact('vip','request')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('vip.vipUser.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // 1.接收前台传来的表单数据 $input = $request->all(); // 2.验证电话号码和用户名是否存在 $username = $input['username']; $userphone = $input['phone']; $nameagain = DB::table('vipuser')->where('user_name',$username)->first(); $phoneagain = DB::table('vipuser')->where('user_phone',$userphone)->first(); if($nameagain){ $data = 2; return $data; } if($phoneagain){ $data = 3; return $data; } // 3.添加到数据库user表 $email = $input['email']; $pass = Crypt::encrypt($input['pass']); $res = Vip::create(['user_email'=>$email,'user_pass'=>$pass,'user_name'=>$username,'user_phone'=>$userphone]); // 4.预制文件夹结构 // 通过phone查找vip $vipuser = Vip::where('user_phone',$userphone)->first(); // 获取所有系统自带文件夹 $folder = DB::table('folder')->where('folder_original',0)->get(); // 为用户内置系统文件夹 if(!empty($vipuser) and !empty($folder)){ foreach ($folder as $v){ \DB::table('vipuser_folder')->insert(['user_id'=>$vipuser->user_id,'folder_id'=>$v->folder_id]); } } // 5.根据是否成功,给客户端一个Json格式反馈 if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // 1.获取当前用户拥有的所有权限 // $user = User::find(session()->get('user')->user_id); $user = Vip::find($id); return view('vip.vipUser.show',compact('user')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $vip = Vip::find($id); return view('vip.vipUser.edit',compact('vip')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // 1.根据ID获取要修改的记录 $user = Vip::find($id); // 2.获取要修改的其他信息 $useremail = $request->input('email'); $userpass = $request->input('pass'); // 3.修改数据库中相应值 $user->user_email = $useremail; $user->user_pass = Crypt::encrypt($userpass); // 给到前台作为修改编辑页面未改动时的原密码展示 // $pass = Crypt::decrypt($user->user_pass); $res = $user->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $res = 1; $res1 = 1; $res2 = 1; $res4 = 1; $res5 = 1; // if(is_array($id)){ // //// dd($res); // // foreach ($id as $v){ // // $vip = DB::table('vipuser')->where('user_id',$v)->get(); // // $res = DB::table('vipuser')->where('user_id',$v)->delete() and $res; //// 删除vipuser_folder表的记录 // $res1 = DB::table('vipuser_folder')->where('user_id',$v)->delete() and $res1; //// 判断是否有自定义文件夹并删除folder表的记录 // if(DB::table('folder')->where('folder_userid',$v)) // { // $res2 = DB::table('folder')->where('folder_userid',$v)->delete(); // } //// 判断是否有app并删除对应app和folder_app表里的记录 // $res3 = DB::table('app')->where('app_userid',$v)->get(); // if(!empty($res3)){ //// 删除folder_app表的记录 // foreach ($res3 as $m){ // $res4 = DB::table('folder_app')->where('app_id',$m->app_id)->delete(); // } //// 删除app表的记录 // $res5 = DB::table('app')->where('app_userid',$v)->delete(); // } // } // }else{ $vip = Vip::find($id); // 删除vipuser表的记录 $res = $vip->delete(); // 删除vipuser_folder表的记录 $res1 = DB::table('vipuser_folder')->where('user_id',$vip->user_id)->delete(); // 判断是否有自定义文件夹并删除folder表的记录 if(DB::table('folder')->where('folder_userid',$vip->userid)) { $res2 = DB::table('folder')->where('folder_userid',$vip->user_id)->delete(); } // 判断是否有app并删除对应app和folder_app表里的记录 $res3 = DB::table('app')->where('app_userid',$vip->user_id)->get(); if(!empty($res3)){ // 删除folder_app表的记录 foreach ($res3 as $v){ $res4 = DB::table('folder_app')->where('app_id',$v->app_id)->delete(); } // 删除app表的记录 $res5 = DB::table('app')->where('app_userid',$vip->user_id)->delete(); } // } if($res and $res1){ $data = 0; }else{ $data = 1; } return $data; } /** * 执行批量删除操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function delAll(Request $request) { $input = $request->input('ids'); $res = 1; if(is_array($input)){ foreach ($input as $v){ $res = Vip::destroy($v) and $res; } }else{ $res = Vip::destroy($input); } if($res){ $data = 0; }else{ $data = 1; } return $data; } } <file_sep><?php namespace App\Http\Controllers\Vip; use App\Model\Folder; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Sms\SendTemplateSMS; use App\Sms\M3Result; use Illuminate\Support\Facades\Crypt; use App\Model\Vip; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; class RegisterController extends Controller { //手机注册页面 public function phoneReg() { return view('vip.phoneregister'); } //发送手机验证码 public function sendCode(Request $request) { // 1. 获取要发送的手机号 $phone = $request->phone; // 2.在数据库中查找此号码是否已注册 $phoneagain = DB::table('vipuser')->where('user_phone',$phone)->first(); if ($phoneagain){ $data = 2; return $data; } // 3.生成模板中需要的参数 ,验证码和时间 $code = rand(1000,9999); $arr = [$code,5]; // 4.调用容联云通讯的接口 $templateSMS = new SendTemplateSMS(); // $M3result = new M3Result(); $M3result = $templateSMS->sendTemplateSMS($phone,$arr,1); // 5.将验证码存入session session()->put('phone',$code); // 6.给前台返回容联云通讯的响应结果 return $M3result->status; } // 手机号注册处理 public function doPhoneRegister(Request $request) { $input = $request->except('_token'); // 在vipuser表查找输入的用户名是否重复 $vipname = $input['username']; $nameagain = DB::table('vipuser')->where('user_name',$vipname)->first(); if ($nameagain){ return redirect('vip/phoneregister')->with('errors','已有此用户名存在,请更换后重新注册'); } // 如果未填验证码或者验证码不对 if(session()->get('phone') != $input['code']){ return redirect('vip/phoneregister')->with('errors','信息填写有误,请重新填写'); } $input['user_pass'] = Crypt::encrypt($input['user_pass']); // $input['expire'] = time()+3600*24; $user = Vip::create(['user_name'=>$input['username'],'user_phone'=>$input['phone'],'user_pass'=>$input['user_pass'],'user_email'=>$input['email']]); if($user){ // 预制文件夹结构 再重定向 // 通过phone查找vip $vipuser = Vip::where('user_phone',$input['phone'])->first(); // 获取所有系统自带文件夹 $folder = DB::table('folder')->where('folder_original',0)->get(); // 为用户内置系统文件夹 if(!empty($vipuser) and !empty($folder)){ foreach ($folder as $v){ \DB::table('vipuser_folder')->insert(['user_id'=>$vipuser->user_id,'folder_id'=>$v->folder_id]); } } return redirect('vip/login')->with('errors','恭喜您,注册成功'); }else{ return back(); } } // //前台邮箱注册页 // public function register() // { // return view('vip.emailregister'); // } // // // 邮箱登录处理 // public function doRegister(Request $request) // { // $input = $request->except('_token'); //// dd($input); // $input['user_pass'] = Crypt::encrypt($input['user_pass']); // $input['token'] = md5($input['user_email'].$input['user_pass'].'123'); // $input['expire'] = time()+3600*24; // // $user = Vip::create($input); // // if($user){ // Mail::send('vip.email.active',['user'=>$user],function ($m) use ($user) { // $m->to($user->user_email, $user->user_name)->subject('激活邮箱'); // }); // return redirect('vip/login')->with('active','请先登录邮箱激活账号'); // }else{ // return redirect('vip/emailregister'); // } // } // // //注册账号邮箱激活 // public function active(Request $request){ // //找到要激活的用户,将用户的active字段改成1 // // $user = Vip::findOrFail($request->userid); // // //验证token的有效性,保证链接是通过邮箱中的激活链接发送的 // if($request->token != $user->token){ // return '当前链接非有效链接,请确保您是通过邮箱的激活链接来激活的'; // } // //激活时间是否已经超时 // if(time() > $user->expire){ // return '激活链接已经超时,请重新注册'; // } // // $res = $user->update(['active'=>1]); // //激活成功,跳转到登录页 // if($res){ // return redirect('vip/login')->with('msg','账号激活成功'); // }else{ // return '邮箱激活失败,请检查激活链接,或者重新注册账号'; // } // } // 忘记密码 public function forget() { return view('vip.forget'); } //密码找回处理(发送密码找回邮件) public function doforget(Request $request) { //要发送邮件的账号 $username = $request->username; // 根据账号名查询用户信息 $user = Vip::where('user_name',$username)->first(); if($user){ //想此用户发送密码找回邮件 Mail::send('vip.email.forget',['user'=>$user],function ($m) use ($user) { $m->to($user->user_email, $user->user_name)->subject('找回密码'); }); return redirect('vip/login')->with('active','发送成功,请先登录邮箱重置密码'); }else{ return back()->with('active','用户不存在,请重新输入要找回密码的账号'); } } //重新设置密码页面 public function reset(Request $request) { $input = $request->all(); //验证token,判断是否是通过重置密码邮件跳转过来的 $user = Vip::find($input['uid']); return view('vip.reset',compact('user')); } //重置密码逻辑 public function doreset(Request $request) { // 1. 接收要重置密码的账号、新密码 $input = $request->all(); $pass = Crypt::encrypt($input['user_pass']); // 2.将此账号的密码重置为新密码 $res = Vip::where('user_name',$input['user_name'])->update(['user_pass'=>$pass]); // 3. 判断更新是否成功 if($res){ return redirect('vip/login')->with('errors','密码重置成功'); }else{ return redirect('vip/reset')->with('errors','密码重置失败,请重试'); } } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class App extends Model { // 1.关联的数据表 public $table = 'app'; // 2.主键 public $primaryKey = 'app_id'; // 3.允许批量操作的字段 public $guarded = []; // 4.是否维护created_at和update_at字段 public $timestamps = false; } <file_sep><?php namespace App\Http\Controllers\Vip; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Model\Vip; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Validator; //use Illuminate\Support\Facades\Input; class LoginController extends Controller { // 获取前台会员登录页面 public function login(){ return view('vip.login'); } // 处理前台登录逻辑 public function dologin(Request $request){ $input = $request->except('_token','wp-submit'); // dd($input); $username = $input['user_name']; $password = $input['<PASSWORD>']; // $token = md5(uniqid(rand(), TRUE)); $timeout = time() + 60*60*24*7; if(isset($input['rememberme'])){ setcookie('username', "$username", $timeout); setcookie('password', "$<PASSWORD>", $timeout); }else{ setcookie('username', "", time()-1); setcookie('password', "",time()-1); } // 3. 验证用户是否存在 $user = Vip::where('user_name',$input['user_name'])->first(); if(empty($user)){ return redirect('vip/login')->with('errors','用户名不存在'); } // 4. 密码是否正确 if($input['user_pass'] != Crypt::decrypt($user->user_pass) ){ return redirect('vip/login')->with('errors','密码错误'); } //如果登录成功,将登录用户信息保存到session中 session()->put('vip',$user); return redirect('vip/index'); } // 退出登录 public function logout(){ // 1.清空session session()->flush(); // 2.重定向到登录页面 return redirect('vip/login'); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Model\Permission; use App\Model\Role; use Illuminate\Http\Request; class RoleController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // 不分页显示 // //1.获取角色列表数据 // $role = Role::get(); //// 2.返回角色视图 // return view('admin.role.list',compact('role')); // 分页显示 // 1.获取提取的请求参数 // $input = $request->all(); // dd($input); $role = Role::orderBy('role_id','asc') ->where(function ($query) use ($request){ $rolename = $request->input('rolename'); if(!empty($rolename)){ $query->where('role_name','like','%'.$rolename.'%'); } }) ->paginate($request->input('num')?$request->input('num'):10); // $user = User::get(); // $user = User::paginate(2); return view('admin.role.list',compact('role','request')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.role.add'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // 1.获取表单提交数据 $input = $request->except('_token'); // dd($input); // 2.进行表单验证 // 3.将数据存入role表 $res = Role::create($input); if($res){ return redirect('admin/role/create')->with('msg','添加成功'); }else{ return back()->with('msg','添加失败'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $role = Role::find($id); return view('admin.role.edit',compact('role')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // 1.根据ID获取要修改的记录 $role = Role::find($id); // 2.获取要修改的其他信息 $rolename = $request->input('rolename'); $roledescription = $request->input('roledescription'); // 3.修改数据库中相应值 $role->role_name = $rolename; $role->role_description = $roledescription; $res = $role->save(); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $role = Role::find($id); // $res1 = 1; // $res2 = 1; // if(is_array($role)){ // foreach ($role->role_id as $v){ // $res1 = \DB::table('role_permission')->where('role_id',$v)->delete(); // } // } $res1 = \DB::table('role_permission')->where('role_id',$role->role_id)->delete(); $res2 = \DB::table('adminuser_role')->where('role_id',$role->role_id)->delete(); $res3 = $role->delete(); if($res1 and $res2 and $res3){ $data = 0; }else{ $data = 1; } return $data; } /** * 执行批量删除操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function delAll(Request $request) { $input = $request->input('ids'); $res = Role::destroy($input); if($res){ $data = 0; }else{ $data = 1; } return $data; } /** * 获取角色授权的页面 * * @param int $id * @return \Illuminate\Http\Response */ public function auth($id) { // 1.获取当前角色 $role = Role::find($id); // 2.获取全部权限列表 $pre = Permission::get(); // 3.获取当前角色所拥有的权限 $role_pre = $role->permission; // 4.当前角色拥有的权限ID $pre_ids = []; foreach ($role_pre as $v){ $pre_ids[] = $v->pre_id; } return view('admin.role.auth',compact('role','pre','pre_ids')); } /** * 执行角色授权操作 * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function doAuth(Request $request) { // 1.获取前台参数 $input = $request->except('_token'); // dd($input); // 2.删除role_permission表的原有权限 \DB::table('role_permission')->where('role_id',$input['role_id'])->delete(); // 3.存入前台勾选的角色权限记录 if(!empty($input['pre_id'])){ foreach ($input['pre_id'] as $v){ \DB::table('role_permission')->insert(['role_id'=>$input['role_id'],'pre_id'=>$v]); } } // 重定向是一条路由,用'.'。 return redirect('admin/role'); } } <file_sep><?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class Permission extends Model { // 1.关联的数据表 public $table = 'permission'; // 2.主键 public $primaryKey = 'pre_id'; // 3.允许批量操作的字段 public $guarded = []; // 4.是否维护created_at和update_at字段 public $timestamps = false; //// 5.添加动态属性,关联角色模型 // public function role(){ // return $this->belongsToMany('App\Model\Role','role_permission','pre_id','role_id'); // } }
7091a419934176eef30e49ccdd41a882fa0d704e
[ "PHP" ]
15
PHP
liushige/netdisk
e62522898fb67123dae5015f22366cee21809335
5f002109a75212f57ea5738683120054357b9fdc
refs/heads/master
<repo_name>simontye/2019_beaver<file_sep>/2019_beaver.R ############################################################### # North American Beaver Lodge # 20191026 # SPT ############################################################### # Clear memory rm(list=ls()) # Load packages library(ggplot2) library(ggthemes) library(pastecs) library(scales) library(activity) library(gtable) library(grid) library(circular) library(Hmisc) library(corrgram) library(vegan) library(devtools) library(ggpmisc) library(reshape) library(data.table) library(tidyr) library(lubridate) library(plyr) library(dplyr) library(esquisse) library(zoo) library(naniar) library(stringr) library(insol) library(aspace) library(lazyeval) library(iNEXT) library(plotrix) library(maptools) library(purrr) library(PMCMRplus) # Set working drive setwd("/Users/simontye/Documents/Research/Projects/Castor_canadensis/2019_Beaver") # Load files beaver <- read.csv("Tye_Beaver.csv") weather <- read.csv("Tye_Weather.csv") # Reformat dates beaver$Date <- as.Date(beaver$Date, "%m/%d/%y") weather$Date <- as.Date(weather$Date, "%m/%d/%y") # Group beavers age classes beaver$Beaver <- (beaver$Beaver_Male + beaver$Beaver_Female + beaver$Beaver_Unknown + beaver$Beaver_Kit) # Reformat columns for date and number of images date <- table(beaver$Date) date <- as.data.frame.table(date) colnames(date)[c(1,2)] <- c("Date", "Images") date$Date <- as.Date(date$Date, "%Y-%m-%d") beaver <- join(beaver, date, by = 'Date') # 1) To see all vertebrate observations, keep this portion exlcluded (#), # then run the code to line 133, which produces a species list # 2) To run the full analysis with days w/ less than 75% of images # (> 108 out of the 144 possible), remove the # and run the code. # Remove days with less than 75% of expected images (>108) beaver <- subset(beaver, Images > 108) # Add missing dates beaver <- complete(data = beaver, Date = seq.Date(min(Date), max(Date), by = "day")) # Add column for missing dates beaver <- add_label_missings(data = beaver, Beaver, missing = "-1", complete = "NA") beaver$any_missing <- as.numeric(as.character(beaver$any_missing)) beaver$Missing_Data <- beaver$any_missing # Combine beaver and weather dataframes beaver <- merge(beaver, weather) # Remove unnecessary dataframes rm(weather, date) # Add ID column for image number beaver <- beaver %>% mutate(ID = row_number()) # Add week column to main beaverframe beaver$Week <- strftime(beaver$Date, format = "%U") # Remove Lodge_Condition column beaver[,c("Filename", "Beaver_Male", "Beaver_Female", "Beaver_Unknown", "Beaver_Kit", "Animal", "Amphibian", "Bird", "Mammal", "Reptile", "Lake_Frozen", "Lodge_Condition", "Pond_Condition", "Precip", "Discharge", "Height", "Temp", "Missing_Data", "Hour", "Week", "Maintenance", "Maintenance_1", "Maintenance_1V", "Maintenance_1H", "Maintenance_2", "Maintenance_2V", "Maintenance_2H", "Maintenance_3", "Maintenance_3V", "Maintenance_3H")] <- NULL ################################################### ################################################### ################################################### # Subset beaver dataframe by lodge materials beaver1 <- subset(beaver, select = c(ID, Date, Month, Time, Images, Animal_1, Animal_1_Count)) beaver2 <- subset(beaver, select = c(ID, Date, Month, Time, Images, Animal_2, Animal_2_Count)) beaver3 <- subset(beaver, select = c(ID, Date, Month, Time, Images, Animal_3, Animal_3_Count)) beaver4 <- subset(beaver, select = c(ID, Date, Month, Time, Images, Beaver_Count)) # Avoid tripiling of observations when joining by creating dummy columns with 0s beaver1$Beaver_Count <- rep(0) beaver2$Beaver_Count <- rep(0) beaver3$Beaver_Count <- rep(0) beaver4$Animal <- rep(0) beaver4$Animal_Count <- rep(0) # Rename columns so dataframes can be merged colnames(beaver1)[c(6:8)] <- c("Animal", "Animal_Count", "Beaver") colnames(beaver2)[c(6:8)] <- c("Animal", "Animal_Count", "Beaver") colnames(beaver3)[c(6:8)] <- c("Animal", "Animal_Count", "Beaver") colnames(beaver4)[c(6:8)] <- c("Beaver", "Animal", "Animal_Count") # Merge dataframes beaver <- rbind(beaver1, beaver2, beaver3, beaver4) # Remove unnecessary dataframes rm(beaver1, beaver2, beaver3, beaver4) # Species list names(table(beaver$Animal)) # Separate organism and species into different columns (Note: warning is due to "Unknown" organisms as no species name is available) beaver <- separate(data = beaver, col = "Animal", into = c("Organism", "Species"), sep = "_") # Create column for each species (w/o Animal_Count taken into account for observation calculations) beaver$AmericanBullfrog <- ifelse(beaver$Species == "AmericanBullfrog" & beaver$Animal_Count > 0, 1, 0) beaver$AmericanCoot <- ifelse(beaver$Species == "AmericanCoot" & beaver$Animal_Count > 0, 1, 0) beaver$BeltedKingfisher <- ifelse(beaver$Species == "BeltedKingfisher" & beaver$Animal_Count > 0, 1, 0) beaver$BlackCrownedNightHeron <- ifelse(beaver$Species == "BlackCrownedNightHeron" & beaver$Animal_Count > 0, 1, 0) beaver$BlueWingedTeal <- ifelse(beaver$Species == "BlueWingedTeal" & beaver$Animal_Count > 0, 1, 0) beaver$CanadaGoose <- ifelse(beaver$Species == "CanadaGoose" & beaver$Animal_Count > 0, 1, 0) beaver$CattleEgret <- ifelse(beaver$Species == "CattleEgret" & beaver$Animal_Count > 0, 1, 0) beaver$CommonGrackle <- ifelse(beaver$Species == "Grackle" & beaver$Animal_Count > 0, 1, 0) beaver$EasternKingbird <- ifelse(beaver$Species == "EasternKingbird" & beaver$Animal_Count > 0, 1, 0) beaver$EuropeanStarling <- ifelse(beaver$Species == "EuropeanStarling" & beaver$Animal_Count > 0, 1, 0) beaver$GreatBlueHeron <- ifelse(beaver$Species == "GreatBlueHeron" & beaver$Animal_Count > 0, 1, 0) beaver$GreatHornedOwl <- ifelse(beaver$Species == "GreatHornedOwl" & beaver$Animal_Count > 0, 1, 0) beaver$GreenHeron <- ifelse(beaver$Species == "GreenHeron" & beaver$Animal_Count > 0, 1, 0) beaver$LittleBlueHeron <- ifelse(beaver$Species == "LittleBlueHeron" & beaver$Animal_Count > 0, 1, 0) beaver$Meadowlark <- ifelse(beaver$Species == "Meadowlark" & beaver$Animal_Count > 0, 1, 0) beaver$NorthernHarrier <- ifelse(beaver$Species == "NorthernHarrier" & beaver$Animal_Count > 0, 1, 0) beaver$RedTailedHawk <- ifelse(beaver$Species == "RedTailedHawk" & beaver$Animal_Count > 0, 1, 0) beaver$RedWingedBlackbird <- ifelse(beaver$Species == "RedWingedBlackbird" & beaver$Animal_Count > 0, 1, 0) beaver$SnowyEgret <- ifelse(beaver$Species == "SnowyEgret" & beaver$Animal_Count > 0, 1, 0) beaver$WoodDuck <- ifelse(beaver$Species == "WoodDuck" & beaver$Animal_Count > 0, 1, 0) beaver$YellowCrownedNightHeron <- ifelse(beaver$Species == "YellowCrownedNightHeron" & beaver$Animal_Count > 0, 1, 0) beaver$YellowHeadedBlackbird <- ifelse(beaver$Species == "YellowHeadedBlackbird" & beaver$Animal_Count > 0, 1, 0) beaver$YellowWarbler <- ifelse(beaver$Species == "YellowWarbler" & beaver$Animal_Count > 0, 1, 0) beaver$Muskrat <- ifelse(beaver$Species == "Muskrat" & beaver$Animal_Count > 0, 1, 0) beaver$NorthernRiverOtter <- ifelse(beaver$Species == "NorthernRiverOtter" & beaver$Animal_Count > 0, 1, 0) beaver$Raccoon <- ifelse(beaver$Species == "Raccoon" & beaver$Animal_Count > 0, 1, 0) beaver$Small <- ifelse(beaver$Species == "Small" & beaver$Animal_Count > 0, 1, 0) beaver$PaintedTurtle <- ifelse(beaver$Species == "PaintedTurtle" & beaver$Animal_Count > 0, 1, 0) # Replace NAs with 0s beaver[is.na(beaver)] <- 0 # Calculate number of observations for each species sum(beaver$AmericanBullfrog) sum(beaver$AmericanCoot) sum(beaver$BeltedKingfisher) sum(beaver$BlackCrownedNightHeron) sum(beaver$BlueWingedTeal) sum(beaver$CanadaGoose) sum(beaver$CattleEgret) sum(beaver$CommonGrackle) sum(beaver$EasternKingbird) sum(beaver$EuropeanStarling) sum(beaver$GreatBlueHeron) sum(beaver$GreatHornedOwl) sum(beaver$GreenHeron) sum(beaver$LittleBlueHeron) sum(beaver$Meadowlark) sum(beaver$NorthernHarrier) sum(beaver$RedTailedHawk) sum(beaver$RedWingedBlackbird) sum(beaver$SnowyEgret) sum(beaver$WoodDuck) sum(beaver$YellowCrownedNightHeron) sum(beaver$YellowHeadedBlackbird) sum(beaver$YellowWarbler) sum(beaver$Muskrat) sum(beaver$Beaver) sum(beaver$NorthernRiverOtter) sum(beaver$Raccoon) sum(beaver$Small) sum(beaver$PaintedTurtle) # Add organism columns by 1) merging data from Organism_Species separation and 2) remove "Unknown" observations beaver$Amphibian <- ifelse(beaver$Organism == "Amphibian", 1, 0) beaver$Bird <- ifelse(beaver$Organism == "Bird", 1, 0) beaver$Mammal <- ifelse(beaver$Organism == "Mammal", 1, 0) beaver$Reptile <- ifelse(beaver$Organism == "Reptile", 1, 0) beaver$Beaver <- ifelse(beaver$Beaver > 0, 1, 0) beaver$Organism <- ifelse(beaver$Organism == "Unknown", 0, beaver$Organism) beaver$Count <- ifelse(beaver$Amphibian == 1, 1, ifelse(beaver$Bird == 1, 1, ifelse(beaver$Mammal == 1, 1, ifelse(beaver$Reptile == 1, 1, ifelse(beaver$Beaver == 1, 1, 0))))) # Calculate number of observations for each organism sum(beaver$Amphibian) sum(beaver$Bird) sum(beaver$Mammal) sum(beaver$Reptile) sum(beaver$Beaver) # Remove unnecessary columns beaver[,c("Animal_Count")] <- NULL # Change data type of columns beaver$Beaver <- as.numeric(beaver$Beaver) # Summarize data by beaver$Date beaver.day <- beaver %>% group_by(Date) %>% summarize( Month = mean(Month), Images = mean(Images), AmericanBullfrog = (sum(AmericanBullfrog) / mean(Images)) * 100, AmericanCoot = (sum(AmericanCoot) / mean(Images)) * 100, BeltedKingfisher = (sum(BeltedKingfisher) / mean(Images)) * 100, BlackCrownedNightHeron = (sum(BlackCrownedNightHeron) / mean(Images)) * 100, BlueWingedTeal = (sum(BlueWingedTeal) / mean(Images)) * 100, CanadaGoose = (sum(CanadaGoose) / mean(Images)) * 100, CattleEgret = (sum(CattleEgret) / mean(Images)) * 100, CommonGrackle = (sum(CommonGrackle) / mean(Images)) * 100, EasternKingbird = (sum(EasternKingbird) / mean(Images)) * 100, EuropeanStarling = (sum(EuropeanStarling) / mean(Images)) * 100, GreatBlueHeron = (sum(GreatBlueHeron) / mean(Images)) * 100, GreatHornedOwl = (sum(GreatHornedOwl) / mean(Images)) * 100, GreenHeron = (sum(GreenHeron) / mean(Images)) * 100, LittleBlueHeron = (sum(LittleBlueHeron) / mean(Images)) * 100, Meadowlark = (sum(Meadowlark) / mean(Images)) * 100, NorthernHarrier = (sum(NorthernHarrier) / mean(Images)) * 100, RedTailedHawk = (sum(RedTailedHawk) / mean(Images)) * 100, RedWingedBlackbird = (sum(RedWingedBlackbird) / mean(Images)) * 100, SnowyEgret = (sum(SnowyEgret) / mean(Images)) * 100, WoodDuck = (sum(WoodDuck) / mean(Images)) * 100, YellowCrownedNightHeron = (sum(YellowCrownedNightHeron) / mean(Images)) * 100, YellowHeadedBlackbird = (sum(YellowHeadedBlackbird) / mean(Images)) * 100, YellowWarbler = (sum(YellowWarbler) / mean(Images)) * 100, Muskrat = (sum(Muskrat) / mean(Images)) * 100, NorthernRiverOtter = (sum(NorthernRiverOtter) / mean(Images)) * 100, Raccoon = (sum(Raccoon) / mean(Images)) * 100, Small = (sum(Small) / mean(Images)) * 100, PaintedTurtle = (sum(PaintedTurtle) / mean(Images)) * 100, Amphibian = (sum(Amphibian) / mean(Images)) * 100, Beaver = (sum(Beaver) / mean(Images)) * 100, Bird = (sum(Bird) / mean(Images)) * 100, Mammal = (sum(Mammal) / mean(Images)) * 100, Reptile = (sum(Reptile) / mean(Images)) * 100) # Summarize data by beaver$Month beaver.month <- beaver.day %>% group_by(Month) %>% summarize( Beaver = (sum(Beaver) / sum(Images)) * 100, Amphibian = (sum(Amphibian) / sum(Images)) * 100, Bird = (sum(Bird) / sum(Images)) * 100, Mammal = (sum(Mammal) / sum(Images)) * 100, Reptile = (sum(Reptile) / sum(Images)) * 100) # Stacked beaver and organism observations by month for annual activity figure beaver.stacked <- stack(beaver.month, select=c("Beaver", "Amphibian", "Bird", "Mammal", "Reptile")) # Rename months beaver.stacked$Month <- rep(1:10, 5) beaver.stacked$Month <- ifelse(beaver.stacked$Month == 10, 12, beaver.stacked$Month) # Rename columns colnames(beaver.stacked)[1:2] <- c("Percent", "Organism") # Reorder months in study period beaver.day$Month <- factor(beaver.day$Month, levels = c("12", "1", "2", "3", "4", "5", "6", "7", "8", "9")) beaver.month$Month <- factor(beaver.month$Month, levels = c("12", "1", "2", "3", "4", "5", "6", "7", "8", "9")) beaver.stacked$Month <- factor(beaver.stacked$Month, levels = c("12", "1", "2", "3", "4", "5", "6", "7", "8", "9")) # Reorder organisms so they stack inversely (Beaver, Amphibian, etc.) beaver.stacked$Organism <- factor(beaver.stacked$Organism, levels = c("Reptile", "Mammal", "Bird", "Amphibian", "Beaver")) # Create vector of color values (same colors from clock figure made in Illustrator) Colors <- c("#b1d689", "#ffa017", "#99c3e8", "#ffe045", "#a18167") ############################################################### ### Animal Activity - Figures ############################################################### ############################################################### ### Annual activity patterns as a stacked bar graph (combined with figure of daily activity patterns in Illustrator) ggplot(data = beaver.stacked, aes(x = Month, y = Percent, fill = Organism)) + geom_bar(position = "stack", stat = "identity", color = "black", size = .25) + scale_y_continuous(breaks=c(0, 5, 10, 15, 20), limits = c(0, 20)) + scale_fill_manual(values = Colors) + theme_bw(base_size = 30) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "Month",y = "Percent of images") ############################################################### ### Annual activity pattern for each organism as separate bar graphs and vertically stacked # Beavers annual.beaver <- ggplot(data = beaver.month, aes(x = Month)) + geom_bar(aes(y = Beaver), position = "dodge", stat = "identity", fill = "#a18167", size = 0.8) + scale_y_continuous(breaks=c(0, 5, 10, 15), limits = c(0, 15)) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "",y = "") # Amphibians annual.amphibian <- ggplot(data = beaver.month, aes(x = Month)) + geom_bar(aes(y = Amphibian), position = "dodge", stat = "identity", fill = "#fff22e", size = 0.8) + scale_y_continuous(breaks=c(0, 5, 10, 15), limits = c(0, 15)) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "",y = "") # Birds annual.bird <- ggplot(data = beaver.month, aes(x = Month)) + geom_bar(aes(y = Bird), position = "dodge", stat = "identity", fill = "#99c3e8", size = 0.8) + scale_y_continuous(breaks=c(0, 5, 10, 15), limits = c(0, 15)) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "",y = "Percent of images") # Mammals annual.mammal <- ggplot(data = beaver.month, aes(x = Month)) + geom_bar(aes(y = Mammal), position = "dodge", stat = "identity", fill = "#ffa017", size = 0.8) + scale_y_continuous(breaks=c(0, 5, 10, 15), limits = c(0, 15)) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "",y = "") # Reptiles annual.reptile <- ggplot(data = beaver.month, aes(x = Month)) + geom_bar(aes(y = Reptile), position = "dodge", stat = "identity", fill = "#b1d689", size = 0.8) + scale_y_continuous(breaks=c(0, 5, 10, 5), limits = c(0, 15)) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 20, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 20))) + labs(x = "Month",y = "") # Combine and align plots (7x16 in) annual.beaver2 <- ggplotGrob(annual.beaver) annual.amphibian2 <- ggplotGrob(annual.amphibian) annual.bird2 <- ggplotGrob(annual.bird) annual.mammal2 <- ggplotGrob(annual.mammal) annual.reptile2 <- ggplotGrob(annual.reptile) annual.all <- rbind(annual.beaver2, annual.amphibian2, annual.bird2, annual.mammal2, annual.reptile2, size = "first") annual.all$widths <- unit.pmax(annual.beaver2$widths, annual.amphibian2$widths, annual.bird2$widths, annual.mammal2$widths, annual.reptile2$widths) grid.newpage() grid.draw(annual.all) ############################################################### ### Daily activity - Clock figure ############################################################### # Add Julian days to animals.day beaver$Date <- as.POSIXct(beaver$Date, format="%Y-%m-%d") beaver$Julian <- JD(beaver$Date, inverse = FALSE) beaver$Julian <- (beaver$Julian - 2457358.5) # Convert Julian days to degrees beaver$Degrees <- (beaver$Julian/366)*360 # Convery degrees to radians beaver$Radians <- as_radians(beaver$Degrees) ############################################################### # Beavers beaver.radians <- subset(beaver, select = c(Beaver, Radians)) beaver.radians$Radians <- ifelse(beaver.radians$Beaver > 0, beaver.radians$Radians, NA) beaver.radians <- na.omit(beaver.radians) beaver.radians <- as.data.frame(beaver.radians$Radians) beaver.radians <- circular(beaver.radians, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") ### MJ: The "pdf..." and "dev.off" lines are blocked off (#). ### Activating these lines creates and exports PDFs of the figures. ### The clocks are disporotional in RStudio but are normal once ### exported as 12 x 12 in. PDF #pdf("annual_beavers.pdf", width = 12, height = 12) plot.circular(beaver.radians, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(beaver.radians, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(beaver.radians, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Amphibians amphibians.radians <- subset(beaver, select = c(Amphibian, Radians)) amphibians.radians$Radians <- ifelse(amphibians.radians$Amphibian > 0, amphibians.radians$Radians, NA) amphibians.radians <- na.omit(amphibians.radians) amphibians.radians <- as.data.frame(amphibians.radians$Radians) amphibians.radians <- circular(amphibians.radians, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("annual_amphibians.pdf", width = 12, height = 12) plot.circular(amphibians.radians, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(amphibians.radians, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(amphibians.radians, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Birds birds.radians <- subset(beaver, select = c(Bird, Radians)) birds.radians$Radians <- ifelse(birds.radians$Bird > 0, birds.radians$Radians, NA) birds.radians <- na.omit(birds.radians) birds.radians <- as.data.frame(birds.radians$Radians) birds.radians <- circular(birds.radians, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("annual_birds.pdf", width = 12, height = 12) plot.circular(birds.radians, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(birds.radians, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(birds.radians, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Mammals mammals.radians <- subset(beaver, select = c(Mammal, Radians)) mammals.radians$Radians <- ifelse(mammals.radians$Mammal > 0, mammals.radians$Radians, NA) mammals.radians <- na.omit(mammals.radians) mammals.radians <- as.data.frame(mammals.radians$Radians) mammals.radians <- circular(mammals.radians, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("annual_mammals.pdf", width = 12, height = 12) plot.circular(mammals.radians, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(mammals.radians, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(mammals.radians, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Reptiles reptiles.radians <- subset(beaver, select = c(Reptile, Radians)) reptiles.radians$Radians <- ifelse(reptiles.radians$Reptile > 0, reptiles.radians$Radians, NA) reptiles.radians <- na.omit(reptiles.radians) reptiles.radians <- as.data.frame(reptiles.radians$Radians) reptiles.radians <- circular(reptiles.radians, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("annual_reptiles.pdf", width = 12, height = 12) plot.circular(reptiles.radians, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(reptiles.radians, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(reptiles.radians, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### ### Annual activity - Clock figure ############################################################### # Convert time of day to radians beaver.hour <- subset(beaver, select = c(Time, Beaver, Amphibian, Bird, Mammal, Reptile)) beaver.hour$Time <- as.POSIXct(beaver.hour$Time, format="%H:%M:%S", units = "mins") beaver.hour$Time <- strptime(beaver.hour$Time, "%Y-%m-%d %H:%M:%S") beaver.hour$Time <- ymd_hms(beaver.hour$Time) beaver.hour$Time <- as.numeric(format(beaver.hour$Time, "%H")) + (as.numeric(format(beaver.hour$Time, "%M")) / 60) beaver.hour$Time <- (beaver.hour$Time * 60 / 229.1831180523) # Rename Time to Radians (so very similar code works for both clocks) colnames(beaver.hour)[c(1)] <- c("Radians") ############################################################### # Beavers beaver.radians2 <- subset(beaver.hour, select = c(Beaver, Radians)) beaver.radians2$Radians <- ifelse(beaver.radians2$Beaver > 0, beaver.radians2$Radians, NA) beaver.radians2 <- na.omit(beaver.radians2) beaver.radians2 <- as.data.frame(beaver.radians2$Radians) beaver.radians2 <- circular(beaver.radians2, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("daily_beavers.pdf", width = 12, height = 12) plot.circular(beaver.radians2, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(beaver.radians2, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(beaver.radians2, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Amphibians amphibians.radians2 <- subset(beaver.hour, select = c(Amphibian, Radians)) amphibians.radians2$Radians <- ifelse(amphibians.radians2$Amphibian > 0, amphibians.radians2$Radians, NA) amphibians.radians2 <- na.omit(amphibians.radians2) amphibians.radians2 <- as.data.frame(amphibians.radians2$Radians) amphibians.radians2 <- circular(amphibians.radians2, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("daily_amphibians.pdf", width = 12, height = 12) plot.circular(amphibians.radians2, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(amphibians.radians2, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(amphibians.radians2, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Birds birds.radians2 <- subset(beaver.hour, select = c(Bird, Radians)) birds.radians2$Radians <- ifelse(birds.radians2$Bird > 0, birds.radians2$Radians, NA) birds.radians2 <- na.omit(birds.radians2) birds.radians2 <- as.data.frame(birds.radians2$Radians) birds.radians2 <- circular(birds.radians2, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") pdf("daily_birds.pdf", width = 12, height = 12) plot.circular(birds.radians2, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(birds.radians2, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(birds.radians2, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Mammals mammals.radians2 <- subset(beaver.hour, select = c(Mammal, Radians)) mammals.radians2$Radians <- ifelse(mammals.radians2$Mammal > 0, mammals.radians2$Radians, NA) mammals.radians2 <- na.omit(mammals.radians2) mammals.radians2 <- as.data.frame(mammals.radians2$Radians) mammals.radians2 <- circular(mammals.radians2, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("daily_mammals.pdf", width = 12, height = 12) plot.circular(mammals.radians2, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(mammals.radians2, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(mammals.radians2, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### # Reptiles reptiles.radians2 <- subset(beaver.hour, select = c(Reptile, Radians)) reptiles.radians2$Radians <- ifelse(reptiles.radians2$Reptile > 0, reptiles.radians2$Radians, NA) reptiles.radians2 <- na.omit(reptiles.radians2) reptiles.radians2 <- as.data.frame(reptiles.radians2$Radians) reptiles.radians2 <- circular(reptiles.radians2, units = "radians", template = "clock24", modulo = "2pi", zero = 0, rotation = "clock") #pdf("daily_reptiles.pdf", width = 12, height = 12) plot.circular(reptiles.radians2, pch = 16, cex = .7, stack = TRUE, axes = TRUE, sep = 0.04, shrink = 2.5, bins = 225, ticks = TRUE, tcl = 0.05, zero = pi/2, template = "clock24") rose.diag(reptiles.radians2, bins = 24, col = "dark gray", prop = 1.5,add = TRUE, rotation = "clock", zero = pi/2, axes = FALSE) lines(density.circular(reptiles.radians2, bw = 40), zero = pi/2, rotation = "clock") #dev.off() ############################################################### ### Statistical analysis - Species accumulation curves ############################################################### # Summarize observations by day beaver.species.accum <- beaver %>% group_by(Date) %>% summarize( AmericanBullfrog = (sum(AmericanBullfrog)), AmericanCoot = (sum(AmericanCoot)), BeltedKingfisher = (sum(BeltedKingfisher)), BlackCrownedNightHeron = (sum(BlackCrownedNightHeron)), BlueWingedTeal = (sum(BlueWingedTeal)), CanadaGoose = (sum(CanadaGoose)), CattleEgret = (sum(CattleEgret)), CommonGrackle = (sum(CommonGrackle)), EasternKingbird = (sum(EasternKingbird)), EuropeanStarling = (sum(EuropeanStarling)), GreatBlueHeron = (sum(GreatBlueHeron)), GreatHornedOwl = (sum(GreatHornedOwl)), GreenHeron = (sum(GreenHeron)), LittleBlueHeron = (sum(LittleBlueHeron)), Meadowlark = (sum(Meadowlark)), NorthernHarrier = (sum(NorthernHarrier)), RedTailedHawk = (sum(RedTailedHawk)), RedWingedBlackbird = (sum(RedWingedBlackbird)), SnowyEgret = (sum(SnowyEgret)), WoodDuck = (sum(WoodDuck)), YellowCrownedNightHeron = (sum(YellowCrownedNightHeron)), YellowHeadedBlackbird = (sum(YellowHeadedBlackbird)), YellowWarbler = (sum(YellowWarbler)), Muskrat = (sum(Muskrat)), NorthernRiverOtter = (sum(NorthernRiverOtter)), Raccoon = (sum(Raccoon)), Small = (sum(Small)), PaintedTurtle = (sum(PaintedTurtle))) # Create separate dataframes by organism amphibians.species.accum <- subset(beaver.species.accum, select = c(AmericanBullfrog)) birds.species.accum <- subset(beaver.species.accum, select = c(AmericanCoot, BeltedKingfisher, BlackCrownedNightHeron, BlueWingedTeal, CanadaGoose, CattleEgret, CommonGrackle, EasternKingbird, EuropeanStarling, GreatBlueHeron, GreatHornedOwl, GreenHeron, LittleBlueHeron, Meadowlark, NorthernHarrier, RedTailedHawk, RedWingedBlackbird, SnowyEgret, WoodDuck, YellowCrownedNightHeron, YellowHeadedBlackbird, YellowWarbler)) mammals.species.accum <- subset(beaver.species.accum, select = c(Muskrat, NorthernRiverOtter, Raccoon, Small)) reptiles.species.accum <- subset(beaver.species.accum, select = c(PaintedTurtle)) # Remove date columns for vegan package to function beaver.species.accum$Date <- NULL amphibians.species.accum$Date <- NULL birds.species.accum$Date <- NULL mammals.species.accum$Date <- NULL reptiles.species.accum$Date <- NULL # Estimate species richness (Jackknife 1 and Jackknife 2 are recommended for incidence data from camera traps (Hortel et al. 2016) species.accum <- specpool(beaver.species.accum, smallsample = TRUE) # Species richness estimates over time species.accum2 <- poolaccum(beaver.species.accum) # Transform data for ggplot2 species.accum3 <- summary(species.accum2) %>% map(as.data.frame) %>% map(rename, V = 2) %>% bind_rows(.id = "index") # Subset out simple species richness, Jackknife 1, and Jackknife 2 estimates species.accum4 <- subset(species.accum3, index == c("S", "jack1", "jack2")) # Rename indices species.accum4$index <- ifelse(species.accum4$index == "S", "Species richness", ifelse(species.accum4$index == "jack1", "First-order Jackknife", ifelse(species.accum4$index == "jack2", "Second-order Jackknife", NA))) # Change column names colnames(species.accum4)[c(4:5)] <- c("ci_lower", "ci.upper") # Change to numeric species.accum4$N <- as.numeric(species.accum4$N) species.accum4$V <- as.numeric(species.accum4$V) species.accum4$ci_upper <- as.numeric(species.accum4$ci.upper) species.accum4$ci_lower <- as.numeric(species.accum4$ci_lower) # Create color pallete (ColorBrewer, 3 divergent colors) cols <- c("Species richness" = "#b2df8a", "First-order Jackknife" = "#a6cee3", "Second-order Jackknife" = "#1f78b4") # Test plot ggplot(data = species.accum4, aes(x= N, color = index)) + #geom_smooth(aes(y = ci_upper, group = index), formula = "y ~ x", method = "loess", level = 0, size = 0.5, se = FALSE) + #geom_smooth(aes(y = ci_lower, group = index), formula = "y ~ x", method = "loess", level = 0, size = 0.5, se = FALSE) + geom_line(aes(y = V, group = index), size = 1) + scale_color_manual(values = cols, aesthetics = c("color")) + theme_bw(base_size = 12) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), axis.line = element_line(color = "black", size = .25, lineend = "square"), axis.ticks = element_line(color = "black", size = .25), axis.title = element_text(color = "black"), axis.text.y = element_text(color = "black"), axis.text.x = element_text(color = "black"), axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 0, l = 0)), axis.title.y.left = element_text(margin = margin(t = 0, r = 10, b = 0, l = 0)), axis.title.y.right = element_text(margin = margin(t = 0, r = 0, b = 0, l = 10)), legend.key = element_rect(fill = NA), legend.background = element_rect(color = "black", size = 0.25)) + labs(x = "Days", y = "Species richness") ############################################################### ### Statistical analysis - Daily activity patterns ############################################################### # Convert to numeric beaver.fit <- as.numeric(beaver.radians[,1]) amphibians.fit <- as.numeric(amphibians.radians[,1]) birds.fit <- as.numeric(birds.radians[,1]) mammals.fit <- as.numeric(mammals.radians[,1]) reptiles.fit <- as.numeric(reptiles.radians[,1]) # Create activity pattern estimates (model for sample size > 100; data for sample size < 100) beaver.fit <- fitact(beaver.fit, sample = "model", reps = 1000) amphibians.fit <- fitact(amphibians.fit, sample = "model", reps = 1000) birds.fit <- fitact(birds.fit, sample = "model", reps = 1000) mammals.fit <- fitact(mammals.fit, sample = "data", reps = 1000) reptiles.fit <- fitact(reptiles.fit, sample = "model", reps = 1000) # Wald test wald.test <- compareAct(list(beaver.fit, amphibians.fit, birds.fit, mammals.fit, reptiles.fit)) # Print results wald.test #1v2 0.158476950 0.01563671 102.7167332 0.0000000000 ### #1v3 -0.050540320 0.01845415 7.5004630 0.0061683133 ### #1v4 0.022452246 0.04255572 0.2783580 0.5977794667 #1v5 -0.054041579 0.02618064 4.2608436 0.0390005482 ### #2v3 -0.209017270 0.01096145 363.6040595 0.0000000000 ### #2v4 -0.136024704 0.03988216 11.6326358 0.0006480466 ### #2v5 -0.212518529 0.02156441 97.1222220 0.0000000000 ### #3v4 0.072992567 0.04106867 3.1589007 0.0755140178 #3v5 -0.003501259 0.02368696 0.0218489 0.8824897642 #4v5 -0.076493825 0.04507223 2.8802795 0.0896704538 ############################################################### ### Statistical analysis - Annual activity patterns ############################################################### # Create separate seasons dataframe beaver.seasons <- beaver # Summarize data by beaver$Date beaver.seasons <- beaver.seasons %>% group_by(Month) %>% summarize( Amphibian = sum(Amphibian) / sum(Images) * 100, Beaver = sum(Beaver) / sum(Images) * 100, Bird = sum(Bird) / sum(Images) * 100, Mammal = sum(Mammal) / sum(Images) * 100, Reptile = sum(Reptile) / sum(Images) * 100) # Create seasons column beaver.seasons$Season[1:10] <- c("Winter", "Winter", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "NA", "Winter") # Remove NAs (shortened fall study period) and month column beaver.seasons <- beaver.seasons[-c(9),] beaver.seasons$Month <- NULL # Reformat seasons dataset beaver.seasons <- reshape2::melt(beaver.seasons, id=c("Season")) colnames(beaver.seasons)[c(2:3)] <- c("Organism", "Frequency") # Two-way ANOVA seasons.anova <- aov(Frequency ~ Season * Organism, data = beaver.seasons) # Summary statistics summary(seasons.anova) # Tukey HSD test TukeyHSD(seasons.anova) #Fit: aov(formula = Frequency ~ Season * Organism, data = beaver.seasons) #Season #diff lwr upr p adj #Summer-Spring -0.001388966 -0.004105770 0.0013278383 0.4280786 #Winter-Spring -0.003763966 -0.006480770 -0.0010471619 0.0050996 ### #Winter-Summer -0.002375000 -0.005091804 0.0003418038 0.0957823 #Organism #diff lwr upr p adj #Beaver-Amphibian 0.0019509499 -0.002175789 0.006077689 0.6500382 #Bird-Amphibian 0.0081181669 0.003991428 0.012244906 0.0000297 ### #Mammal-Amphibian -0.0001931809 -0.004319920 0.003933558 0.9999186 #Reptile-Amphibian 0.0007884502 -0.003338289 0.004915189 0.9805658 #Bird-Beaver 0.0061672170 0.002040478 0.010293956 0.0013265 ### #Mammal-Beaver -0.0021441308 -0.006270870 0.001982608 0.5660545 #Reptile-Beaver -0.0011624997 -0.005289239 0.002964239 0.9232890 #Mammal-Bird -0.0083113478 -0.012438087 -0.004184609 0.0000204 ### #Reptile-Bird -0.0073297167 -0.011456456 -0.003202978 0.0001392 ### #Reptile-Mammal 0.0009816311 -0.003145108 0.005108370 0.9571239 # Season:Organism #diff lwr upr p adj #Spring:Beaver-Spring:Amphibian 5.233302e-03 -3.847352e-03 1.431396e-02 0.7105510 #Spring:Bird-Spring:Amphibian 1.407642e-02 4.995763e-03 2.315707e-02 0.0002596 ### #Spring:Mammal-Spring:Amphibian 3.979464e-04 -8.682708e-03 9.478601e-03 1.0000000 #Spring:Reptile-Spring:Amphibian 2.522427e-03 -6.558227e-03 1.160308e-02 0.9990481 #Spring:Bird-Spring:Beaver 8.843115e-03 -2.375397e-04 1.792377e-02 0.0623095 #Spring:Mammal-Spring:Beaver -4.835356e-03 -1.391601e-02 4.245299e-03 0.8036574 #Spring:Reptile-Spring:Beaver -2.710875e-03 -1.179153e-02 6.369779e-03 0.9979887 #Spring:Mammal-Spring:Bird -1.367847e-02 -2.275912e-02 -4.597816e-03 0.0004027 ### #Spring:Reptile-Spring:Bird -1.155399e-02 -2.063464e-02 -2.473335e-03 0.0040776 ### #Spring:Reptile-Spring:Mammal 2.124481e-03 -6.956174e-03 1.120514e-02 0.9998572 #Summer:Beaver-Summer:Amphibian -9.643762e-04 -1.004503e-02 8.116278e-03 1.0000000 #Summer:Bird-Summer:Amphibian 8.940455e-03 -1.401991e-04 1.802111e-02 0.0569694 #Summer:Mammal-Summer:Amphibian -1.466200e-03 -1.054685e-02 7.614454e-03 0.9999984 #Summer:Reptile-Summer:Amphibian -1.570765e-04 -9.237731e-03 8.923578e-03 1.0000000 #Summer:Bird-Summer:Beaver 9.904831e-03 8.241771e-04 1.898549e-02 0.0225225 ### #Summer:Mammal-Summer:Beaver -5.018240e-04 -9.582478e-03 8.578830e-03 1.0000000 #Summer:Reptile-Summer:Beaver 8.072997e-04 -8.273355e-03 9.887954e-03 1.0000000 #Summer:Mammal-Summer:Bird -1.040666e-02 -1.948731e-02 -1.326001e-03 0.0135675 ### #Summer:Reptile-Summer:Bird -9.097532e-03 -1.817819e-02 -1.687732e-05 0.0492152 ### #Summer:Reptile-Summer:Mammal 1.309124e-03 -7.771531e-03 1.038978e-02 0.9999996 #Winter:Beaver-Winter:Amphibian 1.583924e-03 -7.496731e-03 1.066458e-02 0.9999958 #Winter:Bird-Winter:Amphibian 1.337629e-03 -7.743026e-03 1.041828e-02 0.9999995 #Winter:Mammal-Winter:Amphibian 4.887111e-04 -8.591943e-03 9.569366e-03 1.0000000 #Winter:Reptile-Winter:Amphibian -2.818926e-18 -9.080654e-03 9.080654e-03 1.0000000 #Winter:Bird-Winter:Beaver -2.462951e-04 -9.326950e-03 8.834359e-03 1.0000000 #Winter:Mammal-Winter:Beaver -1.095213e-03 -1.017587e-02 7.985442e-03 1.0000000 #Winter:Reptile-Winter:Beaver -1.583924e-03 -1.066458e-02 7.496731e-03 0.9999958 #Winter:Mammal-Winter:Bird -8.489174e-04 -9.929572e-03 8.231737e-03 1.0000000 #Winter:Reptile-Winter:Bird -1.337629e-03 -1.041828e-02 7.743026e-03 0.9999995 #Winter:Reptile-Winter:Mammal -4.887111e-04 -9.569366e-03 8.591943e-03 1.0000000 # Create separate dataframes to rank seasons for each organism amphibian.seasons <- subset(beaver.seasons, Organism == "Amphibian") bird.seasons <- subset(beaver.seasons, Organism == "Bird") mammal.seasons <- subset(beaver.seasons, Organism == "Mammal") reptile.seasons <- subset(beaver.seasons, Organism == "Reptile") beaver.seasons <- subset(beaver.seasons, Organism == "Beaver") # Change season to factor amphibian.seasons$Season <- as.factor(amphibian.seasons$Season) bird.seasons$Season <- as.factor(bird.seasons$Season) mammal.seasons$Season <- as.factor(mammal.seasons$Season) reptile.seasons$Season <- as.factor(reptile.seasons$Season) beaver.seasons$Season <- as.factor(beaver.seasons$Season) # Steele-Dwass multiple comparisons dscfAllPairsTest(Frequency ~ Season, data = amphibian.seasons) dscfAllPairsTest(Frequency ~ Season, data = bird.seasons) dscfAllPairsTest(Frequency ~ Season, data = mammal.seasons) dscfAllPairsTest(Frequency ~ Season, data = reptile.seasons) dscfAllPairsTest(Frequency ~ Season, data = beaver.seasons) # One-way ANOVAs by organism amphibian.anova <- aov(Frequency ~ Season, data = amphibian.seasons) bird.anova <- aov(Frequency ~ Season, data = bird.seasons) mammal.anova <- aov(Frequency ~ Season, data = mammal.seasons) reptile.anova <- aov(Frequency ~ Season, data = reptile.seasons) beaver.anova <- aov(Frequency ~ Season, data = beaver.seasons) # Summary statistics summary(amphibian.anova) summary(bird.anova) summary(mammal.anova) summary(reptile.anova) summary(beaver.anova) # Tukey HSD tests TukeyHSD(amphibian.anova) TukeyHSD(bird.anova) TukeyHSD(mammal.anova) TukeyHSD(reptile.anova) TukeyHSD(beaver.anova) ################################################################
ad0a48c9ce92bc40702756269ac359954ab9bd2d
[ "R" ]
1
R
simontye/2019_beaver
998d0f53ff0206ee09e8cacf1c6803ef1dd03920
5b64eb5e61eb716a97774a24e3b900611b47eb75
refs/heads/master
<file_sep>require 'test_helper' class MapControllerTest < ActionDispatch::IntegrationTest test "should get google" do get map_google_url assert_response :success end test "should get daum" do get map_daum_url assert_response :success end end <file_sep>Ckeditor.setup do |config| config.parent_controller = 'MyController' end<file_sep>require 'differ/string' require 'uri' class CafesController < ApplicationController before_action :cafe_common, only: [:show, :edit] before_action :cafe_common_id, only: [:update, :destroy] def index end def new @lat = params[:lat] @lng = params[:lng] @address = params[:address] @cafes = Cafes.new end def create @cafes = Cafes.new(get_params) respond_to do |format| if @cafes.save format.html { redirect_to URI.encode('/cafes/'+params[:name]), notice: "카페가 안전하게 등록되었습니다." } else format.html { render action: "new" } end end end def show end def edit end def update respond_to do |format| if @cafes.update(get_params) format.html { redirect_to URI.encode('/cafes/'+params[:name]), notice: "카페 정보가 안전하게 수정되었습니다." } else format.html { render action: "edit" } end end end def destroy respond_to do |format| if @cafes.destroy format.html { redirect_to cafe_path } end end end def history @cafes = Cafes.find_by_name(params[:name]) @versions = Cafes.find_by_name(params[:name]).versions[params[:ver].to_i] end def history_list @cafes = Cafes.find_by_name(params[:name]) @url = request.original_url end def differ @cafe = Cafes.find_by_name(params[:name]) @old_ver = params[:old_ver] @new_ver = params[:new_ver] @old = Cafes.find_by_name(params[:name]).versions[params[:old_ver].to_i].reify.content if Cafes.find_by_name(params[:name]).ver != params[:new_ver].to_i @new = Cafes.find_by_name(params[:name]).versions[params[:new_ver].to_i].reify.content else @new = Cafes.find_by_name(params[:name]).content end @diff = (@new - @old) end Differ.format = :html private def get_params params.require(:cafes).permit([:markericon, :name, :phone, :lat, :lng, :address, :content, :americano, :size, :toilet, :parking, :allnight, :floor, :ip, :ver]) end def cafe_common @cafes = Cafes.find_by_name(params[:name]) end def cafe_common_id @cafes = Cafes.find(params[:id]) end end <file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :set_paper_trail_whodunnit def info_for_paper_trail # Save additional info { ip: request.remote_ip } end def user_for_paper_trail # Save the user responsible for the action user_signed_in? ? current_user.id : 'Guest' end end <file_sep>class Cafes < ApplicationRecord has_paper_trail meta: { :ip => :ip } end <file_sep>class MapController < ApplicationController def google @q = Cafes.ransack(params[:q]) @cafes = @q.result(distinct: true) @query_latitude = params[:lat] @query_longitude = params[:lng] @query_zoom = params[:zoom] @remote_ip = request.env["HTTP_X_FORWARDED_FOR"] @url = request.original_url respond_to do |format| format.html {render :layout => 'map'} format.json {render :json =>@cafes, :layout => 'map'} format.js end end def daum @q = Cafes.ransack(params[:q]) @cafes = @q.result(distinct: true) @query_latitude = params[:lat] @query_longitude = params[:lng] @query_zoom = params[:zoom] @remote_ip = request.env["HTTP_X_FORWARDED_FOR"] @url = request.original_url respond_to do |format| format.html {render :layout => 'map'} format.json {render :json =>@cafes, :layout => 'map'} format.js end end end <file_sep>class CreateCafes < ActiveRecord::Migration[5.0] def change create_table :cafes do |t| t.string :markericon t.string :name t.string :phone t.float :lat t.float :lng t.string :address t.text :content t.integer :americano t.string :size t.string :toilet t.string :parking t.string :allnight t.string :floor t.string :ip t.integer :ver t.timestamps end end end
b64be02c95eae5bf73c0c0e0ddeac1c70ea25470
[ "Ruby" ]
7
Ruby
forceson/cafewiki2
c41ac3f40732eb00b7ab29811cbbe9f56f38edc1
62d58ac05b844b221e7d1351e7387330c572ff93
refs/heads/master
<file_sep>#include<bits/stdc++.h> #include<pthread.h> #include<cstdio> #include<stdlib.h> #include<unistd.h> #include<semaphore.h> using namespace std; sem_t mutex; int CSvalue=0; void *p(void* id) { while(1) { //ncs_begin int *idd=(int*)id; int id1=*idd; //ncs_end //waiting_process_begin sem_wait (&mutex); cout<<"\t"<<id1<<" is waiting"<<endl; usleep(1500000+id1*100000); //waiting_process_end() //critical_section_begin cout<<"\t\t\t================================\n\n"; cout<<"\t\t\t"<<id1<<" is in Critical Section CSvalue="<<(++CSvalue)<<endl<<endl; cout<<"\t\t\t================================\n\n"; cout<<"\t"<<id1<<" is out of Critical Section"<<endl<<endl; //critical_section_ends //post_critical_section_start sem_post (&mutex); cout<<"\t"<<id1<<" called Signal()"<<endl<<endl; usleep(1000000+id1*100000); //post_critcal_section_finish } pthread_exit(NULL); } //driver code int main(int argc,char* argv[]) //value of 'n' using command line arguments { int n=atoi(argv[1]); pthread_t thread[n]; sem_init(&mutex, 0, 1); int id[n]; for(int i=0;i<n;i++) { id[i]=i+1; pthread_create(&thread[i], NULL, &p, &id[i]); } pthread_exit(NULL); return 0; } <file_sep>#include<stdio.h> #include<mpi.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[]) { int rank, src, dest, numprocs, i, no, sum=0; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); if(rank==0){ for(i=1; i<numprocs; i++){ MPI_Recv(&no, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); sum+=no; } printf("SUM IS: %d\n", sum+numprocs); } else{ MPI_Send(&rank, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } MPI_Finalize(); return 0; } <file_sep>#include<bits/stdc++.h> #include<pthread.h> #include <unistd.h> using namespace std; pthread_mutex_t mutex; int con=0, n, data=1,srd=0; class monitor { public: int readers, writers, bk_writer, bk_reader; pthread_cond_t OKtoRead, OKtoWrite; //pthread_cond_init(&notZero,NULL); void StartRead(int id){ if(writers!=0 || bk_writer!=0){ bk_reader++; printf("Reader %d blocked\n",id); pthread_cond_wait(&OKtoRead, &mutex); } readers++; pthread_cond_signal(&OKtoRead); } void EndRead(int id){ readers--; printf("Reader %d leaving database\n",id); if(readers==0){ pthread_cond_signal(&OKtoWrite); } } void StartWrite(int id){ if(writers!=0 || readers!=0){ bk_writer++; printf("Writer %d blocked\n",id); pthread_cond_wait(&OKtoWrite, &mutex); } writers++; } void EndWrite(int id){ writers--; printf("Writer %d leaving database\n",id); if(bk_reader==0){ pthread_cond_signal(&OKtoWrite); } else{ pthread_cond_signal(&OKtoRead); } } monitor(){ readers=0, writers=0, bk_writer=0, bk_reader=0; pthread_cond_init(&OKtoRead, NULL); pthread_cond_init(&OKtoWrite, NULL); } }; monitor obj; int reader_id=1 ,writer_id=1; void *readerFunc(void *arg) { while(1){ obj.StartRead(reader_id); printf("***** Reader %d reading database *****\n\n",reader_id); usleep(1000000); obj.EndRead(reader_id); usleep(1000000); reader_id++; } } void *writerFunc(void *arg) { while(1) { //usleep(1000000); obj.StartWrite(writer_id); printf("<<<<<< Writer %d writing database >>>>>> \n\n",writer_id); usleep(1000000); obj.EndWrite(writer_id); usleep(1000000); writer_id++; } } int main(){ pthread_t reader, writer; pthread_mutex_init(&mutex,NULL); pthread_create(&reader, NULL, &readerFunc, NULL); pthread_create(&writer, NULL, &writerFunc, NULL); pthread_exit(NULL); pthread_mutex_destroy(&mutex); return 0; } <file_sep>#include <bits/stdc++.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> using namespace std; sem_t notempty; vector<int> buffer; void *produce(void* id) { while(1) { //ncs_begin //ncs_end //waiting_process_begin //sem_wait(&mutex); usleep(1000000); cout<<"\tproducer is producing\n"; //waiting_process_end() //critical_section_begin cout<<"\t|================================|\n"; cout<<"\t|Producer is in Critical Section |"<<endl; buffer.push_back(1); cout<<"\t|Size of buffer= "<<buffer.size()<<" \t\t|\n"; cout<<"\t|================================|\n\n"; cout<<"\tProducer is out of Critical Section"<<endl<<endl; //critical_section_ends //post_critical_section_start sem_post(&notempty); cout<<"\tProducer called Signal()"<<endl<<endl; usleep(1000000); //post_critcal_section_finish } pthread_exit(NULL); } void *consume(void* id) { while(1) { //ncs_begin //ncs_end //waiting_process_begin cout<<"\t\tConsumer is waiting\n "; sem_wait(&notempty); go: if(buffer.empty()==true ) { printf("Consumer cant consume, buffer is empty\n"); usleep(1000000); goto go; } //waiting_process_end() //critical_section_begin cout<<"\t\t|================================|\n"; cout<<"\t\t|Consumer is in Critical Section |"<<endl; buffer.pop_back(); cout<<"\t\t|Size of buffer= "<<buffer.size()<<" \t\t|\n"; cout<<"\t\t|================================|\n\n"; cout<<"\t\tConsumer is out of Critical Section"<<endl; //critical_section_ends //post_critical_section_start //sem_post(&mutex); //cout<<"\t\t"<<id2<<" called Signal()"<<endl<<endl; usleep(1000000); //post_critcal_section_finish } pthread_exit(NULL); } int main() { pthread_t thread1, thread2; sem_init(&notempty, 0, 0); int id1=1,id2=2; pthread_create(&thread1, NULL, &produce, &id1); pthread_create(&thread2, NULL, &consume, &id2); pthread_exit(NULL); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *myThreadFun(void *vargp) { sleep(1); int a=(int)vargp; printf("Hello %d\n",a); return NULL; } int main() { pthread_t tid[5]; int i,ch; for(i=0;i<5;i++) { pthread_create(&tid[i], NULL, myThreadFun,(void *)i); pthread_join(tid[i], NULL); } pthread_exit(NULL); exit(0); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *myThreadFun(void *vargp) { sleep(1); int a=(int)vargp; printf("Sum till %d is %d\n",a,(a*(a+1))/2); return NULL; } int main() { pthread_t tid; int i,n; scanf("%d",&n); pthread_create(&tid, NULL, myThreadFun,(void *)n); pthread_exit(NULL); exit(0); } <file_sep>#include<stdio.h> #include<string.h> #include<mpi.h> #define BUFFER_SIZE 100 int main(int argc, char *argv[]){ int rank, numprocs, src, dest, src_tag, dest_tag; int root=0, len_name, l, i; char proc_name[100], proc_name_root[100]; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); for(i=0; i<numprocs; i++){ if(i==rank)continue; char msg[]="HELLO WORLD"; l = strlen(msg); dest = i; dest_tag = 0; printf("Process with rank %d sending msg %s to process with rank %d\n", rank, msg, i); MPI_Send(msg, l, MPI_CHAR, dest, dest_tag, MPI_COMM_WORLD); } for(i=0; i<numprocs; i++){ if(i==rank)continue; char rmsg[BUFFER_SIZE]; src=i, src_tag=0; MPI_Recv(rmsg, BUFFER_SIZE, MPI_CHAR, src, src_tag, MPI_COMM_WORLD, &status); printf("Process %d received msg %s from process %d\n", rank, rmsg, src); } MPI_Finalize(); return 0; } <file_sep>#include <stdio.h> #include <pthread.h> int id=0; void test(int i){ L : if(id != 0) goto L; id = i; sleep(1); if( id != i) goto L; printf("\t\t%d in crit\n ",i); id = 0; printf("\t\t\t\t%d out crit\n\n",i); } int main(){ pthread_t t1,t2,t3,t4; pthread_create(&t1,NULL,(void*)&test,(void*)1); pthread_create(&t2,NULL,(void*)&test,(void*)2); pthread_create(&t3,NULL,(void*)&test,(void*)3); pthread_create(&t4,NULL,(void*)&test,(void*)4); pthread_join(t1,NULL); pthread_join(t2,NULL); pthread_join(t3,NULL); pthread_join(t4,NULL); printf("\nParent terminated\n"); return(0); } <file_sep>#include <bits/stdc++.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> using namespace std; sem_t mutex; int ind=0; void *p(void* id) { while(1) { //ncs_begin int *idd=(int*)id; int id1=*idd; //ncs_end //waiting_process_begin usleep(1500000); sem_wait(&mutex); lab: cout<<"\t"<<id1<<" is waiting"<<endl; //waiting_process_end() //critical_section_begin cout<<"\t|================================|\n"; cout<<"\t|"<<id1<<" is in Critical Section |"<<endl; cout<<"\t|================================|\n\n"; cout<<"\t"<<id1<<" is out of Critical Section"<<endl<<endl; //critical_section_ends //post_critical_section_start sem_post(&mutex); cout<<"\t"<<id1<<" called Signal()"<<endl<<endl; ind++; if(ind%4!=0) usleep(1000000); else goto lab; //post_critcal_section_finish } pthread_exit(NULL); } void *q(void* id) { while(1) { //ncs_begin int *idd=(int*)id; int id2=*idd; //ncs_end //waiting_process_begin cout<<"\t\t"<<id2<<" is waiting"<<endl; sem_wait(&mutex); usleep(1000000); //waiting_process_end() //critical_section_begin cout<<"\t\t|================================|\n"; cout<<"\t\t|"<<id2<<" is in Critical Section |"<<endl; cout<<"\t\t|================================|\n\n"; cout<<"\t\t"<<id2<<" is out of Critical Section"<<endl; //critical_section_ends //post_critical_section_start sem_post(&mutex); cout<<"\t\t"<<id2<<" called Signal()"<<endl<<endl; usleep(1500000); //post_critcal_section_finish } pthread_exit(NULL); } int main() { pthread_t thread1, thread2; sem_init(&mutex, 0, 1); int id1=1,id2=2; pthread_create(&thread1, NULL, &p, &id1); pthread_create(&thread2, NULL, &q, &id2); pthread_exit(NULL); return 0; } <file_sep>#include<bits/stdc++.h> #include<semaphore.h> #include<pthread.h> #include<stdlib.h> #include<queue> #include <unistd.h> using namespace std; int inf_buff[1000001]; sem_t notEmpty, notFull, mutex; int data=1; int con=1; int ind=1; int srd=1; int in=0, out=0, n; void *producerFunc(void *arg){ while(1){ usleep(3000000); printf("Producer producing data %d at index %d\n\n", data,in); sem_wait(&notFull); inf_buff[in]=data; data++; in=(in+1)%n; sem_post(&notEmpty); usleep(1000000); con++; ind++; } } void *consumerFunc(void *arg){ while(1){ usleep(4000000); sem_wait(&notEmpty); printf("\n\t\t\tConsumer is waiting\n\n"); usleep(1000000); int k=inf_buff[out]; out=(out+1)%n; sem_post(&notFull); printf("\t\t\tConsumer consuming data %d\n\n",k); usleep(3000000); con++; ind++; } } int main(){ int i; sem_init(&notEmpty, 0, 0); printf("Enter size of buffer: "); scanf("%d", &n); sem_init(&notFull, 0, n - 1); pthread_t producer, consumer; pthread_create(&producer, NULL, &producerFunc, NULL); pthread_create(&consumer, NULL, &consumerFunc, NULL); pthread_exit(NULL); return 0; } <file_sep>#include<bits/stdc++.h> #include<semaphore.h> #include<pthread.h> #include<stdlib.h> #include<queue> #include <unistd.h> using namespace std; queue <int> inf_buff; sem_t notEmpty, notFull; int n; bool ful=false; int data=1; void *producerFunc(void *arg){ while(1){ usleep(3000000); printf("Producer producing data %d\n\n", data); int val; sem_getvalue(&notFull,&val); if(val<=0&&ful==false) { printf("Buffer FULL Producer waiting to produce\n"); ful=true; } sem_wait(&notFull); inf_buff.push(data); data++; sem_post(&notEmpty); usleep(1000000); } } void *consumerFunc(void *arg){ while(1){ usleep(4000000); sem_wait(&notEmpty); printf("\n\t\t\t\tConsumer is waiting\n\n"); usleep(1000000); if(inf_buff.size()>=n-1&&ful==true){ ful=false; while(!inf_buff.empty()){ int k=inf_buff.front(); //Consumer consuming data sem_post(&notFull); printf("\t\t\t\tConsumer consuming data %d\n\n", k); inf_buff.pop(); //printf("\t\t\t\tCurrent buffer size =%ld \n\n",inf_buff.size()); usleep(1000000); } } else { int k=inf_buff.front(); sem_post(&notFull); //Consumer consuming data printf("\t\t\t\tConsumer consuming data %d\n\n", k); inf_buff.pop(); //printf("\t\t\t\tCurrent buffer size =%ld \n\n",inf_buff.size()); } usleep(3000000); } } int main(){ int i; sem_init(&notEmpty, 0, 0); printf("Enter size of buffer: "); scanf("%d", &n); sem_init(&notFull, 0, n - 1); pthread_t producer, consumer; pthread_create(&producer, NULL, &producerFunc, NULL); pthread_create(&consumer, NULL, &consumerFunc, NULL); pthread_exit(NULL); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include<math.h> // A normal C function that is executed as a thread when its name // is specified in pthread_create() void *myThreadFun(void *vargp) { printf("Printing GeeksQuiz from Thread \n"); return NULL; } void *fun(void *c) { printf("HELLO\n") ; return NULL ; } struct node { int a[100],s ; }; void *fun2( void *b) { int i ; struct node *a= b; for(i=0 ; i<(*a).s ;i++) printf("%d " ,(*a).a[i]) ; printf("\n") ; return NULL ; } void *fun3(void *b) { int *n = b ; float *f ; f =calloc(100 , sizeof(float)) ; int i=0 ; for( ; *n<=100 ;(*n)++ ) f[i++] = sqrt(*n) ; ; printf("%d ",*n) ; pthread_exit(f) ; } int main() { /* pthread_t tid; printf("Before Thread\n"); pthread_create(&tid, NULL, myThreadFun, NULL ); pthread_join(tid, NULL); printf("After Thread\n"); */ printf("\nnew\n\n") ; pthread_t t1,t2 ; char c[]="hello"; pthread_create(&t1 ,NULL , fun , NULL) ; pthread_join(t1,NULL) ; /* ------------- 1 ------------------- int i; for( i=0 ; i<5 ;i++) { pthread_create(&t1 ,NULL , fun , NULL) ; pthread_join(t1,NULL) ; } */ int a[]={0,1,2,3,4,5} ; pthread_t t; int s=6 ,i; struct node b ; b.s=6 ; for( i=0 ; i<b.s ;i++ ) b.a[i]=i ; pthread_create( &t , NULL , fun2 , &b) ; pthread_join( t , NULL) ; for( i=1 ; i<=1 ;i++ ) { pthread_create( &t , NULL , fun3 , &i ); void *b; pthread_join( t,&b ); float *f=b ; for( i=0 ; i<100 ;i++ ) printf("%f\n",f[i]) ; } exit(0); } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *myThreadFun(void *vargp) { int *n=vargp; int a=*n; int *ans=(int*)malloc(sizeof(int)); *ans=(a*(a+1)*(2*a+1))/6; pthread_exit(ans); } int main() { pthread_t tid; int i,n; void *ans; scanf("%d",&n); pthread_create(&tid, NULL, myThreadFun,&n); pthread_join(tid,&ans); int *ansa=ans; printf("Sum of series til %d is %d\n",n,*ansa); return 0; } <file_sep>#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define M 3 #define K 3 #define N 3 long int A [M][K] = { {1,2,3}, {3,2,1}, {1,2,3} }; long int B [K][N] = { {7,2,9}, {5,4,3}, {3,4,5} }; long int C [M][N]; struct node { int i; int j; }; void *multiply(void *param) { struct node *matrix=param; int n,sum=0; for(n = 0; n< K; n++) { sum+=A[matrix->i][n]*B[n][matrix->j]; } C[matrix->i][matrix->j]=sum; pthread_exit(0); } int main() { int i,j, count = 0; for(i=0;i<M;i++) { for(j=0;j<N;j++) { struct node *matrix=(struct node *)malloc(sizeof(struct node)); matrix->i = i; matrix->j = j; pthread_t tid; pthread_create(&tid,NULL,multiply,matrix); pthread_join(tid, NULL); count++; } } for(i=0;i<M;i++) { for(j=0;j<N;j++) { printf("%ld ", C[i][j]); } printf("\n"); } } <file_sep>#include<stdio.h> #include<stdlib.h> #include<omp.h> int main(int argc , char **argv) { int Threadid, Noofthreads,i; printf("Parallel execution:\n"); int sum=0; #pragma omp parallel for for(i=1;i<=atoi(argv[1]);i++) { #pragma omp critical sum+=i; printf("Sum = %d \n",sum); } printf("Final sum: %d\n", sum); printf("\nSequential execution:\n"); sum=0; for(i=1;i<=atoi(argv[1]);i++) { sum+=i; printf("Sum = %d \n",sum); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #include "mpi.h" double func(double x) { return (4.0 / (1.0 + x*x)); } int main(int argc,char *argv[]) { int NoIntervals, interval; int MyRank, Numprocs; int iproc, Root = 0; int Source, Source_tag; int Destination, Destination_tag; double PI25DT = 3.141592653589793238462643; double mypi, pi, h, sum, x; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&Numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&MyRank); if(MyRank == Root) { puts("Enter the NoIntervals of intervals: "); scanf("%d",&NoIntervals); for(iproc = 1 ; iproc < Numprocs ; iproc++) { Destination = iproc; Destination_tag = 0; MPI_Send(&NoIntervals, 1, MPI_INT, Destination, Destination_tag, MPI_COMM_WORLD); } } else { Source = Root; Source_tag = 0; MPI_Recv(&NoIntervals, 1, MPI_INT, Source, Source_tag, MPI_COMM_WORLD, &status); } if(NoIntervals <= 0) { if(MyRank == Root) printf("Invalid Value for Number of Intervals .....\n"); MPI_Finalize(); exit(-1); } h = 1.0 / (double) NoIntervals; sum = 0.0; for(interval = MyRank + 1; interval <= NoIntervals; interval += Numprocs) { x = h * ((double)interval - 0.5); sum += func(x); } mypi = h * sum; pi = 0.0; if(MyRank == Root) { pi = pi + mypi; for(iproc = 1 ; iproc < Numprocs ; iproc++) { Source = iproc; Source_tag = 0; MPI_Recv(&mypi, 1, MPI_DOUBLE, Source, Source_tag, MPI_COMM_WORLD, &status); pi = pi + mypi; } } else { Destination = Root; Destination_tag = 0; MPI_Send(&mypi, 1, MPI_DOUBLE, Destination, Destination_tag, MPI_COMM_WORLD); } if(MyRank == Root) { printf("pi is approximately %.16f, Error is %.16f\n", pi, fabs(pi - PI25DT)); } MPI_Finalize(); } <file_sep>#include<stdio.h> #include<pthread.h> #include<stdlib.h> #include<math.h> int main(int argc,char *argv[]) { FILE *fp; if(argc==1) { perror("ERROR: No filename given "); return 0; } else if(argc>2) { perror("ERROR: More than one filename given "); return 0; } else { fp=fopen(argv[1],"r"); if(!fp) { perror("ERROR "); return -1; } if(fp) { perror("FILE FOUND "); printf("Do you want the content of file to be printed here: YES: 1\t NO: 0\n"); int c; scanf("%d",&c); if(c==1) { char s; while((s=fgetc(fp))!=EOF) printf("%c",s); } return 0; } fclose(fp); } return 0; } <file_sep>#include<bits/stdc++.h> #include<semaphore.h> #include<pthread.h> #include<unistd.h> sem_t mutex, delay; int count, k, n; void *callThread(void *arg){ int *x=(int *)arg; int id=*x; int m; id++; while(1){ printf("\n\tProcess %d in non-critical section\n", id); sleep(1); sem_wait(&mutex); count=count-1; m=count; sem_post(&mutex); if(m<=-1)sem_wait(&delay); printf("\n\t\t\t\t=============================\n\t\t\t\tProcess %d in critical section\n\t\t\t\t=============================\n\n", id); sleep(n); printf("\tProcess %d out of critical section\n", id); sem_wait(&mutex); count=count+1; if(count<=0)sem_post(&delay); sem_post(&mutex); sleep(1+id*1); } } int main(){ int i; sem_init(&mutex, 0, 1); sem_init(&delay, 0, 0); printf("Enter no. of threads: "); scanf("%d", &n); printf("Enter processes to be in critical section: "); scanf("%d", &k); if(n<k) { printf("Value of k is greater than n\n"); return 0; } count=k; pthread_t thread_buffer[n]; for(i=0; i<n; i++){ pthread_create(&thread_buffer[i], NULL, &callThread, &i); sleep(1); } pthread_exit(NULL); return 0; } <file_sep># Concurrent_Parallel_Programming Important assignments and their solutions for the course: Concurrent and Parallel programming (B.Tech, CSE, MNIT (2015-2019)) Week - 2: Q.2 Write a program for matrix multiplication using pthread_join(). No mutex should be used. Q.3 Write a C program in which a filename is passed as a command line argument. In case a wrong name or no file name is passed is passed using CLA it should print an error message using perror(). Q.4 Write a C program that continuously print(with a sleep time of 1 second) the process id and the total sleep time. This program should send a SIGINT signal using signal() call, when a particular key is pressed. Q.5 Write a program using pthread to find out the sum of following series: 1+4+9+16+.......+ n. Here main function should write the final output on screen. Main thread will create the child threads and child threads will find out the sum of series. Week - 4: Q. 1 Implement all the four attempt of Dekker’s algorithm to solve critical section problem. Q.2 Implement Dekker’s Algorithm for mutual exclusion. Q.3 Implement fisher’s algorithm for mutual exclusion Q.4 Implement Manna-Pnueli algorithm for Mutual exclusion. Week - 5: 1. Implement solution of Critical Section problem with Semaphores (two processes). 2. Implement solution of Critical Section problem with Semaphores (N processes). 3. Implement solution of Critical Section problem with Semaphores (k out of N processes). 4. Implement producer-consumer problem with Semaphores (infinite buffer). 5. Implement producer-consumer problem with Semaphores (finite buffer). 6. Implement producer-consumer problem with Semaphores (circular buffer). 7. Implement critical section problem with exchange exchange (a, b) is integer temp Temp <- a a <- b b <- Temp Week - 6: 1. Implement Critical Section problem using semaphores with a monitor. 2. Implement the solution of producer-consumer bounded buffer problem with a monitor. 3. Implement the solution of Readers and writers with a monitor. 4. Consider a system consisting of processes P1, P2, ..., Pn, each of which has a unique priority number. Write a monitor that allocates three identical line printers to these processes, using the priority numbers for deciding the order of allocation. Week - 7: 1. Write MPI Program (SPMD) to get started. 2. Write MPI Program (MPMD) to get started. 3. Write MPI program to find sum of n integers on Parallel Processing Platform. You have to use MPI point-to-point blocking communication library calls. 4. Write MPI program to find sum of n integers on Parallel Processing Platform. You have to use MPI point-to-point blocking communication library calls. 5. Write MPI program to find sum of n integers on a Parallel Computing System in which processors are connected with ring topology and use MPI point-to-point blocking communication library calls. 6. Write MPI program to find sum of n integers on a Parallel Computing System in which processors are connected with tree topology (Associative-fan-in rule for tree can be assumed) and use MPI point-to-point blocking communication library calls. 7. Write MPI program to compute the value of PI by numerical integration using MPI point-to-point blocking communication library calls. 8. Write MPI program for prefix sum (scan operation) calculation using MPI point-to-point blocking communication library calls. 9. Write MPI program to find sum of n integers on a Parallel Computing System in which processors are connected with tree topology (Associative-fan-in rule for tree can be assumed) and use MPI point-to-point non-blocking communication library calls. 10. Write MPI program to broadcast message "Hello world" to all the process. Week - 8: 11. Write a OpenMP program to print unique identifier. 12. Write a "Hello world" Program Using OpenMP pragmas. 13. Illustrate a program for loop recurrence using OpenMP PARALLEL FOR directive. 14. Write an OpenMP program to find Sum of Natural Numbers using OpenMP Parallel FOR directive. 15. Write an OpenMP program to find Sum of Natural Numbers using OpenMP REDUCTION clause. 16. Write an OpenMP program for Loop-carried dependence using OpenMP parallel Directive. <file_sep>#include<stdio.h> #include<stdlib.h> #include<omp.h> int main(int argc , char **argv) { int Threadid, Noofthreads; omp_set_num_threads(atoi(argv[1])); #pragma omp parallel private(Threadid) { Threadid = omp_get_thread_num(); printf("\n\t\t Hello World is being printed by the thread : %d\n", Threadid); /*if (Threadid == 0) { Noofthreads = omp_get_num_threads(); printf("\n\t\t Master thread printing total number of threads for this execution are : %d\n", Noofthreads); }*/ } return 0; } <file_sep>#include<bits/stdc++.h> #include<pthread.h> #include<stdlib.h> #include<unistd.h> using namespace std; void exchange(int *a, int *b){ int temp=*a; *a=*b; *b=temp; } int common=1; void *callThread1(void *arg){ int local1=0; while(1){ sleep(2); cout<<"\n\tProcess p in non-critical section\n"; do{ exchange(&common, &local1); } while(local1!=1); cout<<"\n\t\t=============================\n\t\tProcess p in critical section\n\t\t=============================\n\n"; cout<<"\tProcess p out of critical section\n"; exchange(&common, &local1); sleep(2); } } void *callThread2(void *arg){ int local2=0; while(1){ sleep(2); cout<<"\n\tProcess q in non-critical section\n"; do{ exchange(&common, &local2); } while(local2!=1); cout<<"\n\t\t=============================\n\t\tProcess q in critical section\n\t\t=============================\n\n"; cout<<"\tProcess q out of critical section\n"; exchange(&common, &local2); sleep(2); } } int main(){ pthread_t p, q; pthread_create(&p, NULL, &callThread1, NULL); pthread_create(&q, NULL, &callThread2, NULL); pthread_exit(NULL); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <math.h> void *calc(void *vargp) { double a[100]; int i; void *ap; for(i=0;i<100;i++) a[i]=sqrt(i),printf("%.2lf \t",a[i]); void *ap; ap=(void*)a; return ap; } void *show(double* p) { /*double *p; p=*((double*)vargp);*/ int i; for(i=0;i<100;i++) printf("%.2lf \t",p[i]); printf("\n"); return NULL; } int main() { pthread_t tid,tid2; int i,n; double *p; pthread_create(&tid, NULL, calc,NULL); //p=pthread_join(tid, NULL); p=(double *)calc( //pthread_create(&tid2, NULL, show, p); //pthread_join(tid2, NULL); exit(0); } <file_sep>#include<stdio.h> #include<stdlib.h> #include<omp.h> int main(int argc , char **argv) { int Threadid, Noofthreads,i; int a[100],n; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); int sum=0; printf("Parallel execution:\n"); #pragma omp parallel for for(i=0;i<n;i++) { #pragma omp critical //to remove dependencies sum+=a[i]; printf("Sum = %d \n",sum); } printf("Final sum: %d\n", sum); printf("\nSequential execution:\n"); sum=0; for(i=0;i<n;i++) { sum+=a[i]; printf("Sum = %d \n",sum); } return 0; } <file_sep>#include<stdio.h> #include<mpi.h> #include<stdlib.h> #include<string.h> #include<math.h> #define LOG2(x) log10((double)(x)) / log10((double) 2) int main(int argc, char *argv[]) { int rank, numprocs, src, dest, data, i, no1, no2, sum = 0; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); double height = LOG2(numprocs); if(ceil(height) != floor(height)) { printf("Number should be exact power of 2\n"); return 1; } sum = rank; for(i = 0; i < (int)height; i++) { no1 = pow(2, i); if(rank%no1 == 0) { no2 = pow(2, i+1); if(rank%no2 == 0) { MPI_Recv(&data, 1, MPI_INT, rank + no1, 0, MPI_COMM_WORLD, &status); sum = sum + data; } else { MPI_Send(&sum, 1, MPI_INT, rank - no1, 0, MPI_COMM_WORLD); } } } if(rank == 0) { printf("SUM IS: %d\n", sum + numprocs); } MPI_Finalize(); return 0; } <file_sep>#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> #include <pthread.h> #include <sys/types.h> #include <sys/syscall.h> void sighandler(int); int c=0; void *myThreadFun(void *vargp) { sleep(1); int *n=vargp; int a=*n; pid_t id = syscall(__NR_gettid); printf("Hello!! Thread no. %d created and tid = %d\n",a,id); pthread_exit(NULL); } int main() { signal(SIGINT,sighandler); pthread_t tid[100000]; int i=0; while(1) { pthread_create(&tid[i], NULL, myThreadFun,&i); pthread_join(tid[i], NULL); c++; i++; } return(0); } void sighandler(int signum) { printf("\nTotal processes done till now : %d\n", c); exit(1); } <file_sep>#include<bits/stdc++.h> #include<pthread.h> #include <unistd.h> using namespace std; pthread_mutex_t mutex; int con=0, n, data=1,srd=0,f=0; class monitor { public: int s, curr_size, cnt,asd; queue <int> fin_buffer; pthread_cond_t notEmpty, notFull; //pthread_cond_init(&notZero,NULL); void append(int d){ if(curr_size==n){ cnt++; if(cnt%2==0){ while(!fin_buffer.empty()){ int k=fin_buffer.front(); printf("<<<<< CONSUMER CONSUMING DATA %d>>>>> \n\n", k); fin_buffer.pop(); curr_size--; //usleep(1000000); } if(asd%2!=0) f=1; asd++; } else{ printf("\tProducer blocked\n\n"); pthread_cond_wait(&notFull, &mutex); } //if(f==1); } //if(cnt%3==0)f=1; if(f==0) { fin_buffer.push(d); curr_size++; pthread_cond_signal(&notEmpty); } } int take(){ if(curr_size==0){ printf("\tConsumer blocked\n\n"); pthread_cond_wait(&notEmpty, &mutex); } int k=fin_buffer.front(); fin_buffer.pop(); curr_size--; pthread_cond_signal(&notFull); return k; } monitor(){ s=1; curr_size=0; cnt=0,asd=0; pthread_cond_init(&notEmpty, NULL); pthread_cond_init(&notFull, NULL); } }; monitor obj; void *producerFunc(void *arg) { while(1){ if(srd%3==0) usleep(1000000); else usleep(3000000); obj.append(data); if(f==0) printf("*****PRODUCER PRODUCING DATA %d*****\n\n", data); f=0; data++; usleep(1000000); srd++; } } void *consumerFunc(void *arg) { while(1) { usleep(4000000); int k=obj.take(); printf("<<<<<< CONSUMER CONSUMING DATA %d>>>>>> \n\n", k); usleep(3000000); } } int main(){ cout<<"Enter size of buffer: "<<endl; cin>>n; pthread_t producer, consumer; pthread_mutex_init(&mutex,NULL); pthread_create(&producer, NULL, &producerFunc, NULL); pthread_create(&consumer, NULL, &consumerFunc, NULL); pthread_exit(NULL); pthread_mutex_destroy(&mutex); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <omp.h> /* Main Program */ main(int argc,char **argv) { int threadid,Noofthreads; omp_set_num_threads(atoi(argv[1])); #pragma omp parallel private(threadid) { threadid = omp_get_thread_num(); printf("\n\t\t My thread id is : %d\n", threadid); } } <file_sep>#include<stdio.h> #include<mpi.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[]){ int rank, numprocs, src, dest, data, sum = 0; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); if(rank == 0){ MPI_Send(&rank, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); } else{ src = rank-1; MPI_Recv(&data, 1, MPI_INT, src, 0, MPI_COMM_WORLD, &status); sum = rank + data; printf("process no is %d and Sum is :%d\n",rank,sum); dest = (rank + 1)%numprocs; MPI_Send(&sum, 1, MPI_INT, dest, 0, MPI_COMM_WORLD); } if(rank==0){ src = numprocs-1; MPI_Recv(&sum, 1, MPI_INT, src, 0, MPI_COMM_WORLD, &status); printf("process no is %d and Sum is :0\n",rank); } MPI_Finalize(); return 0; } <file_sep>#include<bits/stdc++.h> #include<pthread.h> #include <unistd.h> using namespace std; pthread_mutex_t mutex; int con=0; class monitor { public: int s; pthread_cond_t notZero; //pthread_cond_init(&notZero,NULL); void wait(char id){ if(s==0) { printf("\t\tProcess %c blocked\n\n", id); pthread_cond_wait(&notZero,&mutex); } s=s-1; } void signal(){ s=s+1; pthread_cond_signal(&notZero); } monitor(){ s=1; pthread_cond_init(&notZero,NULL); //printf("dsgdf\n"); } }; monitor obj; void *callThread1(void *arg) { char *k=(char *)arg; char id=*k; while(1) { //monitor obj; //pthread_mutex_lock(&mutex); usleep(1000000); abc: obj.wait(id); //usleep(1000000); printf("========================\nprocess A is in critical section\n===========================\n\n"); usleep(1000000); printf("\t--------------------------------\n\tprocess A out of critical section\n\t--------------------------------\n\n"); obj.signal(); //pthread_mutex_unlock(&mutex); if(con%3!=0) usleep(1000000); else goto abc; con++; } } void *callThread2(void *arg) { char *k=(char *)arg; char id=*k; while(1) { //monitor obj; //pthread_mutex_lock(&mutex); usleep(1000000); obj.wait(id); //usleep(1000000); printf("========================\nprocess B is in critical section\n===========================\n\n"); usleep(1000000); printf("\t--------------------------------\n\tprocess B out of critical section\n\t--------------------------------\n\n"); obj.signal(); //pthread_mutex_unlock(&mutex); usleep(1000000); } } int main() { pthread_t tid1, tid2; char p='A', q='B'; pthread_mutex_init(&mutex,NULL); pthread_create(&tid1, NULL, &callThread1, &p); pthread_create(&tid2, NULL, &callThread2, &q); pthread_exit(NULL); pthread_mutex_destroy(&mutex); return 0; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<string.h> #include<mpi.h> #define Size 100 int main(int argc, char *argv[]) { int Myrank,NoOfProcess,i; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&Myrank); MPI_Comm_size(MPI_COMM_WORLD,&NoOfProcess); if(Myrank!=0) { char buf[]="Hello World!!"; int l=strlen(buf); printf("sending\n"); MPI_Send(buf,l,MPI_CHAR,0,0,MPI_COMM_WORLD); } else { char recbuf[200]; for(i=1;i<NoOfProcess;i++) { MPI_Recv(recbuf,200,MPI_CHAR,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&status); printf("P:%d Got data from processor %d \n",Myrank,status.MPI_SOURCE); } } MPI_Finalize(); return 0; } <file_sep>#include<stdio.h> #include<mpi.h> #include<stdlib.h> #include<string.h> int main(int argc, char *argv[]) { int rank, numprocs, src, dest, data, sum = 0; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); char buf[100]; int l; if(rank == 0) { strcpy(buf,"Hello world"); l=strlen(buf); } MPI_Bcast (buf,13, MPI_CHAR,0, MPI_COMM_WORLD); printf("Process %d Recieved %s\n",rank,buf); MPI_Finalize(); return 0; } <file_sep>#include<stdio.h> #include<stdlib.h> #include<omp.h> int main(int argc , char **argv) { int Threadid, Noofthreads,i; printf("Parallel execution:\n"); #pragma omp parallel for for(i=0;i<atoi(argv[1]);i++) { printf("Hello world iteration no. = %d \n",i); } printf("Sequential execution:\n"); for(i=0;i<atoi(argv[1]);i++) { printf("Hello world iteration no. = %d \n",i); } return 0; } <file_sep>#include<stdio.h> #include<pthread.h> int turn=0,timer=0,done1=0,done2=0; void *fun1(void *arg) { int *n=arg,i=0; int flag1=*n; while(1) { if(turn!=0) { while(turn!=0) { printf("0 is waiting at time= %d\n",timer); timer++; sleep(1); } } else { printf("0 is enjoying CS at time= %d\n",timer); timer++; turn=1; sleep(1); } i++; } done1=1; pthread_exit(NULL); } void *fun2(void *arg) { int *n=arg,i=0; int flag2=*n; while(1) { if(turn!=1) { while(turn!=1) { printf("1 is waiting at time= %d\n",timer); timer++; sleep(1); } } else { printf("1 is enjoying CS at time= %d\n",timer); timer++; turn=0; sleep(1); } i++; } done2=1; pthread_exit(NULL); } int main() { int i=0,j=1,k; pthread_t tid1,tid2; pthread_create(&tid1, NULL,fun1,&i); pthread_create(&tid2, NULL,fun2,&j); pthread_join(tid1,NULL); pthread_join(tid2,NULL); return 0; } <file_sep>#include<bits/stdc++.h> #include<pthread.h> #include <unistd.h> using namespace std; struct pnode{ int id; int val; }; pthread_mutex_t mutex, m; bool cmpfunc(struct pnode a, struct pnode b){ if(a.val==b.val)return a.id<b.id; return a.val>b.val; } class monitor { public: queue <int> printer; pthread_cond_t pro; void wait(int id, int *printer_no){ pthread_mutex_lock(&m); if(printer.empty()) { printf("\t\tProcess %d blocked\n\n", (int)id); pthread_mutex_unlock(&m); pthread_cond_wait(&pro, &mutex); pthread_mutex_lock(&m); } *printer_no = printer.front(); printer.pop(); pthread_mutex_unlock(&m); } void signal(int printer_no){ pthread_mutex_lock(&m); printer.push(printer_no); pthread_cond_signal(&pro); pthread_mutex_unlock(&m); } monitor(){ printer.push(1); printer.push(2); printer.push(3); pthread_cond_init(&pro, NULL); } }; monitor obj; void *callThread(void *arg) { int id = *(int *)arg; int printer_no; printf("Process %d requests printer\n\n", (int)id); obj.wait(id, &printer_no); printf("Process %d assigned printer %d\n\n", (int)id, printer_no); sleep(rand() % 10 + 1); obj.signal(printer_no); printf("Process %d release printer %d\n\n", (int)id, printer_no); } int main() { int n, i, no; cout << "Enter no. of processes: "; cin >> n; cout << "Enter priority for each process: "<<endl; pnode arr[1001]; for(i = 0; i < n; i++){ cout << "Process " << i+1 << "-"; arr[i].id=i+1; cin >> arr[i].val; } sort(arr, arr+n, cmpfunc); cout << "\tProcesses prioritywise: " << endl; for(i = 0; i < n; i++){ cout<<"\tProcess "<<arr[i].id<<endl; } pthread_t process[1000001]; pthread_mutex_init(&mutex, NULL); pthread_mutex_init(&m, NULL); int x = 0; while(1) { pthread_create(&process[x], NULL, &callThread, &(arr[x].id)); x=(x+1)%n; sleep(2); } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&m); pthread_exit(NULL); return 0; }
c855f42120f5b0c64fe5217d994f499334d3c2f6
[ "Markdown", "C", "C++" ]
34
C++
paraggoyal28/Concurrent_Parallel_Programming
b5d347933df6ebf5476e3220f9959acaff815fd3
ff730ecc69336f45fdc5166d4ba0b85afe4da3e8
refs/heads/master
<repo_name>Gyuuto/noise_canceler<file_sep>/noise_canceler/NoiseCancelerModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace noise_canceler { class NoiseCancelerModel { public int Delay { get; set; } public double LeftWeight { get; set; } public double RightWeight { get; set; } public double[] FreqWeight { get; set; } } } <file_sep>/noise_canceler/AudioOutputDevice.cs using LiveCharts; using LiveCharts.Wpf; using MathNet.Numerics; using MathNet.Numerics.IntegralTransforms; using NAudio.CoreAudioApi; using NAudio.Wave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; namespace noise_canceler { class AudioOutputDevice : AudioDevice { private WasapiLoopbackCapture source_stream; private WaveDataViewModel data_model; private List<double> left_val; private List<double> right_val; public static List<String> getOutputDevices () { return new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).Select(x => x.FriendlyName).ToList(); } public int get_sample_rate () { return source_stream.WaveFormat.SampleRate; } public List<double> get_left_val () { List<double> ret; lock (left_val) { ret = new List<double>(left_val); left_val.Clear(); } return ret; } public List<double> get_right_val () { List<double> ret; lock (right_val) { ret = new List<double>(right_val); right_val.Clear(); } return ret; } public AudioOutputDevice ( WaveDataViewModel data_model, int device_index ) { this.data_model = data_model; left_val = new List<double>(); right_val = new List<double>(); source_stream = new WasapiLoopbackCapture(new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)[device_index]); source_stream.DataAvailable += (obj, e) => { (List<Point>, List<Point>) points = convert_from_bytes(source_stream.WaveFormat.BitsPerSample, source_stream.WaveFormat.Channels, e.Buffer, e.BytesRecorded); lock ( left_val ) { left_val.AddRange(points.Item1.Select(x => x.Y).ToList()); } lock ( right_val ) { right_val.AddRange(points.Item2.Select(x => x.Y).ToList()); } /* var truncated_buffer_L = truncate_list(points.Item1.Select(x => x.Y).ToList(), 100); List<Point> truncated_points_L = new List<Point>(); for (int i = 0; i < truncated_buffer_L.Count; ++i) { truncated_points_L.Add(new Point() { Y = truncated_buffer_L[i], X = (double)i / truncated_buffer_L.Count }); } data_model.DataL.Clear(); data_model.DataL.AddRange(truncated_points_L); var freq_point_L = getFFT_points(source_stream.WaveFormat.SampleRate, points.Item1); data_model.FreqL.Clear(); data_model.FreqL.AddRange(freq_point_L.GetRange(0, 200).Select(x => new Point(x.Item1, x.Item2.Magnitude))); //*/ /* var truncated_buffer_R = truncate_list(points.Item2.Select(x => x.Y).ToList(), 100); List<Point> truncated_points_R = new List<Point>(); for (int i = 0; i < truncated_buffer_R.Count; ++i) { truncated_points_R.Add(new Point() { Y = truncated_buffer_R[i], X = (double)i / truncated_buffer_R.Count }); } data_model.DataR.Clear(); data_model.DataR.AddRange(truncated_points_R); var freq_point_R = getFFT_points(source_stream.WaveFormat.SampleRate, points.Item2); data_model.FreqR.Clear(); data_model.FreqR.AddRange(freq_point_R.GetRange(0, 200).Select(x => new Point(x.Item1, x.Item2.Magnitude))); /* NoiseCanceler nc = new NoiseCanceler(); var tmp = nc.apply_freq_weight(get_sample_rate(), right_val); var truncated_tmp = truncate_list(tmp, 100); List<Point> truncated_points_tmp = new List<Point>(); for (int i = 0; i < truncated_tmp.Count; ++i) { truncated_points_tmp.Add(new Point() { Y = truncated_tmp[i], X = (double)i / truncated_tmp.Count }); } data_model.DataOutput.Clear(); data_model.DataOutput.AddRange(truncated_points_tmp); var freq_tmp = getFFT_points(source_stream.WaveFormat.SampleRate, tmp.Select(x => new Point(0, x)).ToList()); data_model.FreqOutput.Clear(); data_model.FreqOutput.AddRange(freq_tmp.GetRange(0, 200).Select(x => new Point(x.Item1, x.Item2.Magnitude))); //*/ }; } ~AudioOutputDevice () { stop(); } public void start () { source_stream.StartRecording(); } public void stop () { source_stream.StopRecording(); } } } <file_sep>/noise_canceler/MainViewModel.cs using NAudio.Wave; using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Text; using System.Threading.Tasks; namespace noise_canceler { class MainViewModel { public List<string> AudioInputDevices { get; private set; } public List<string> AudioEnvironmentDevices { get; private set; } public List<string> AudioOutputDevices { get; private set; } public MainViewModel () { init_audio_device(); } private void init_audio_device () { AudioInputDevices = AudioInputDevice.getInputDevices(); AudioEnvironmentDevices = AudioOutputDevice.getOutputDevices(); AudioOutputDevices = AudioInputDevice.getOutputDevices(); } } } <file_sep>/noise_canceler/NoiseCanceler.cs using MathNet.Numerics; using MathNet.Numerics.IntegralTransforms; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace noise_canceler { class NoiseCanceler { private const int UPPER_FREQUENCY = 22000; private int delay; private double left_weight, right_weight; private double[] freq_weight; public NoiseCanceler() { delay = 0; left_weight = 0.5; right_weight = 0.5; freq_weight = new double[10]; // divide 10 parts /* freq_weight[0] = 0.1; // 0 - 2200 freq_weight[1] = 0.1; // 2200 - 4400 freq_weight[2] = 0.3; // 4400 - 6600 freq_weight[3] = 0.5; // 6600 - 8800 freq_weight[4] = 0.5; // 8800 - 11000 freq_weight[5] = 0.6; // 11000 - 13200 freq_weight[6] = 0.6; // 13200 - 15400 freq_weight[7] = 0.6; // 15400 - 17600 freq_weight[8] = 0.8; // 17600 - 19800 freq_weight[9] = 0.8; // 19800 - 22000 */ freq_weight[0] = 1.0; // 0 - 2200 freq_weight[1] = 1.0; // 2200 - 4400 freq_weight[2] = 1.0; // 4400 - 6600 freq_weight[3] = 1.0; // 6600 - 8800 freq_weight[4] = 1.0; // 8800 - 11000 freq_weight[5] = 1.0; // 11000 - 13200 freq_weight[6] = 1.0; // 13200 - 15400 freq_weight[7] = 1.0; // 15400 - 17600 freq_weight[8] = 1.0; // 17600 - 19800 freq_weight[9] = 1.0; // 19800 - 22000 } private List<double> convert_sample_rate(int before_length, int after_length, List<double> v) { List<double> ret = new List<double>(); for (int i = 0; i < after_length; ++i) { double idx = (double)(before_length - 1) / after_length * i; int a = (int)Math.Floor(idx), b = (int)Math.Ceiling(idx); double c = v[b] - v[a]; ret.Add(v[a] + c * (idx - a)); } return ret; } public List<double> get_noise_canceled_buffer ( int sampling_rate_env, List<double> left_env, List<double> right_env, int sampling_rate_source, List<double> source ) { using ( var writer = new StreamWriter("output.txt", true) ) { for ( int i = 0; i < Math.Max(left_env.Count, Math.Max(right_env.Count, source.Count)); ++i ) { writer.WriteLine(String.Format("{0} {1} {2}", (i < left_env.Count ? left_env[i] : 0.0), (i < right_env.Count ? right_env[i] : 0.0), (i < source.Count ? source[i] : 0.0))); } writer.WriteLine(""); } List<double> ret = new List<double>(); List<double> calced_left = apply_freq_weight(sampling_rate_env, left_env); List<double> calced_right = apply_freq_weight(sampling_rate_env, right_env); for ( int i = 0; i < source.Count; ++i ) { ret.Add(source[i]); } for ( int i = 0; i < left_env.Count; ++i ) { if (i - delay < 0 || ret.Count <= i ) continue; ret[i - delay] -= left_weight * calced_left[i]; } for ( int i = 0; i < right_env.Count; ++i ) { if (i - delay < 0 || ret.Count <= i) continue; ret[i - delay] -= right_weight * calced_right[i]; } /* for ( int i = 0; i < ret.Count; ++i ) { ret[i] = Math.Min(1.0, Math.Max(-1.0, ret[i])); } */ return ret; } public List<double> apply_freq_weight ( int sampling_rate, List<double> v ) { Complex[] buf = prepare_complex_array(v); Fourier.Forward(buf, FourierOptions.Matlab); for ( int i = 0; i < buf.Length/2; ++i ) { double freq = (double)i * sampling_rate / buf.Length; int freq_idx = Math.Min(freq_weight.Length - 1, (int)(freq / (UPPER_FREQUENCY / freq_weight.Length))); buf[i] *= (float)freq_weight[freq_idx]; buf[buf.Length-i-1] *= (float)freq_weight[freq_idx]; } Fourier.Inverse(buf, FourierOptions.Matlab); return buf.Select(x => (double)x.Real).ToList(); } private Complex[] prepare_complex_array ( List<double> v ) { Complex[] ret = new Complex[v.Count]; for (int i = 0; i < v.Count; ++i) ret[i] = new Complex(v[i], 0.0); return ret; } } } <file_sep>/noise_canceler/WaveDataViewModel.cs using LiveCharts; using LiveCharts.Configurations; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace noise_canceler { class WaveDataViewModel { public ChartValues<Point> DataL { get; set; } public ChartValues<Point> DataR { get; set; } public ChartValues<Point> FreqL { get; set; } public ChartValues<Point> FreqR { get; set; } public ChartValues<Point> DataOutput { get; set; } public ChartValues<Point> FreqOutput { get; set; } public Func<double, string> XFormatter { get; set; } public Func<double, string> YFormatter { get; set; } public WaveDataViewModel() { Charting.For<Point>(Mappers.Xy<Point>().X(model => model.X).Y(model => model.Y)); DataL = new ChartValues<Point>(); DataR = new ChartValues<Point>(); FreqL = new ChartValues<Point>(); FreqR = new ChartValues<Point>(); DataOutput = new ChartValues<Point>(); FreqOutput = new ChartValues<Point>(); XFormatter = x => x.ToString(); YFormatter = y => y.ToString(); } } } <file_sep>/noise_canceler/MainWindow.xaml.cs using LiveCharts; using LiveCharts.Wpf; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace noise_canceler { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { private AudioInputDevice input_device; private AudioOutputDevice env_device; private WaveDataViewModel wave_data_model_input; private WaveDataViewModel wave_data_model_env; public MainWindow() { InitializeComponent(); wave_data_model_env = new WaveDataViewModel(); env_device = new AudioOutputDevice(wave_data_model_env, 0); audio_env_grid.DataContext = wave_data_model_env; wave_data_model_input = new WaveDataViewModel(); input_device = new AudioInputDevice(wave_data_model_input, env_device, 0, 0); audo_input_grid.DataContext = wave_data_model_input; init_event(); } private void init_event() { this.comboBox_input.SelectionChanged += (sender, e) => { ComboBox cur_cb = (ComboBox)sender; input_device = new AudioInputDevice(wave_data_model_input, env_device, cur_cb.SelectedIndex, comboBox_output.SelectedIndex); }; this.comboBox_speaker.SelectionChanged += (sender, e) => { ComboBox cur_cb = (ComboBox)sender; env_device = new AudioOutputDevice(wave_data_model_env, cur_cb.SelectedIndex); }; this.comboBox_output.SelectionChanged += (sender, e) => { ComboBox cur_cb = (ComboBox)sender; input_device = new AudioInputDevice(wave_data_model_input, env_device, comboBox_input.SelectedIndex, cur_cb.SelectedIndex); }; this.button_start.Click += (sender, e) => { input_device.start(); env_device.start(); }; this.button_stop.Click += (sender, e) => { input_device.stop(); env_device.stop(); }; } } } <file_sep>/noise_canceler/AudioInputDevice.cs using LiveCharts; using LiveCharts.Wpf; using MathNet.Numerics; using MathNet.Numerics.IntegralTransforms; using NAudio.Wave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Threading; namespace noise_canceler { class AudioInputDevice : AudioDevice { private AudioOutputDevice environment; private WaveIn source_stream; private WaveOut dest; private BufferedWaveProvider wave_provider; private WaveDataViewModel data_model; private NoiseCanceler noise_canceler; public List<double> val { get; private set; } public static List<string> getInputDevices () { List<string> ret = new List<string>(); List<WaveInCapabilities> sources = new List<WaveInCapabilities>(); for (int i = 0; i < WaveIn.DeviceCount; ++i) sources.Add(WaveIn.GetCapabilities(i)); foreach (var source in sources) { ret.Add(source.ProductName); } return ret; } public static List<string> getOutputDevices () { List<string> ret = new List<string>(); List<WaveOutCapabilities> sources = new List<WaveOutCapabilities>(); for (int i = 0; i < WaveOut.DeviceCount; ++i) sources.Add(WaveOut.GetCapabilities(i)); foreach (var source in sources) { ret.Add(source.ProductName); } return ret; } public AudioInputDevice ( WaveDataViewModel data_model, AudioOutputDevice environment, int input_device_index, int output_device_index ) { this.data_model = data_model; noise_canceler = new NoiseCanceler(); source_stream = new NAudio.Wave.WaveIn(); source_stream.DeviceNumber = input_device_index; source_stream.WaveFormat = new WaveFormat(44100, 24, 1); dest = new NAudio.Wave.WaveOut(); dest.DeviceNumber = output_device_index; dest.DesiredLatency = 100; wave_provider = new BufferedWaveProvider(source_stream.WaveFormat); wave_provider.DiscardOnBufferOverflow = true; dest.Init(wave_provider); int cnt = 0; List<double> buffers = new List<double>(); source_stream.DataAvailable += (obj, e) => { /* var truncated_points = get_point_from_bytes(e.Buffer, e.BytesRecorded); data_model.DataL.Clear(); data_model.DataL.AddRange(truncated_points); var freq_point = getFFT_points(source_stream.WaveFormat.SampleRate, convert_from_bytes(source_stream.WaveFormat.BitsPerSample, source_stream.WaveFormat.Channels, e.Buffer, e.BytesRecorded).Item1); data_model.FreqL.Clear(); data_model.FreqL.AddRange(freq_point.GetRange(0, 200).Select(x => new Point(x.Item1, x.Item2.Magnitude))); //*/ //////////////////////////////////////////////////////////////////////////////////////////////////// List<double> source_point = convert_from_bytes(source_stream.WaveFormat.BitsPerSample, source_stream.WaveFormat.Channels, e.Buffer, e.BytesRecorded).Item1 .Select(x => x.Y) .ToList(); List<double> canceled_buf = noise_canceler.get_noise_canceled_buffer(environment.get_sample_rate(), environment.get_left_val(), environment.get_right_val(), source_stream.WaveFormat.SampleRate, source_point); byte[] result = convert_from_list(dest.OutputWaveFormat.BitsPerSample, dest.OutputWaveFormat.Channels, canceled_buf).Item1; wave_provider.AddSamples(result, 0, result.Length); /* var truncated_points = get_point_from_bytes(result, result.Length); data_model.DataOutput.Clear(); data_model.DataOutput.AddRange(truncated_points); var freq_point = getFFT_points(dest.OutputWaveFormat.SampleRate, convert_from_bytes(dest.OutputWaveFormat.BitsPerSample, dest.OutputWaveFormat.Channels, result, result.Length).Item1); data_model.FreqOutput.Clear(); data_model.FreqOutput.AddRange(freq_point.GetRange(0, 200).Select(x => new Point(x.Item1, x.Item2.Magnitude))); //*/ }; } ~AudioInputDevice () { stop(); } private List<Point> get_point_from_bytes ( byte[] buffer, int length ) { (List<Point>, List<Point>) points = convert_from_bytes(source_stream.WaveFormat.BitsPerSample, source_stream.WaveFormat.Channels, buffer, length); val = points.Item1.Select(x => x.Y).ToList(); var truncated_buffer = truncate_list(points.Item1.Select(x => x.Y).ToList(), 100); List<Point> truncated_points = new List<Point>(); for (int i = 0; i < truncated_buffer.Count; ++i) { truncated_points.Add(new Point() { Y = truncated_buffer[i], X = (double)i / truncated_buffer.Count }); } return truncated_points; } public void start () { source_stream.StartRecording(); dest.Play(); } public void stop () { source_stream.StopRecording(); dest.Stop(); } } } <file_sep>/noise_canceler/AudioDevice.cs using MathNet.Numerics; using MathNet.Numerics.IntegralTransforms; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using System.Windows; namespace noise_canceler { class AudioDevice { protected (List<Point>, List<Point>) convert_from_bytes(int bits_per_sample, int channel, byte[] buffer, int length) { var left_points = new List<Point>(); var right_points = new List<Point>(); int bytes = bits_per_sample / 8; double max_x = length / bytes; double min_y = -(1L << (bytes * 8 - 1)), max_y = (1L << (bytes * 8 - 1)) - 1; for (int i = 0; i < length / bytes; ++i) { if (bytes != 4) { int val = 0; if (bytes == 2) val = BitConverter.ToInt16(buffer, bytes * i); else if (bytes == 3) { bool is_negative = (buffer[bytes * i + 2] & 0x80) != 0; val = (is_negative ? ~buffer[bytes * i + 2] & 0xFF : buffer[bytes * i + 2]); val <<= 8; val += (is_negative ? ~buffer[bytes * i + 1] & 0xFF : buffer[bytes * i + 1]); val <<= 8; val += (is_negative ? (~buffer[bytes * i] & 0xFF) + 1 : buffer[bytes * i]); if (is_negative) val = -val; } if (i % channel == 0) left_points.Add(new Point(i / max_x, Math.Max(0.0, Math.Min(1.0, (val - min_y) / (max_y - min_y))) * 2 - 1)); else right_points.Add(new Point(i / max_x, Math.Max(0.0, Math.Min(1.0, (val - min_y) / (max_y - min_y))) * 2 - 1)); } else { float val = BitConverter.ToSingle(buffer, bytes * i); if (i % channel == 0) left_points.Add(new Point(i / max_x, val)); else right_points.Add(new Point(i / max_x, val)); } } return (left_points, right_points); } protected (byte[], byte[]) convert_from_list(int bits_per_sample, int channel, List<double> v_l, List<double> v_r = null ) { int bytes = bits_per_sample / 8; var left_ret = new byte[bytes*v_l.Count]; var right_ret = new byte[bytes * (v_r?.Count ?? 0)]; int min = -(1 << (bits_per_sample - 1)), max = (1 << (bits_per_sample - 1)) - 1; for (int i = 0; i < v_l.Count; ++i) { int val = (int)((v_l[i] + 1)/2.0 * (max - min) - min); for (int j = 0; j < bytes; ++j) left_ret[bytes * i + j] = (byte)((val & (0xFF << (j * 8))) >> (j * 8)); } for (int i = 0; i < (v_r?.Count ?? 0); ++i) { int val = (int)((v_r[i] + 1) / 2.0 * max - min); for (int j = 0; j < bytes; ++j) right_ret[bytes * i + j] = (byte)((val & (0xFF << (j * 8))) >> (j * 8)); } return (left_ret, right_ret); } protected List<double> truncate_list(List<double> buffer, int length) { List<double> ret = new List<double>(); for (int i = 0; i < buffer.Count / length; ++i) { double sum = 0; for (int j = 0; j < length; ++j) { sum += buffer[i * length + j]; } ret.Add(sum / length); } return ret; } protected List<(double, Complex)> getFFT_points ( int sample_rate, List<Point> points ) { var freq = new Complex[points.Count]; for (int i = 0; i < points.Count; ++i) freq[i] = new Complex((float)points[i].Y, 0); Fourier.Forward(freq, FourierOptions.Matlab); var freq_point = new List<(double, Complex)>(); for (int i = 0; i < freq.Length; ++i) { freq_point.Add(((double)i * sample_rate / freq.Length, freq[i])); } return freq_point; } } }
cba247ca71fb146400c53461028c592698a8a356
[ "C#" ]
8
C#
Gyuuto/noise_canceler
4576e12b7aba7d02a135bd93a11ecb6a95a11c81
ab7cc7ab3c6a67dbc6ea0978a32a23dd91a1592d
refs/heads/master
<repo_name>Storh/gradproj-comegg<file_sep>/app/service/content/activity.js 'use strict'; const Service = require('egg').Service; class ActivityService extends Service { async getListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; const sqlstr = `SELECT a.regist_id,a.user_id,a.add_time,a.remark, b.nickname,b.headimgurl FROM ${this.app.config.dbprefix}activity_regist a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${reqData.content_id} AND a.is_delete = 0 AND a.state = 1 ORDER BY a.regist_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); if (item.reply_time) item.reply_time = this.ctx.service.base.fromatDate(new Date(item.reply_time).getTime()); return item; }); return list; } // 获取动态内容 async getDetailById(user_id, content_id) { // 动态内容(1)用户参与(2)评论(3) // 点赞类型 const likeType = 1; const sqlstr = `SELECT a.content_id,a.type_id,a.title,a.content,a.keyword,a.show_type,a.visit_num,a.like_num,a.collect_num,a.add_time,a.link_external_name,a.link_external_url, b.user_id,b.phone,b.nickname,b.headimgurl,b.personal_signature, c.closing_date,c.num_upper_limit, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state, if((SELECT collect_state FROM ${this.app.config.dbprefix}collect_record WHERE rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS collect_state FROM ${this.app.config.dbprefix}content_record a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id LEFT JOIN ${this.app.config.dbprefix}activity_content c ON c.content_id = a.content_id WHERE a.content_id = ${content_id} AND a.is_delete = 0 AND a.state = 1`; const results = await this.app.mysql.query(sqlstr); const data = JSON.parse(JSON.stringify(results[0])); if (data.headimgurl.length < 100) { data.headimgurl = this.app.config.publicAdd + data.headimgurl; } return data; } async add(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const closing_date = new Date(reqData.closing_date); const num_upper_limit = reqData.num_upper_limit; const district_id = userInfo.district_id; let content_id; const trans_success = await app.mysql.beginTransactionScope(async addmain => { const add_main_log = await addmain.insert(app.config.dbprefix + 'content_record', { type_id: 4, user_id, district_id, title, content, show_type, keyword, link_external_name, link_external_url, add_time: date_now, }); content_id = add_main_log.insertId; // 插入活动内容表 addmain.insert(app.config.dbprefix + 'activity_content', { content_id, closing_date, num_upper_limit, }); // 关键字 if (keyword) { const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); } // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); await addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id, }, { where: { type_id: uploadType, user_id, file_id: photoIdArr, }, }); } return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return content_id; } async edit(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const content_id = reqData.content_id; const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const closing_date = new Date(reqData.closing_date); const num_upper_limit = reqData.num_upper_limit; const trans_success = await app.mysql.beginTransactionScope(async addmain => { // 更新动态内容表 addmain.update(app.config.dbprefix + 'content_record', { title, content, show_type, keyword, link_external_name, link_external_url, modify_time: date_now, }, { where: { content_id, user_id, }, }); // 更新活动内容表 addmain.update(app.config.dbprefix + 'activity_content', { closing_date, num_upper_limit, }, { where: { content_id, }, }); // 关键字 await addmain.delete(app.config.dbprefix + 'content_keyword', { content_id, }); if (keyword) { const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); } // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); // 删除原来存储的图片 const delstr = `SELECT * FROM ${app.config.dbprefix}upload_file_record WHERE type_id=${uploadType} AND user_id=${user_id} AND rel_id=${content_id} AND file_id NOT IN (${photoIdArr.toString()})`; const dellist = await addmain.query(delstr); dellist.forEach(item => { addmain.delete(app.config.dbprefix + 'upload_file_record', { file_id: item.file_id, }); }); await addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id, }, { where: { type_id: uploadType, user_id, file_id: photoIdArr, }, }); } return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return true; } async registAdd(user_id, reqData) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const is_regist = await this.app.mysql.get(this.app.config.dbprefix + 'activity_regist', { user_id, content_id: reqData.content_id, is_delete: 0, state: 1, }); if (is_regist) this.ctx.throw('您已参与过了这次活动了'); const active_info = await this.app.mysql.get(this.app.config.dbprefix + 'activity_content', { content_id: reqData.content_id, }); const activity_content = JSON.parse(JSON.stringify(active_info)); const closing_date = activity_content.closing_date; const num_upper_limit = activity_content.num_upper_limit; if (new Date(closing_date).getTime() - new Date().getTime() <= 0) this.ctx.throw('很抱歉,该活动已结束,请关注下次活动'); const limirsql = `SELECT count(*) as nums FROM ${this.app.config.dbprefix}activity_regist WHERE 1 AND is_delete = 0 AND state = 1 AND content_id = ${reqData.content_id}`; const row = await this.app.mysql.query(limirsql); const limitusernum = JSON.parse(JSON.stringify(row[0])); if (limitusernum.nums + 1 > num_upper_limit) this.ctx.throw('很抱歉,该活动已达参与人数上限,谢谢您的参与,请关注下次活动'); const remark = reqData.remark; const regist_log = await this.app.mysql.insert(this.app.config.dbprefix + 'activity_regist', { user_id, content_id: reqData.content_id, remark, add_time: date_now, }); if (regist_log) { // 通知 this.registAddPostNotice(user_id, reqData.content_id, regist_log.insertId); return regist_log.insertId; } this.ctx.throw('提交失败'); } async registAddPostNotice(user_id, content_id, regist_id) { // SYSTEM系统通知(1);CONTENT_REGIST内容参与记录(2);CONTENT_REVIEW内容评论记录(3);TYPE_LIKE点赞(4); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const contentInfo = await this.ctx.service.common.getContentInfoById(content_id); const noticedata = { type_id: 2, receive_user_id: contentInfo.user_id, start_user_id: user_id, rel_id: regist_id, content_id, regist_id, content_type: contentInfo.type_id, title: userInfo.nickname + '参与了你的' + this.app.config.contentType[contentInfo.type_id - 1].name, desc: contentInfo.content, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } } module.exports = ActivityService; <file_sep>/app/router.js 'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.prefix('/app'); router.post('/', controller.member.phoneLogin.login);// 测试接口 router.post('/member/phoneLogin/bindPhone', controller.member.phoneLogin.bindPhone);// 1.1.3、 手机号注册登录 router.post('/member/info/reg', app.jwt, controller.member.info.reg);// 1.1.6、 注册后完善用户信息 router.post('/content/main/getList', app.jwt, controller.content.main.getList);// 1.2.1、 获取动态记录列表 router.post('/content/main/getDetailById', app.jwt, controller.content.main.getDetailById);// 1.2.2、 获取动态记录详情 router.post('/content/activity/getDetailById', app.jwt, controller.content.activity.getDetailById);// 1.2.3、 获取动态记录详情(活动) router.post('/content/activity/getListById', app.jwt, controller.content.activity.getListById);// 1.2.4、 获取活动参与列表(活动-用户) router.post('/content/pack/getDetailById', app.jwt, controller.content.pack.getDetailById);// 1.2.5、 获取动态记录详情(拼团) router.post('/content/pack/getListById', app.jwt, controller.content.pack.getListById);// 1.2.6、 获取拼团参与列表(拼团-用户) router.post('/content/pack/getGoodsListById', app.jwt, controller.content.pack.getGoodsListById);// 1.2.7、 获取拼团商品列表(拼团-商品) router.post('/content/pack/getOrderListById', app.jwt, controller.content.pack.getOrderListById);// 1.2.8、 获取拼团参与列表(拼团-订单) router.post('/content/pack/getSelfGoodsInfoById', app.jwt, controller.content.pack.getSelfGoodsInfoById);// 1.2.9、 获取拼团商品列表(拼团-商品明细) router.post('/content/help/getListById', app.jwt, controller.content.help.getListById);// 1.2.10、 获取互助参与详情列表 router.post('/content/question/getListById', app.jwt, controller.content.question.getListById);// 1.2.11、 获取问答参与详情列表 router.post('/content/unused/getListById', app.jwt, controller.content.unused.getListById);// 1.2.12、 获取闲置参与详情列表 router.post('/content/topic/getListById', app.jwt, controller.content.topic.getListById);// 1.2.13、 获取话题参与详情列表 router.post('/content/main/add', app.jwt, controller.content.main.add);// 1.2.14、 提交发布动态接口 router.post('/content/activity/add', app.jwt, controller.content.activity.add);// 1.2.15、 提交发布动态接口(活动) router.post('/content/pack/add', app.jwt, controller.content.pack.add);// 1.2.16、 提交发布动态接口(拼团) router.post('/content/main/edit', app.jwt, controller.content.main.edit);// 1.2.17、 编辑动态接口 router.post('/content/activity/edit', app.jwt, controller.content.activity.edit);// 1.2.18、 编辑动态接口(活动) router.post('/content/pack/edit', app.jwt, controller.content.pack.edit);// 1.2.19、 编辑动态接口(拼团) router.post('/content/review/getListById', app.jwt, controller.content.review.getListById);// 1.2.21、 获取动态记录评论列表 router.post('/content/review/add', app.jwt, controller.content.review.add);// 1.2.22、 为动态添加评论接口 router.post('/content/review/reply', app.jwt, controller.content.review.reply);// 1.2.23、 回复评论接口 router.post('/content/review/delete', app.jwt, controller.content.review.delete);// 1.2.24、 删除评论接口 router.post('/content/help/registAdd', app.jwt, controller.content.help.registAdd);// 1.2.26、 会员参与互助接口 router.post('/content/help/registReply', app.jwt, controller.content.help.registReply);// 1.2.27、 会员参与互助回复接口 router.post('/content/question/registAdd', app.jwt, controller.content.question.registAdd);// 1.2.30、 会员参与问答接口 router.post('/content/question/registReply', app.jwt, controller.content.question.registReply);// 1.2.31、 会员参与问答回复接口 router.post('/content/unused/registAdd', app.jwt, controller.content.unused.registAdd);// 1.2.34、 会员参与闲置接口 router.post('/content/unused/registReply', app.jwt, controller.content.unused.registReply);// 1.2.35、 会员参与闲置回复接口 router.post('/content/activity/registAdd', app.jwt, controller.content.activity.registAdd);// 1.2.38、 会员参与活动接口 router.post('/content/pack/registAdd', app.jwt, controller.content.pack.registAdd);// 1.2.39、 会员参与拼团接口 router.post('/content/topic/registAdd', app.jwt, controller.content.topic.registAdd);// 1.2.40、 会员参与话题接口 router.post('/content/topic/registReply', app.jwt, controller.content.topic.registReply);// 1.2.41、 会员参与话题回复接口 router.post('/content/main/setLike', app.jwt, controller.content.main.setLike);// 1.2.44、 为动态点赞 router.post('/content/regist/setLike', app.jwt, controller.content.regist.setLike);// 1.2.45、 为参与内容点赞 router.post('/content/review/setLike', app.jwt, controller.content.review.setLike);// 1.2.46、 为评论点赞 router.post('/content/main/setCollect', app.jwt, controller.content.main.setCollect);// 1.2.47、 收藏动态 router.post('/addressBook/main/getList', app.jwt, controller.member.info.addressBookList);// 1.3.1、 获取通讯录列表 router.post('/notice/main/getList', app.jwt, controller.notice.getList);// 1.4.1、 获取通知列表 router.post('/notice/main/setRead', app.jwt, controller.notice.setRead);// 1.4.2、 标记通知已读状态 router.post('/notice/official/getDetailById', app.jwt, controller.notice.getDetailById);// 1.4.3、 获取系统通知详情 router.post('/member/info/getInfo', app.jwt, controller.member.info.getInfo);// 1.5.1、 获取用户基本信息 router.post('/member/info/edit', app.jwt, controller.member.info.edit);// 1.5.2、 编辑用户信息 router.post('/member/content/getListBySelf', app.jwt, controller.member.content.getListBySelf);// 1.5.3、 用户发起的动态列表 router.post('/member/contentPack/getListBySelf', app.jwt, controller.member.content.getPackListBySelf);// 1.5.4、 用户发起的动态列表(拼团) router.post('/member/content/getListByRegist', app.jwt, controller.member.content.getListByRegist);// 1.5.5、 用户参与的动态列表 router.post('/member/contentPack/getListByRegist', app.jwt, controller.member.content.getPackListByRegist);// 1.5.6、 用户参与的动态列表(拼团) router.post('/member/collect/getList', app.jwt, controller.member.content.getCollectList);// 1.5.7、 我收藏的动态列表 router.post('/baseData/distList', app.jwt, controller.baseData.distList);// 1.6.1、 获取街道小区列表 router.post('/baseData/specialityList', app.jwt, controller.baseData.specialityList);// 1.6.2、 获取职业特长列表 router.post('/baseData/hobbyList', app.jwt, controller.baseData.hobbyList);// 1.6.3、 获取业余爱好列表 router.post('/uploadFile/uploadPhoto', app.jwt, controller.baseData.uploadPhoto);// 1.7.1、 上传图片通用接口 }; <file_sep>/app/controller/member/content.js 'use strict'; const Controller = require('egg').Controller; class ContentController extends Controller { // 用户发起的动态列表 async getListBySelf() { const { ctx } = this; const user_id = ctx.request.body.user_id ? ctx.request.body.user_id : ctx.state.user.user_id; const reqData = ctx.request.body; const list = await ctx.service.member.content.getListBySelf(user_id, reqData); ctx.body = { data: { list }, }; } // 用户发起的动态列表(拼团) async getPackListBySelf() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; const list = await ctx.service.member.content.getPackListBySelf(user_id, reqData); ctx.body = { data: { list }, }; } // 用户参与的动态列表 async getListByRegist() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_type) { this.ctx.throw('内容类型不能为空'); } const list = await ctx.service.member.content.getListByRegist(user_id, reqData); ctx.body = { data: { list }, }; } // 用户参与的动态列表(拼团) async getPackListByRegist() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; reqData.content_type = 5; const list = await ctx.service.member.content.getListByRegist(user_id, reqData); ctx.body = { data: { list }, }; } // 我收藏的动态列表 async getCollectList() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; const list = await ctx.service.member.content.getCollectList(user_id, reqData); ctx.body = { data: { list }, }; } } module.exports = ContentController; <file_sep>/app/controller/member/phoneLogin.js 'use strict'; const Controller = require('egg').Controller; class PhoneLoginController extends Controller { async bindPhone() { const { ctx } = this; const phone_passw = ctx.request.body; if (phone_passw.passWord && phone_passw.phone) { const data = await ctx.service.login.authUserInfoLogin(phone_passw); ctx.body = { data }; } else { this.ctx.throw('登录数据不完整'); } } async login() { const { ctx, app } = this; const abody = app.config.jwt.secret; // console.log(app.config.dbprefix); const token = app.jwt.sign({ user_id: 1 }, app.config.jwt.secret, { expiresIn: '3 days' }); // app.jwt.sign({ foo: 'bar' }, app.config.jwt.secret, { expiresIn: '3 days' }); // const token = app.jwt.sign({ foo: 'bar' }, app.config.jwt.secret, { expiresIn: 10 }); // this.ctx.throw('有猫饼', { data: { token }, myErrType: 255 }); // this.ctx.throw('有猫饼', { data: { token } }); // const result = await this.app.mysql.get(this.app.config.dbprefix + 'user_profile', { user_id: 369, state: 1 }); // const resultarr = [ result ]; // const resultarr = await this.app.mysql.select(app.config.dbprefix + 'upload_file_record', { // columns: [ 'src' ], // }); // const resultmap = resultarr.map(item => { // if (item.src) { // item.src = 'http://www.chinaclick.com.cn/ailin/' + item.src; // } // return item.src; // }); // const str = resultmap.toString(); // const link = str.replace(/,/g, ` // `); // const resultmap = resultarr.map(item => { // if (item.add_time) { // item.add_time = new Date(item.add_time).toLocaleString(); // } // return item; // }); // console.log(result); // const abody = await ctx.service.helper.getNameFirstCharter('W'); ctx.body = { token, abody, // resultmap, // link, }; } } module.exports = PhoneLoginController; <file_sep>/app/service/content/unused.js 'use strict'; const Service = require('egg').Service; class UnusedService extends Service { async getListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; // 用户的点赞类型 动态内容(1)'SET_LIKE_CONTENT'; 用户参与(2)'SET_LIKE_REGIST';评论(3)'SET_LIKE_REVIEW' const likeType = 2; const contentType = this.app.config.contentTypeIdByName.UNUSED; const sqlstr = `SELECT a.regist_id,a.user_id,a.add_text,a.reply_text,a.add_time,a.reply_time,a.like_num, b.nickname,b.headimgurl, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND content_type = ${contentType} AND rel_id = a.regist_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state FROM ${this.app.config.dbprefix}unused_regist a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${reqData.content_id} AND a.is_delete = 0 AND a.state = 1 ORDER BY a.regist_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); if (item.reply_time) item.reply_time = this.ctx.service.base.fromatDate(new Date(item.reply_time).getTime()); return item; }); return list; } async registAdd(user_id, reqData) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const regist_log = await this.app.mysql.insert(this.app.config.dbprefix + 'unused_regist', { user_id, content_id: reqData.content_id, add_text: reqData.add_text, add_time: date_now, }); if (regist_log) { // 通知 this.ctx.service.content.help.registAddPostNotice(user_id, reqData.content_id, regist_log.insertId, reqData.add_text); return regist_log.insertId; } this.ctx.throw('提交失败'); } } module.exports = UnusedService; <file_sep>/app/service/content/review.js 'use strict'; const Service = require('egg').Service; class ReviewService extends Service { async getListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; // 用户的点赞类型 动态内容(1)'SET_LIKE_CONTENT'; 用户参与(2)'SET_LIKE_REGIST';评论(3)'SET_LIKE_REVIEW' const likeType = 3; const sqlstr = `SELECT a.review_id,a.user_id,a.review_text,a.reply_text,a.add_time,a.reply_time,a.like_num, b.nickname,b.headimgurl, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND rel_id = a.review_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state FROM ${this.app.config.dbprefix}review_record a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${reqData.content_id} AND a.is_delete = 0 AND a.state = 1 ORDER BY a.review_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); if (item.reply_time) item.reply_time = this.ctx.service.base.fromatDate(new Date(item.reply_time).getTime()); return item; }); return list; } async add(user_id, reqData) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const review_log = await this.app.mysql.insert(this.app.config.dbprefix + 'review_record', { user_id, content_id: reqData.content_id, review_text: reqData.review_text, add_time: date_now, }); if (review_log) { // 通知 this.addPostNotice(user_id, reqData.content_id, review_log.insertId, reqData.review_text); return review_log.insertId; } this.ctx.throw('提交失败'); } async addPostNotice(user_id, content_id, review_id, review_text) { // SYSTEM系统通知(1);CONTENT_REGIST内容参与记录(2);CONTENT_REVIEW内容评论记录(3);TYPE_LIKE点赞(4); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const contentInfo = await this.ctx.service.common.getContentInfoById(content_id); const noticedata = { type_id: 3, receive_user_id: contentInfo.user_id, start_user_id: user_id, rel_id: review_id, content_id, regist_id: review_id, title: userInfo.nickname + '评论了你的' + this.app.config.contentType[contentInfo.type_id - 1].name, desc: review_text, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } async setLike(user_id, reqData) { const like_state = Number(reqData.like_state); // 获取动态内容 const { ctx, app } = this; const reviewBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + 'review_record', { review_id: reqData.review_id, state: 1, is_delete: 0, }); const reviewBaseInfo = JSON.parse(JSON.stringify(reviewBaseInfoRow)); const content_id = reviewBaseInfo.content_id; const receive_user_id = reviewBaseInfo.user_id; const desc = reviewBaseInfo.review_text; const like_num_ori = reviewBaseInfo.like_num; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const contentInfo = await this.ctx.service.common.getContentInfoById(content_id); if (!contentInfo) { this.ctx.throw('该动态记录不存在'); } const content_type = contentInfo.type_id; // 自动事务 let like_state_ori; let like_id; const trans_success = await app.mysql.beginTransactionScope(async sqlrevsetlike => { // 读取点赞记录 // SET_LIKE_CONTENT动态内容(1); SET_LIKE_REGIST用户参与(2);SET_LIKE_REVIEW评论(3) const type = 3; const is_setlike_log = await sqlrevsetlike.get(this.app.config.dbprefix + 'like_record', { type_id: type, user_id, rel_id: reqData.review_id, }); if (!is_setlike_log) { // 未设置喜欢 if (like_state === 0) { ctx.throw('您还未点赞'); } else { like_state_ori = -1; const set_like_log = await sqlrevsetlike.insert(app.config.dbprefix + 'like_record', { type_id: type, user_id, rel_id: reqData.review_id, content_type, like_state, add_time: date_now, }); if (set_like_log) { like_id = set_like_log.insertId; } else { ctx.throw('操作失败'); } } } else { const setlike_log = JSON.parse(JSON.stringify(is_setlike_log)); like_id = setlike_log.like_id; like_state_ori = setlike_log.like_state; await sqlrevsetlike.update(app.config.dbprefix + 'like_record', { like_state, modify_time: date_now, }, { where: { like_id } }); } // 更新动态内容表 if (like_state_ori !== like_state) { // 原始喜欢记录和这次是喜欢状态不同 // 根据这次的点赞状态设置偏移数 const like_num_offset = like_state === 1 ? 1 : -1; if (like_num_ori === 0 && like_num_offset < 0) { console.log('中奖了'); } else { const sqlstr = `UPDATE ${app.config.dbprefix}review_record SET like_num = like_num + (${like_num_offset}) WHERE review_id = ${reqData.review_id}`; await sqlrevsetlike.query(sqlstr); } } return true; }, ctx); if (!trans_success) { ctx.throw('操作失败,请重试'); } if (like_state === 1 && like_state_ori !== like_state) { // 添加通知 this.setLikePostNotice(user_id, like_id, content_id, reqData.review_id, receive_user_id, content_type, desc); } return true; } async setLikePostNotice(user_id, rel_id, content_id, review_id, receive_user_id, content_type, desc) { // (1)NOTICE_RECORD_TYPE_SYSTEM系统通知;(2)NOTICE_RECORD_TYPE_CONTENT_REGIST内容参与记录; // (3)NOTICE_RECORD_TYPE_CONTENT_REVIEW内容评论记录;(4)NOTICE_RECORD_TYPE_LIKE点赞; const userInfo = await this.ctx.service.member.info.getInfo(user_id); const noticedata = { type_id: 4, receive_user_id, start_user_id: user_id, rel_id, content_id, regist_id: review_id, content_type, title: userInfo.nickname + '点赞了你评论的' + this.app.config.contentType[content_type - 1].name, desc, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } async delete(user_id, review_id) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const delinfo = await this.app.mysql.update(this.app.config.dbprefix + 'user_profile', { state: 2, update_state_user_time: date_now, }, { where: { user_id, review_id, }, }); if (delinfo) { return true; } this.ctx.throw('删除失败'); } async reply(user_id, reqData) { const review_id = reqData.review_id; const reply_text = reqData.reply_text; // 获取评论人id const replyBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + 'review_record', { review_id, state: 1, is_delete: 0, }); const replyBaseInfo = JSON.parse(JSON.stringify(replyBaseInfoRow)); const content_id = replyBaseInfo.content_id; const receive_user_id = replyBaseInfo.user_id; // 获取动态内容类型 const contentBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + 'content_record', { content_id, user_id, state: 1, is_delete: 0, }); const contentBaseInfo = JSON.parse(JSON.stringify(contentBaseInfoRow)); const content_type = contentBaseInfo.type_id; const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const replyinfo = await this.app.mysql.update(this.app.config.dbprefix + 'review_record', { reply_text, reply_time: date_now, }, { where: { review_id } }); if (replyinfo) { // 通知 this.registReplyPostNotice(user_id, content_id, review_id, receive_user_id, content_type, reply_text); return replyinfo.affectedRows; } this.ctx.throw('提交失败'); } async registReplyPostNotice(user_id, content_id, review_id, receive_user_id, content_type, reply_text) { // SYSTEM系统通知(1);CONTENT_REGIST内容参与记录(2);CONTENT_REVIEW内容评论记录(3);TYPE_LIKE点赞(4); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const noticedata = { type_id: 3, receive_user_id, start_user_id: user_id, rel_id: review_id, content_id, regist_id: review_id, content_type, title: userInfo.nickname + '回复了你评论的' + this.app.config.contentType[content_type - 1].name, desc: reply_text, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } } module.exports = ReviewService; <file_sep>/app/service/user.js 'use strict'; const Service = require('egg').Service; class UserService extends Service { async userInfo(user_id) { const userInfo = await this.getUserInfo(user_id); if (userInfo.districts) { // 获取所在小区的详细信息 userInfo.districts = await this.getUserDistricts(userInfo.districts); } // 获取职业特长 userInfo.speciality = await this.getUserSpeciality(userInfo.speciality); // 获取业余爱好 userInfo.hobby = await this.getUserHobby(userInfo.hobby); return userInfo; } async getUserInfo(user_id) { const result = await this.app.mysql.get('userinfo', { user_id }); return JSON.parse(JSON.stringify(result)); } async getUserDistricts(set_id) { const estresult = await this.app.mysql.get('estate', { id: set_id }); const estinfo = JSON.parse(JSON.stringify(estresult)); const strresult = await this.app.mysql.get('street', { id: estinfo.sid }); const strinfo = JSON.parse(JSON.stringify(strresult)); return { estate: { id: estinfo.id, name: estinfo.name, }, street: { id: strinfo.id, name: strinfo.name, }, }; } async getUserSpeciality(specialityList) { const specialityLength = specialityList.length; const speciality = []; for (let i = 0; i < specialityLength; i++) { const speresult = await this.app.mysql.get('speciality', { kind_id: specialityList[i] }); speciality.push(JSON.parse(JSON.stringify(speresult))); } return speciality; } async getUserHobby(hobbyList) { const hobbyLength = hobbyList.length; const hobby = []; for (let i = 0; i < hobbyLength; i++) { const hobresult = await this.app.mysql.get('hobby', { kind_id: hobbyList[i] }); hobby.push(JSON.parse(JSON.stringify(hobresult))); } return hobby; } } module.exports = UserService; <file_sep>/app/service/content/main.js 'use strict'; const Service = require('egg').Service; class MainService extends Service { async add(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const type_id = reqData.type_id; const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const district_id = userInfo.district_id; let content_id; const trans_success = await app.mysql.beginTransactionScope(async addmain => { const add_main_log = await addmain.insert(app.config.dbprefix + 'content_record', { type_id, user_id, district_id, title, content, show_type, keyword, link_external_name, link_external_url, add_time: date_now, }); content_id = add_main_log.insertId; // 关键字 if (keyword) { const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); } // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); await addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id }, { where: { type_id: uploadType, user_id, file_id: photoIdArr }, }); } return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return content_id; } async edit(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const content_id = reqData.content_id; const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const trans_success = await app.mysql.beginTransactionScope(async addmain => { addmain.update(app.config.dbprefix + 'content_record', { title, content, show_type, keyword, link_external_name, link_external_url, modify_time: date_now, }, { where: { content_id, user_id, }, }); // 关键字 await addmain.delete(app.config.dbprefix + 'content_keyword', { content_id, }); if (keyword) { const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); } // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); // 删除原来存储的图片 const delstr = `SELECT * FROM ${app.config.dbprefix}upload_file_record WHERE type_id=${uploadType} AND user_id=${user_id} AND rel_id=${content_id} AND file_id NOT IN (${photoIdArr.toString()})`; const dellist = await addmain.query(delstr); dellist.forEach(item => { addmain.delete(app.config.dbprefix + 'upload_file_record', { file_id: item.file_id, }); }); await addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id, }, { where: { type_id: uploadType, user_id, file_id: photoIdArr, }, }); } return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return true; } // 喜欢或不喜欢 async setLike(user_id, reqData) { const like_state = Number(reqData.like_state); // 获取动态内容 const { ctx, app } = this; const contentBaseInfoRow = await this.app.mysql.select(this.app.config.dbprefix + 'content_record', { where: { content_id: reqData.content_id, state: 1, is_delete: 0 }, columns: [ 'content_id', 'type_id', 'user_id', 'content', 'like_num' ], }); const contentBaseInfo = JSON.parse(JSON.stringify(contentBaseInfoRow))[0]; const receive_user_id = contentBaseInfo.user_id; const content_type = contentBaseInfo.type_id; const desc = contentBaseInfo.content; const like_num_ori = contentBaseInfo.like_num; const date_now = ctx.service.base.fromatDate(new Date().getTime()); // 自动事务 let like_state_ori; let like_id; const trans_success = await app.mysql.beginTransactionScope(async sqlsetlike => { // 读取点赞记录 // 动态内容(1); 用户参与(2);评论(3) const type = 1; const is_setlike_log = await sqlsetlike.get(this.app.config.dbprefix + 'like_record', { type_id: type, user_id, rel_id: reqData.content_id, }); if (!is_setlike_log) { // 未设置喜欢 if (like_state === 0) { ctx.throw('您还未点赞'); } else { like_state_ori = -1; const set_like_log = await sqlsetlike.insert(app.config.dbprefix + 'like_record', { type_id: type, user_id, rel_id: reqData.content_id, content_type, like_state, add_time: date_now, }); if (set_like_log) { like_id = set_like_log.insertId; } else { ctx.throw('操作失败'); } } } else { const setlike_log = JSON.parse(JSON.stringify(is_setlike_log)); like_id = setlike_log.like_id; like_state_ori = setlike_log.like_state; await sqlsetlike.update(app.config.dbprefix + 'like_record', { like_state, modify_time: date_now, }, { where: { like_id } }); } // 更新动态内容表 if (like_state_ori !== like_state) { const like_num_offset = like_state === 1 ? 1 : -1; if (like_num_ori === 0 && like_num_offset < 0) { console.log('中奖了'); } else { const sqlstr = 'UPDATE ' + app.config.dbprefix + 'content_record ' + 'SET like_num = like_num + (' + like_num_offset + ') ' + 'WHERE content_id = ' + reqData.content_id; await sqlsetlike.query(sqlstr); } } return true; }, ctx); if (!trans_success) { ctx.throw('操作失败,请重试'); } if (like_state === 1 && like_state_ori !== like_state) { // 添加通知 this.setLikePostNotice(user_id, like_id, reqData.content_id, receive_user_id, content_type, desc); } return true; } // 点赞后发送系统通知 async setLikePostNotice(user_id, rel_id, content_id, receive_user_id, content_type, desc) { // 系统通知(1)内容参与记录(2)内容评论记录(3)点赞(4) const userInfo = await this.ctx.service.member.info.getInfo(user_id); const noticedata = { type_id: 4, receive_user_id, start_user_id: user_id, rel_id, content_id, content_type, title: userInfo.nickname + '点赞了你的' + this.app.config.contentType[content_type - 1].name, desc, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } // 获取首页列表 async getList(user_id, reqData) { // [1,2,3,4,5,6] // ['互助','问答','乐享','活动','团购','话题'] let sql_event_type = '';// 类型检索 switch (reqData.event_type) { case 1: sql_event_type = 'AND a.type_id IN (1, 2, 6)'; break; case 2: sql_event_type = 'AND a.type_id IN (3, 4, 5)'; break; default: sql_event_type = ''; } let sql_district_type = '';// 社区检索 switch (reqData.district_type) { case 1: sql_district_type = ` AND a.district_id = (SELECT district_id FROM ${this.app.config.dbprefix}user_profile WHERE user_id = ${user_id})`; break; case 2: sql_district_type = ` AND FIND_IN_SET(a.district_id, (SELECT GROUP_CONCAT(district_id) FROM ${this.app.config.dbprefix}district WHERE is_delete = 0 AND state = 1 AND parent_id = (SELECT parent_id FROM ${this.app.config.dbprefix}district WHERE district_id = (SELECT district_id FROM ${this.app.config.dbprefix}user_profile WHERE user_id = ${user_id}))) ) AND a.show_type = 2 `; break; default: sql_district_type = ''; } let sql_search_key; if (reqData.search_key) { sql_search_key = "AND t.keywords LIKE '%" + await this.escape_like_str(reqData.search_key) + "%'"; } else { sql_search_key = ''; } const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; const likeType = 1;// 动态内容 const photoType = 2;// 动态内容图片 // 执行查找 const list = await this.duSearchList(user_id, photoType, likeType, sql_event_type, sql_district_type, sql_search_key, limit); return list; } // 进行首页列表实际内容的检索 async duSearchList(user_id, photoType, likeType, sql_event_type, sql_district_type, sql_search_key, limit) { const sqlstr = `SELECT t.content_id,t.type_id,t.title,t.image,t.content,t.visit_num,t.like_num,t.user_id,t.nickname,t.headimgurl, if(t.like_state = 1,1,0) AS like_state FROM( SELECT a.content_id,a.type_id,a.title,a.content,a.visit_num,a.like_num,a.user_id,a.sort, b.nickname, b.headimgurl, (SELECT CONCAT(src,',',img_width,',',img_height) FROM ${this.app.config.dbprefix}upload_file_record WHERE type_id = ${photoType} AND rel_id = a.content_id ORDER BY file_id ASC LIMIT 1) AS image, (SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND rel_id = a.content_id AND user_id = ${user_id}) AS like_state, CONCAT( a.title, a.content ) as keywords FROM ${this.app.config.dbprefix}content_record a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE 1 AND a.is_delete = 0 AND a.state = 1 ${sql_event_type} ${sql_district_type} ) t WHERE 1 ${sql_search_key} ORDER BY t.sort DESC, t.content_id DESC ${limit} `; const results = await this.app.mysql.query(sqlstr); return JSON.parse(JSON.stringify(results)); } // 对搜索中like关键字符进行替换 async escape_like_str(str) { str.replace(/%/g, '/%'); str.replace(/_/g, '/_'); return str; } // 获取动态内容 async getDetailById(user_id, content_id) { // 动态内容(1)用户参与(2)评论(3) // 点赞类型 const likeType = 1; const sqlstr = `SELECT a.content_id,a.type_id,a.title,a.content,a.keyword,a.show_type,a.visit_num,a.like_num,a.collect_num,a.add_time,a.link_external_name,a.link_external_url, b.user_id,b.phone,b.nickname,b.headimgurl,b.personal_signature, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state, if((SELECT collect_state FROM ${this.app.config.dbprefix}collect_record WHERE rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS collect_state FROM ${this.app.config.dbprefix}content_record a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${content_id} AND a.is_delete = 0 AND a.state = 1`; const results = await this.app.mysql.query(sqlstr); const data = JSON.parse(JSON.stringify(results[0])); if (data.headimgurl.length < 100) { data.headimgurl = this.app.config.publicAdd + data.headimgurl; } return data; } // 获取动态的图片列表 async getPhotos(content_id) { // 用户头像(1)动态内容图片(2) const type_id = 2; const photoListRow = await this.app.mysql.select(this.app.config.dbprefix + 'upload_file_record', { where: { type_id, rel_id: content_id }, columns: [ 'file_id', 'src' ], }); const photoList = JSON.parse(JSON.stringify(photoListRow)); const images = []; photoList.forEach(element => { images.push({ id: element.file_id, src: this.app.config.publicAdd + element.src, }); }); return images; } async setCollect(user_id, reqData) { const collect_state = Number(reqData.collect_state); // 获取动态内容 const { ctx, app } = this; const contentBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + 'content_record', { content_id: reqData.content_id, state: 1, is_delete: 0, }); const contentBaseInfo = JSON.parse(JSON.stringify(contentBaseInfoRow)); const collect_num_ori = contentBaseInfo.collect_num; const date_now = ctx.service.base.fromatDate(new Date().getTime()); // 自动事务 let collect_state_ori; let collect_id; const trans_success = await app.mysql.beginTransactionScope(async sqlsetColl => { const is_setColl_log = await sqlsetColl.get(this.app.config.dbprefix + 'collect_record', { user_id, rel_id: reqData.content_id, }); if (!is_setColl_log) { // 未设置喜欢 if (collect_state === 0) { ctx.throw('您还未收藏'); } else { collect_state_ori = -1; const set_coll_log = await sqlsetColl.insert(app.config.dbprefix + 'collect_record', { user_id, rel_id: reqData.content_id, collect_state, add_time: date_now, }); if (set_coll_log) { collect_id = set_coll_log.insertId; } else { ctx.throw('操作失败'); } } } else { const setColl_log = JSON.parse(JSON.stringify(is_setColl_log)); collect_id = setColl_log.collect_id; collect_state_ori = setColl_log.collect_state; await sqlsetColl.update(app.config.dbprefix + 'collect_record', { collect_state, modify_time: date_now, }, { where: { collect_id } }); } // 更新动态内容表 if (collect_state_ori !== collect_state) { const collect_num_offset = collect_state === 1 ? 1 : -1; if (collect_num_ori === 0 && collect_num_offset < 0) { console.log('中奖了'); } else { const sqlstr = `UPDATE ${app.config.dbprefix}content_record SET collect_num = collect_num + (${collect_num_offset}) WHERE content_id = ${reqData.content_id}`; await sqlsetColl.query(sqlstr); } } return true; }, ctx); if (!trans_success) { ctx.throw('操作失败,请重试'); } return true; } } module.exports = MainService; <file_sep>/app/service/notice.js 'use strict'; const Service = require('egg').Service; class NoticeService extends Service { async getList(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; // const userInfo = await this.ctx.service.member.info.getInfo(user_id); const sql = `SELECT a.id, a.type_id AS notice_type, a.content_type AS content_type, a.content_id, a.regist_id, a.title, a.desc, a.read_state, a.add_time, (SELECT nickname FROM ${this.app.config.dbprefix}user_profile WHERE user_id = a.start_user_id) AS nickname, (SELECT headimgurl FROM ${this.app.config.dbprefix}user_profile WHERE user_id = a.start_user_id) AS headimgurl FROM ${this.app.config.dbprefix}notice_record a WHERE 1 AND a.is_delete = 0 AND a.state = 1 AND a.receive_user_id = ${user_id} ORDER BY a.id DESC ${limit}`; const results = await this.app.mysql.query(sql); const list = results.map(item => { if (item.headimgurl && item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); return item; }); return list; } async setRead(user_id, id) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const result = await this.app.mysql.update(this.app.config.dbprefix + 'notice_record', { read_state: 1, read_time: date_now, }, { where: { id, receive_user_id: user_id, } }); if (result.affectedRows === 1) return true; } async getDetailById(notice_id) { const inforow = await this.app.mysql.get(this.app.config.dbprefix + 'notice', { notice_id, is_delete: 0, state: 1, }); const info = JSON.parse(JSON.stringify(inforow)); const data = { notice_id: info.notice_id, title: info.title, content: info.content, add_time: new Date(info.add_time).toLocaleString(), }; return data; } } module.exports = NoticeService; <file_sep>/app/service/member/info.js 'use strict'; const Service = require('egg').Service; class InfoService extends Service { async reg(user_id, reqData) { const { ctx, app } = this; const name_first_letter = await ctx.service.login.getNameFirstCharter(reqData.nickname); const info_last_modify_time = await ctx.service.base.fromatDate(new Date().getTime()); const upDataInfo = { nickname: reqData.nickname, district_id: reqData.district_id, name_first_letter, info_last_modify_time, }; const result = await this.app.mysql.update(app.config.dbprefix + 'user_profile', upDataInfo, { where: { user_id } }); const updateSuccess = result.affectedRows === 1; return updateSuccess; } async getInfo(user_id) { const result = await this.app.mysql.select(this.app.config.dbprefix + 'user_profile', { where: { user_id, state: 1 }, columns: [ 'user_id', 'phone', 'nickname', 'headimgurl', 'sex', 'district_id', 'personal_signature', 'is_manage' ], // 要查询的表字段 }); return JSON.parse(JSON.stringify(result))[0]; } async edit(user_id, reqData) { const { ctx, app } = this; const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const nickname = reqData.nickname; const sex = reqData.sex; const personal_signature = reqData.personal_signature; const speciality = reqData.speciality; const hobby = reqData.hobby; const trans_success = await app.mysql.beginTransactionScope(async editInfo => { // 更新职业特长关联表 const specialityTypeId = 1; await editInfo.delete(app.config.dbprefix + 'kind_relation', { type_id: specialityTypeId, // 职业特长 rel_id: user_id, }); const specialityArr = speciality.map(item => { editInfo.insert(app.config.dbprefix + 'kind_relation', { type_id: specialityTypeId, rel_id: user_id, kind_id: item.kind_id, kind_name: item.kind_name, }); return item.kind_name; }); // 更新业余爱好关联表 const hobbyTypeId = 2; await editInfo.delete(app.config.dbprefix + 'kind_relation', { type_id: hobbyTypeId, // 职业特长 rel_id: user_id, }); const hobbyArr = hobby.map(item => { editInfo.insert(app.config.dbprefix + 'kind_relation', { type_id: hobbyTypeId, rel_id: user_id, kind_id: item.kind_id, kind_name: item.kind_name, }); return item.kind_name; }); // 更新用户表 const result = await editInfo.update(this.app.config.dbprefix + 'user_profile', { nickname, name_first_letter: await ctx.service.login.getNameFirstCharter(nickname), sex, personal_signature, speciality: specialityArr.toString(), hobby: hobbyArr.toString(), info_last_modify_time: date_now, }, { where: { user_id, state: 1, } }); if (result.affectedRows === 1) return true; return false; }, ctx); if (!trans_success) { ctx.throw('操作失败,请重试'); } return trans_success; } async getAddressList(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; const userInfo = await this.ctx.service.member.info.getInfo(user_id); const sql = `SELECT user_id,nickname,headimgurl,personal_signature,name_first_letter FROM ${this.app.config.dbprefix}user_profile WHERE state = 1 AND user_id != ${user_id} AND district_id = ${userInfo.district_id} ORDER BY REPLACE(name_first_letter, '#', 'ZZZ') ASC, user_id DESC ${limit}`; const results = await this.app.mysql.query(sql); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; return item; }); return list; } } module.exports = InfoService; <file_sep>/app/controller/member/info.js 'use strict'; const Controller = require('egg').Controller; class InfoController extends Controller { // 编辑用户信息 async reg() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body;// 获取post数据 if (!reqData.nickname) { this.ctx.throw('姓名不能为空'); } if (!reqData.district_id) { this.ctx.throw('所在小区ID不能为空'); } const updateSuccess = await ctx.service.member.info.reg(user_id, reqData); if (updateSuccess) { ctx.body = { data: {}, }; } else { this.ctx.throw('提交失败'); } } // 获取用户基本信息 async getInfo() { const { ctx } = this; const user_id = ctx.request.body.user_id;// 获取post数据 // console.log(ctx.request.body); // 基础数据 const userInfo = await ctx.service.member.info.getInfo(user_id); if (userInfo.headimgurl.length < 100) { userInfo.headimgurl = this.app.config.publicAdd + userInfo.headimgurl; } // 地址信息 // console.log(userInfo); const estaterow = await ctx.service.common.getDistById(userInfo.district_id); const streetrow = await ctx.service.common.getDistById(estaterow.parent_id); userInfo.districts = { estate: { id: estaterow.district_id, name: estaterow.name, }, street: { id: streetrow.district_id, name: streetrow.name, }, }; // 职业特长 userInfo.speciality = await ctx.service.common.getUserSpecHobyById(user_id, 'speciality'); // 业余爱好 userInfo.hobby = await ctx.service.common.getUserSpecHobyById(user_id, 'hobby'); ctx.body = { data: userInfo, }; } // 编辑用户信息 async edit() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body;// 获取post数据 if (!reqData.nickname) { this.ctx.throw('姓名不能为空'); } const updateSuccess = await ctx.service.member.info.edit(user_id, reqData); if (updateSuccess) { ctx.body = { data: {}, }; } else { this.ctx.throw('提交失败'); } } // 获取通讯录列表 async addressBookList() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; const list = await ctx.service.member.info.getAddressList(user_id, reqData); ctx.body = { data: { list }, }; } } module.exports = InfoController; <file_sep>/app/service/content/pack.js 'use strict'; const Service = require('egg').Service; class PackService extends Service { async getListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; const sqlstr = `SELECT a.regist_id,a.user_id,a.add_time, b.nickname,b.headimgurl FROM ${this.app.config.dbprefix}pack_regist a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${reqData.content_id} AND a.is_delete = 0 AND a.state = 1 GROUP BY a.user_id ORDER BY a.regist_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); if (item.reply_time) item.reply_time = this.ctx.service.base.fromatDate(new Date(item.reply_time).getTime()); return item; }); return list; } // 获取拼团内容 async getDetailById(user_id, content_id) { // 动态内容(1)用户参与(2)评论(3) // 点赞类型 const likeType = 1; const sqlstr = `SELECT a.content_id,a.type_id,a.title,a.content,a.keyword,a.show_type,a.visit_num,a.like_num,a.collect_num,a.add_time,a.link_external_name,a.link_external_url, b.user_id,b.phone,b.nickname,b.headimgurl,b.personal_signature, c.closing_date, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state, if((SELECT collect_state FROM ${this.app.config.dbprefix}collect_record WHERE rel_id = a.content_id AND user_id = ${user_id}) = 1, 1, 0) AS collect_state FROM ${this.app.config.dbprefix}content_record a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id LEFT JOIN ${this.app.config.dbprefix}pack_content c ON c.content_id = a.content_id WHERE a.content_id = ${content_id} AND a.is_delete = 0 AND a.state = 1`; const results = await this.app.mysql.query(sqlstr); const data = JSON.parse(JSON.stringify(results[0])); if (data.headimgurl.length < 100) { data.headimgurl = this.app.config.publicAdd + data.headimgurl; } return data; } // 查看拼团是否结束 async findPackEnd(content_id) { const sqlstr = `SELECT a.content_id, a.user_id, b.closing_date FROM ${this.app.config.dbprefix}content_record a INNER JOIN ${this.app.config.dbprefix}pack_content b ON b.content_id = a.content_id WHERE a.is_delete = 0 AND a.state = 1 AND a.content_id = ${content_id}`; const results = await this.app.mysql.query(sqlstr); if (!results) this.ctx.throw('该团购活动不存在'); return JSON.parse(JSON.stringify(results[0])); } async getGoodsAmountNewList(goodsList, content_id) { const goods_amount_promise = goodsList.map(async element => { const goods_id = element.goods_id; const buy_number = Number(element.buy_number); const getGoods = await this.getGoodsById(content_id, goods_id); if (!getGoods) this.ctx.throw(`${element.goods_name}-${element.goods_specs}不存在`); const goods_name = getGoods.goods_name; const goods_price = getGoods.goods_price; const goods_specs = getGoods.goods_specs; const goods_number = getGoods.goods_number; const used_number = await this.getGoodsNumUsed(goods_id); const enable_number = Number(goods_number) - Number(used_number); if (enable_number < buy_number) { this.ctx.throw('库存不足'); } return { goods_id, goods_name, goods_price, goods_specs, buy_number, }; }); const goods_amount_arr = await Promise.all(goods_amount_promise); const goods_amount = this.goodsAmount(goods_amount_arr); if (goods_amount <= 0) { this.ctx.throw('订单总额必须大于0'); } return { goods_amount, goods_amount_arr, }; } goodsAmount(list) { let goods_amount = 0; list.forEach(item => { goods_amount += parseInt(Number(item.goods_price) * 100, 10) * item.buy_number; }); return goods_amount / 100; } async registAdd(user_id, reqData) { const { app, ctx } = this; const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); // 获取拼团是否结束 const result = await this.findPackEnd(reqData.content_id); const launch_user_id = result.user_id; const closing_date = result.closing_date; if (new Date(closing_date).getTime() - new Date().getTime() <= 0) { this.ctx.throw('很抱歉,该团购活动已结束,请关注下次活动'); } const consignee = reqData.consignee; const mobile = reqData.mobile; const address = reqData.address; const message = reqData.message; // 获取商品价格和信息 const goods_amount_new_list = await this.getGoodsAmountNewList(reqData.goods, reqData.content_id); const order_info = await this.app.mysql.insert(this.app.config.dbprefix + 'order_info', { launch_user_id, regist_user_id: user_id, content_id: reqData.content_id, content_type: 5, add_time: date_now, goods_amount: goods_amount_new_list.goods_amount, order_amount: goods_amount_new_list.goods_amount, order_status: 1, consignee, mobile, address, message, }); const order_id = order_info.insertId; const order_no = this.ctx.service.common.getOrderNoById(order_id.toString()); const trans_success = await app.mysql.beginTransactionScope(async sqlsetColl => { sqlsetColl.update(app.config.dbprefix + 'order_info', { order_no }, { where: { order_id } }); // 记录商品详情 goods_amount_new_list.goods_amount_arr.forEach(async element => { sqlsetColl.insert(this.app.config.dbprefix + 'order_goods', { order_id, launch_user_id, regist_user_id: user_id, content_id: reqData.content_id, content_type: 5, goods_id: element.goods_id, goods_name: element.goods_name, goods_price: element.goods_price, goods_specs: element.goods_specs, goods_number: element.buy_number, }); }); // 记录到拼团参与表 const pack_ins = await sqlsetColl.insert(this.app.config.dbprefix + 'pack_regist', { user_id, content_id: reqData.content_id, order_id, add_time: date_now, }); const regist_id = pack_ins.insertId; return regist_id; }, ctx); if (!trans_success) { ctx.throw('操作失败,请重试'); } // 通知 this.registAddPostNotice(user_id, reqData.content_id, trans_success); return trans_success; } async getGoodsById(content_id, goods_id) { const result = await this.app.mysql.get(this.app.config.dbprefix + 'goods', { goods_id, content_id, is_delete: 0, }); return result; } async getGoodsNumUsed(goods_id) { const sqlstr = `SELECT SUM(goods_number) as nums FROM ${this.app.config.dbprefix}order_goods a INNER JOIN ${this.app.config.dbprefix}order_info b ON b.order_id = a.order_id WHERE a.goods_id = ${goods_id} AND b.order_status IN(0,1)`; const results = await this.app.mysql.query(sqlstr); const result = JSON.parse(JSON.stringify(results[0])); if (results) { return result.nums; } return 0; } async registAddPostNotice(user_id, content_id, regist_id) { // (1)SYSTEM系统通知;(2)CONTENT_REGIST内容参与记录;(3)CONTENT_REVIEW内容评论记录;(4)TYPE_LIKE点赞; const userInfo = await this.ctx.service.member.info.getInfo(user_id); const contentInfo = await this.ctx.service.common.getContentInfoById(content_id); if (!contentInfo) return; const noticedata = { type_id: 2, receive_user_id: contentInfo.user_id, start_user_id: user_id, rel_id: regist_id, content_id, regist_id, content_type: contentInfo.type_id, title: userInfo.nickname + '参与了你的' + this.app.config.contentType[contentInfo.type_id - 1].name, desc: contentInfo.content, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } async getOrderListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; const sqlstr = `SELECT a.order_id,a.regist_user_id,a.add_time,a.order_amount,a.consignee,a.mobile,a.address,a.message, b.nickname,b.headimgurl FROM ${this.app.config.dbprefix}order_info a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.regist_user_id WHERE a.content_id = ${reqData.content_id} AND a.launch_user_id = ${user_id} ORDER BY a.order_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(async item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); item.goods = await this.getOrderGoodsList(item.order_id); return item; }); return await Promise.all(list); } async getOrderGoodsList(order_id) { const sqlstr = `SELECT goods_name,goods_specs,goods_price,goods_number FROM ${this.app.config.dbprefix}order_goods WHERE order_id = ${order_id} ORDER BY record_id ASC`; const resultsGoods = await this.app.mysql.query(sqlstr); return resultsGoods; } async getGoodsListAllById(content_id) { const sqlstr = `SELECT t.goods_id, t.goods_name, t.goods_specs, t.goods_price, t.goods_number, SUM( t.buy_number ) AS used_number FROM ( SELECT a.goods_id, a.goods_name, a.goods_specs, a.goods_price, a.goods_number, a.is_delete, b.order_id, b.goods_number AS buy_number FROM ${this.app.config.dbprefix}goods a LEFT JOIN ${this.app.config.dbprefix}order_goods b ON b.goods_id = a.goods_id LEFT JOIN ${this.app.config.dbprefix}order_info c ON c.order_id = b.order_id WHERE 1 AND a.content_id = ${content_id} AND ( a.is_delete = 0 OR b.goods_number IS NOT NULL ) AND ( c.order_status IN (1,2) OR b.goods_number IS NULL ) ) t WHERE 1 GROUP BY t.goods_id ORDER BY t.goods_id ASC`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { const used_number = item.used_number ? item.used_number : 0; item.remaining_number = item.goods_number - used_number; delete item.is_delete; delete item.used_number; return item; }); return list; } async getOrderAmountByContentId(user_id, content_id) { const sqlstr = `SELECT SUM(order_amount) AS order_amount FROM ${this.app.config.dbprefix}order_info WHERE 1 AND content_id = ${content_id} AND launch_user_id = ${user_id}`; const results = await this.app.mysql.query(sqlstr); let order_amount = 0; if (results) { const result = JSON.parse(JSON.stringify(results[0])); order_amount = result.order_amount; } return order_amount; } async getGoodsListById(content_id) { const sqlstr = `SELECT a.goods_id, a.goods_name, a.goods_specs, a.goods_price, a.goods_number, SUM( b.goods_number ) AS used_number FROM ${this.app.config.dbprefix}goods a LEFT JOIN ${this.app.config.dbprefix}order_goods b ON b.goods_id = a.goods_id WHERE 1 AND a.is_delete = 0 AND a.content_id = ${content_id} AND ( ( SELECT order_status FROM ${this.app.config.dbprefix}order_info WHERE order_id = b.order_id ) IN ( 1, 2 ) OR b.goods_number IS NULL ) GROUP BY a.goods_id ORDER BY a.goods_id ASC`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { const used_number = item.used_number ? item.used_number : 0; item.remaining_number = item.goods_number - used_number; delete item.used_number; return item; }); return list; } async add(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const closing_date = new Date(reqData.closing_date); const goods = reqData.goods;// 商品数组 const district_id = userInfo.district_id; let content_id; const trans_success = await app.mysql.beginTransactionScope(async addmain => { const add_main_log = await addmain.insert(app.config.dbprefix + 'content_record', { type_id: 5, user_id, district_id, title, content, show_type, keyword, link_external_name, link_external_url, add_time: date_now, }); content_id = add_main_log.insertId; // 插入拼团内容表 addmain.insert(app.config.dbprefix + 'pack_content', { content_id, closing_date, }); // 关键字 if (keyword) { const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); } // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); await addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id, }, { where: { type_id: uploadType, user_id, file_id: photoIdArr, }, }); } // 商品 goods.forEach(gooditem => { addmain.insert(app.config.dbprefix + 'goods', { user_id, content_id, content_type: 5, goods_name: gooditem.goods_name, goods_specs: gooditem.goods_specs, goods_price: gooditem.goods_price, goods_number: gooditem.goods_number, }); }); return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return content_id; } async edit(user_id, reqData) { const { ctx, app } = this; const date_now = ctx.service.base.fromatDate(new Date().getTime()); const content_id = reqData.content_id; const title = reqData.title; const images = reqData.images; const content = reqData.content; const show_type = reqData.show_type; const keyword = reqData.keyword; const link_external_name = reqData.link_external_name; const link_external_url = reqData.link_external_url; const closing_date = new Date(reqData.closing_date); const goods = reqData.goods;// 商品数组 const trans_success = await app.mysql.beginTransactionScope(async addmain => { // 更新动态内容表 addmain.update(app.config.dbprefix + 'content_record', { title, content, show_type, keyword, link_external_name, link_external_url, modify_time: date_now, }, { where: { content_id, user_id, }, }); // 更新团购内容表 addmain.update(app.config.dbprefix + 'pack_content', { closing_date, }, { where: { content_id, } }); // 关键字 addmain.delete(app.config.dbprefix + 'content_keyword', { content_id, }); const keywordArr = keyword.split(','); keywordArr.forEach(aword => { addmain.insert(app.config.dbprefix + 'content_keyword', { content_id, keyword: aword, }); }); // 图片 if (images) { const uploadType = 2;// 动态内容图片 const photoIdArr = images.map(item => { return item.id; }); // 删除原来存储的图片 const delstr = `SELECT * FROM ${app.config.dbprefix}upload_file_record WHERE type_id=${uploadType} AND user_id=${user_id} AND rel_id=${content_id} AND file_id NOT IN (${photoIdArr.toString()})`; const dellist = await addmain.query(delstr); const delarr = dellist.map(item => { return item.file_id; }); if (delarr.length) { addmain.delete(app.config.dbprefix + 'upload_file_record', { file_id: delarr, }); } addmain.update(app.config.dbprefix + 'upload_file_record', { rel_id: content_id }, { where: { type_id: uploadType, user_id, file_id: photoIdArr } } ); } // 商品 const goodsIdArr = await this.getGoodsIdArr(user_id, content_id, goods); // 删除用户前端删除的商品 const delgoodstr = `UPDATE ${app.config.dbprefix}goods SET is_delete=1 WHERE user_id=${user_id} AND content_id=${content_id} AND goods_id NOT IN (${goodsIdArr.toString()})`; addmain.query(delgoodstr); return true; }, ctx); if (!trans_success) { ctx.throw('提交失败,请重试'); } return true; } async getGoodsIdArr(user_id, content_id, goods) { const goodsIdArr = goods.map(async gooditem => { if (gooditem.goods_id) { this.app.mysql.update(this.app.config.dbprefix + 'goods', { goods_name: gooditem.goods_name, goods_specs: gooditem.goods_specs, goods_price: gooditem.goods_price, goods_number: gooditem.goods_number, }, { where: { goods_id: gooditem.goods_id, content_id, }, }); return gooditem.goods_id; } const newgood = await this.app.mysql.insert(this.app.config.dbprefix + 'goods', { user_id, content_id, content_type: 5, goods_name: gooditem.goods_name, goods_specs: gooditem.goods_specs, goods_price: gooditem.goods_price, goods_number: gooditem.goods_number, }); return newgood.insertId; }); return await Promise.all(goodsIdArr); } } module.exports = PackService; <file_sep>/app/controller/content/main.js 'use strict'; const Controller = require('egg').Controller; class MainController extends Controller { async getList() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.event_type) { this.ctx.throw('页面类型不能为空'); } if (!reqData.district_type) { this.ctx.throw('社区筛选类型不能为空'); } const resultsrow = await ctx.service.content.main.getList(user_id, reqData); const list = []; resultsrow.forEach(element => { if (element.image) { const imageArr = element.image.split(','); element.image = { src: this.app.config.publicAdd + imageArr[0], width: imageArr[1], height: imageArr[2], }; } else { element.image = ''; } if (element.like_num > 99) { element.like_num = '99+'; } if (element.headimgurl.length < 100) { element.headimgurl = this.app.config.publicAdd + element.headimgurl; } list.push(element); }); ctx.body = { data: { list }, }; } // 获取动态详情 async getDetailById() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } const content_id = Number(reqData.content_id); ctx.service.common.visitRecordAdd(user_id, content_id); const data = await ctx.service.content.main.getDetailById(user_id, content_id); if (!data) { this.ctx.throw('该动态内容不存在'); } const images = await ctx.service.content.main.getPhotos(content_id); data.images = images; data.add_time = this.ctx.service.base.fromatDate(new Date(data.add_time).getTime()); ctx.body = { data, }; } // 点赞动态 async setLike() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } if (!('like_state' in reqData)) { this.ctx.throw('点赞状态不能为空'); } const results = await ctx.service.content.main.setLike(user_id, reqData); if (results) { ctx.body = { data: {}, }; } } // 收藏动态 async setCollect() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } if (!('collect_state' in reqData)) { this.ctx.throw('收藏状态不能为空'); } const results = await ctx.service.content.main.setCollect(user_id, reqData); if (results) { ctx.body = { data: {}, }; } } // 发布动态 async add() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.type_id) { this.ctx.throw('内容类型不能为空'); } if (!reqData.title) { this.ctx.throw('标题不能为空'); } if (!reqData.content) { this.ctx.throw('内容描述不能为空'); } if (!reqData.show_type) { this.ctx.throw('可见类型不能为空'); } const content_id = await ctx.service.content.main.add(user_id, reqData); if (content_id) { ctx.body = { data: { content_id }, }; } } // 编辑动态 async edit() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } if (!reqData.title) { this.ctx.throw('标题不能为空'); } if (!reqData.content) { this.ctx.throw('内容描述不能为空'); } if (!reqData.show_type) { this.ctx.throw('可见类型不能为空'); } const result = await ctx.service.content.main.edit(user_id, reqData); if (result) { ctx.body = { data: { }, }; } } } module.exports = MainController; <file_sep>/app/controller/content/review.js 'use strict'; const Controller = require('egg').Controller; class ReviewController extends Controller { async getListById() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } const list = await ctx.service.content.review.getListById(user_id, reqData); ctx.body = { data: { list }, }; } // 动态添加评论 async add() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.content_id) { this.ctx.throw('动态ID不能为空'); } if (!reqData.review_text) { this.ctx.throw('评论内容不能为空'); } const review_id = await ctx.service.content.review.add(user_id, reqData); ctx.body = { data: { review_id }, }; } // 评论点赞 async setLike() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.review_id) { this.ctx.throw('评论记录ID不能为空'); } if (!('like_state' in reqData)) { this.ctx.throw('点赞状态不能为空'); } const results = await ctx.service.content.review.setLike(user_id, reqData); if (results) { ctx.body = { data: {}, }; } } // 评论删除 async delete() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.review_id) { this.ctx.throw('评论记录ID不能为空'); } const results = await ctx.service.content.review.delete(user_id, reqData.review_id); if (results) { ctx.body = { data: {}, }; } } // 回复评论 async reply() { const { ctx } = this; const user_id = ctx.state.user.user_id; const reqData = ctx.request.body; if (!reqData.review_id) { this.ctx.throw('评论记录ID不能为空'); } if (!reqData.reply_text) { this.ctx.throw('回复内容不能为空'); } const replySuccess = await ctx.service.content.review.reply(user_id, reqData); if (replySuccess) { ctx.body = { data: {}, }; } } } module.exports = ReviewController; <file_sep>/config/config.default.js /* eslint valid-jsdoc: "off" */ 'use strict'; /** * @param {Egg.EggAppInfo} appInfo app info */ module.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = exports = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1584019421199_9328'; // add your middleware config here config.middleware = [ 'jwtErrorHandler' ]; // 安全策略暂时关闭,防止无法开发 config.security = { csrf: { enable: false, ignoreJSON: true, }, domainWhiteList: [ 'http://localhost:8080' ], // 允许访问接口的白名单 }; config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', }; // config/config.${env}.js exports.mysql = { // 单数据库信息配置 client: { // host host: 'rm-uf6vwri7l8a0553ne0o.mysql.rds.aliyuncs.com', // 端口号 port: '3306', // 用户名 user: 'gradpro_admin', // 密码 password: '<PASSWORD>', // 数据库名 database: 'gradproj', }, // 是否加载到 app 上,默认开启 app: true, // 是否加载到 agent 上,默认关闭 agent: false, }; exports.jwt = { secret: 'G2adPr0j', }; // add your user config here const userConfig = { // 采用app.config.XX访问 dbprefix: 'al_', // 数据库表前缀 serviceUrl: 'http://127.0.0.1:7001', // 服务器地址 publicAdd: 'http://127.0.0.1:7001/public/', // 静态资源地址 contentTypeIdByName: { HELP: 1, QUESTION: 2, UNUSED: 3, ACTIVITY: 4, PACK: 5, TOPIC: 6, }, contentType: [ { name: '互助', id: 1, registTable: 'help_regist', }, { name: '问答', id: 2, registTable: 'question_regist', }, { name: '共享', id: 3, registTable: 'unused_regist', }, { name: '活动', id: 4, registTable: 'activity_regist', }, { name: '团购', id: 5, registTable: 'pack_regist', }, { name: '话题', id: 6, registTable: 'topic_regist', }, ], // myAppName: 'egg', }; return { ...config, ...userConfig, }; }; <file_sep>/config/config.prod.js /* eslint valid-jsdoc: "off" */ 'use strict'; /** * @param {Egg.EggAppInfo} appInfo app info */ module.exports = appInfo => { /** * built-in config * @type {Egg.EggAppConfig} **/ const config = exports = {}; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1584019421199_9328'; // add your middleware config here config.middleware = [ 'jwtErrorHandler' ]; // 安全策略暂时关闭,防止无法开发 config.security = { csrf: { enable: false, ignoreJSON: true, }, domainWhiteList: [ 'http://localhost:8080', '0.0.0.0/0' ], // 允许访问接口的白名单 }; config.cors = { origin: '*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', }; // config/config.${env}.js // add your user config here const userConfig = { dbprefix: 'al_', // 数据库表前缀 serviceUrl: 'http://water.glasssoda.cn:7001', // 服务器地址 publicAdd: 'http://water.glasssoda.cn:7001/public/', // 静态资源地址 }; return { ...config, ...userConfig, }; }; <file_sep>/app/service/content/help.js 'use strict'; const Service = require('egg').Service; class HelpService extends Service { async getListById(user_id, reqData) { const limitrow = await this.ctx.service.common.getPageStyle(reqData); const limit = limitrow.limit; // 用户的点赞类型 动态内容(1)'SET_LIKE_CONTENT'; 用户参与(2)'SET_LIKE_REGIST';评论(3)'SET_LIKE_REVIEW' const likeType = 2; const contentType = this.app.config.contentTypeIdByName.HELP; const sqlstr = `SELECT a.regist_id,a.user_id,a.add_text,a.reply_text,a.add_time,a.reply_time,a.like_num, b.nickname,b.headimgurl, if((SELECT like_state FROM ${this.app.config.dbprefix}like_record WHERE type_id = ${likeType} AND content_type = ${contentType} AND rel_id = a.regist_id AND user_id = ${user_id}) = 1, 1, 0) AS like_state FROM ${this.app.config.dbprefix}help_regist a INNER JOIN ${this.app.config.dbprefix}user_profile b ON b.user_id = a.user_id WHERE a.content_id = ${reqData.content_id} AND a.is_delete = 0 AND a.state = 1 ORDER BY a.regist_id DESC ${limit}`; const results = await this.app.mysql.query(sqlstr); const list = results.map(item => { if (item.headimgurl.length < 100) item.headimgurl = this.app.config.publicAdd + item.headimgurl; if (item.add_time) item.add_time = this.ctx.service.base.fromatDate(new Date(item.add_time).getTime()); if (item.reply_time) item.reply_time = this.ctx.service.base.fromatDate(new Date(item.reply_time).getTime()); return item; }); return list; } async registAdd(user_id, reqData) { const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const regist_log = await this.app.mysql.insert(this.app.config.dbprefix + 'help_regist', { user_id, content_id: reqData.content_id, add_text: reqData.add_text, add_time: date_now, }); if (regist_log) { // 通知 this.registAddPostNotice(user_id, reqData.content_id, regist_log.insertId, reqData.add_text); return regist_log.insertId; } this.ctx.throw('提交失败'); } async registAddPostNotice(user_id, content_id, regist_id, add_text) { // SYSTEM系统通知(1);CONTENT_REGIST内容参与记录(2);CONTENT_REVIEW内容评论记录(3);TYPE_LIKE点赞(4); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const contentInfo = await this.ctx.service.common.getContentInfoById(content_id); const noticedata = { type_id: 2, receive_user_id: contentInfo.user_id, start_user_id: user_id, rel_id: regist_id, content_id, content_type: contentInfo.type_id, title: userInfo.nickname + '参与了你的' + this.app.config.contentType[contentInfo.type_id - 1].name, desc: add_text, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } async registReply(user_id, reqData, dbName) { const regist_id = reqData.regist_id; const reply_text = reqData.reply_text; // 获取参与人id const replyBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + dbName, { regist_id, state: 1, is_delete: 0, }); const replyBaseInfo = JSON.parse(JSON.stringify(replyBaseInfoRow)); const content_id = replyBaseInfo.content_id; const receive_user_id = replyBaseInfo.user_id; // 获取动态内容类型 const contentBaseInfoRow = await this.app.mysql.get(this.app.config.dbprefix + 'content_record', { content_id, user_id, state: 1, is_delete: 0, }); const contentBaseInfo = JSON.parse(JSON.stringify(contentBaseInfoRow)); const content_type = contentBaseInfo.type_id; const date_now = this.ctx.service.base.fromatDate(new Date().getTime()); const replyinfo = await this.app.mysql.update(this.app.config.dbprefix + dbName, { reply_text, reply_time: date_now, }, { where: { regist_id } }); if (replyinfo) { // 通知 this.registReplyPostNotice(user_id, content_id, regist_id, receive_user_id, content_type, reply_text); return replyinfo.affectedRows; } this.ctx.throw('提交失败'); } async registReplyPostNotice(user_id, content_id, regist_id, receive_user_id, content_type, reply_text) { // SYSTEM系统通知(1);CONTENT_REGIST内容参与记录(2);CONTENT_REVIEW内容评论记录(3);TYPE_LIKE点赞(4); const userInfo = await this.ctx.service.member.info.getInfo(user_id); const noticedata = { type_id: 3, receive_user_id, start_user_id: user_id, rel_id: regist_id, content_id, regist_id, content_type, title: userInfo.nickname + '回复了你参与的' + this.app.config.contentType[content_type - 1].name, desc: reply_text, }; await this.ctx.service.common.noticeRecordAdd(noticedata); } } module.exports = HelpService;
c73371b5bba747560dfc6ea1fdbfdaaa50c7823e
[ "JavaScript" ]
17
JavaScript
Storh/gradproj-comegg
f0d02bc1c939616629665be2884e3ade0509adcf
e52af5a18eaf56c981e25a85a18229b48d8c8725
refs/heads/master
<file_sep>import React from 'react' import ReactDOM from 'react-dom' import Header from'./AppBar.jsx' class TestBox extends React.Component { constructor(props) { super(props); } render() { return( <div> <Header /> <p>hoge</p> </div> ); } } ReactDOM.render( <TestBox />, document.getElementById('content') ); <file_sep># react-electron-test1 test1 #備忘録 http://stackoverflow.com/questions/36953711/i-cannot-use-material-ui-components-after-update-to-material-ui0-15-0-beta-1
85cb03378f5893f53a20410a5f6d0966e943af48
[ "JavaScript", "Markdown" ]
2
JavaScript
gaku3601/react-electron-test1
f57d3c425508c9b7074e992982b56403ed6cffa4
3da04b6f922467c3e404aafa5568940cf09426e2
refs/heads/master
<repo_name>happysansam/HouseholdLedgerManagementSystem<file_sep>/src/gui/HistoryViewer.java package gui; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import cash.CashInfo; import manager.CashManager; public class HistoryViewer extends JPanel { WindowFrame frame; CashManager cashManager; public HistoryViewer(WindowFrame frame, CashManager cashManager) { this.frame = frame; this.cashManager = cashManager; System.out.println("***"+ cashManager.size() + "***"); DefaultTableModel model = new DefaultTableModel(); model.addColumn("No."); model.addColumn("In/Out"); model.addColumn("Amount"); model.addColumn("Purpose"); model.addColumn("wallet"); for (int i = 0; i<cashManager.size(); i++) { Vector row = new Vector(); CashInfo ci = cashManager.get(i); row.add(ci.getNum()); row.add(ci.getHowIoS()); row.add(ci.getCash()); row.add(ci.getHow()); row.add(ci.getWallet()); model.addRow(row); } JTable table = new JTable(model); JScrollPane sp = new JScrollPane(table); this.add(sp); } } <file_sep>/src/manager/CashManager.java package manager; import java.io.Serializable; import java.util.ArrayList; import java.util.InputMismatchException; import java.util.Scanner; import cash.Bankbook; import cash.CashInfo; import cash.CashL; import cash.CashList; import cash.walletList; import exception.CashException; public class CashManager implements Serializable { /** * */ private static final long serialVersionUID = 2715230278478154011L; ArrayList<CashInfo> Cash = new ArrayList<CashInfo>(); transient Scanner sc; CashManager(Scanner sc) { this.sc = sc; } public void setScanner(Scanner sc) { this.sc = sc; } public void input(int a) { CashInfo cashinfo; int kind = 0; sc = new Scanner(System.in); while(true) { try { System.out.print("Press 1 for Cash \npress 2 for Bankbook\n"); kind = sc.nextInt(); if (kind ==1) { cashinfo = new CashL(); cashinfo.getCashInfo(a, MenuManager.num, walletList.Cash); Cash.add(cashinfo); break; } else if (kind == 2) { cashinfo = new Bankbook(); cashinfo.getCashInfo(a, MenuManager.num, walletList.Bankbook); Cash.add(cashinfo); break; } else { System.out.print("Please type 1 or 2"); } } catch(InputMismatchException e) { System.out.println("Please type an integer 1 or 2!"); if(sc.hasNext()){ sc.next(); } kind = -1; } } } public void BalanceCheck() { for (int i=0; i<Cash.size();i++) { if (Cash.get(i).getHowIoS()=="Spending") { MenuManager.Balance = MenuManager.Balance - Cash.get(i).getCash(); } else if (Cash.get(i).getHowIoS()=="Income") { MenuManager.Balance = MenuManager.Balance + Cash.get(i).getCash(); } } System.out.print("Balance : " + MenuManager.Balance + "\n"); } public void delete() { sc = new Scanner(System.in); System.out.print("List number : "); int a = sc.nextInt(); int index = array(a); if (index >= 0) { Cash.remove(index); System.out.print("the list " + a + " is deleted\n"); } else { System.out.print("the list has not found\n"); } } public int array(int a) { int index = -1; for(int i = 0; i < Cash.size(); i++) { if (Cash.get(i).getNum() == a) { index = i; break; } } for(int i = index; i <Cash.size(); i++) { int b = Cash.get(i).getNum(); Cash.get(i).setNum(--b); } MenuManager.num--; return index; } public void edit() { sc = new Scanner(System.in); System.out.print("List number : "); int a = sc.nextInt(); int index = -1; for(int i = 0; i < Cash.size(); i++) { CashList cash = (CashList) Cash.get(i); if (Cash.get(i).getNum() == a) { while (index != 4) { try { showEditMenu(); sc = new Scanner(System.in);; index = sc.nextInt(); sc = new Scanner(System.in); switch (index) { default : System.out.println("Please select one number between 1 - 4:"); continue; case 1: System.out.println("Please type amount of money : "); try { cash.setCash(sc.nextInt()); } catch (CashException e1) { System.out.println("Please type more than 10 won."); } continue; case 2: System.out.println("Please type how : "); String How = sc.nextLine(); cash.setHow(How); continue; case 3: System.out.print("please type 1 if you Spend money or type 2 if you get money"); int b = sc.nextInt(); if (b==1) { cash.setHowIoS("Spending"); } else if (b==2) { cash.setHowIoS("Income"); } continue; case 4: break; } } catch(InputMismatchException e) { System.out.println("Please type an integer 1 to 4!"); if(sc.hasNext()){ sc.next(); } index = -1; } } break; } } } public int size() { return Cash.size(); } public CashInfo get(int index) { return Cash.get(index); } public void showEditMenu() { System.out.println("*** Householde Ledger Management Sysytem Edit Menu ***"); System.out.println("1. Cash\n2. How\n3. Spending or Income\n4. Exit\nSelect one number between 1 - 4 :"); } public void history() { if (Cash.size() != 0) { for (int i=0; i<Cash.size();i++) { if (Cash.get(i).getWallet()==walletList.Secret) { } else { Cash.get(i).printInfo(); } } } } } <file_sep>/src/cash/CashL.java package cash; import java.util.InputMismatchException; import java.util.Scanner; import exception.CashException; public class CashL extends CashList implements CashInfo{ public void getCashInfo(int a, int num, walletList wallet) { setWallet(wallet); Scanner input = new Scanner(System.in); int p; String How; setNum(num); System.out.println("Please input amount of cash :"); input = new Scanner(System.in); while(true) { try { setCash(input.nextInt()); } catch (CashException e1) { System.out.println("Please type more than 10 won."); getCashInfo(a,num,wallet); } try { System.out.print("If you don't want to save impormation press 1 or do press 2 : "); p = input.nextInt(); if(p == 1) { setHow(""); break; } else if (p == 2) { System.out.println("How :"); input = new Scanner(System.in); How = input.nextLine(); setHow(How); break; } else { System.out.print("Please press 1 or 2"); continue; } } catch(InputMismatchException e) { System.out.println("Please type an integer 1 or 2!"); if(input.hasNext()){ input.next(); } p = -1; } } if (a==1) { setHowIoS("Spending"); } else if (a==2) { setHowIoS("Income"); } } public void printInfo() { System.out.println("Num : " + getNum() + " " + getWallet() + " Amount : " + getCash() + " How : " + getHowIoS() + " " + getHow()); } } <file_sep>/README.md # HouseholdLedgerManagementSystem oop at gnu
359a0d44a5162aad386cee2bd9c5f571f2d6266d
[ "Markdown", "Java" ]
4
Java
happysansam/HouseholdLedgerManagementSystem
0a880687f773e0f8518fc1434ae9d5bf52888fcd
c9b9074a1a0515e52644c7e7fb7b29c13cfe0d13
refs/heads/main
<file_sep>var chai = require('chai') var expect = chai.expect const MartianRover = require('../rover.js'); describe('Rover', function() { it('Test to check the Rover Class', function() { expect(new MartianRover(0,1, 'N','FRF')).to.be.an.instanceOf(MartianRover) }) describe('#constructors', function() { it('Test to check rotation equals to N', function() { var myRover = new MartianRover(0,1, 'N','FRF') expect(myRover.rotation).to.equal('N') }) it('Test to check xAxis is set to 0', function() { var myRover = new MartianRover(0,0, 'N', 'FRF') expect(myRover.xAxis).to.equal(0) }) it('Test to check yAxis is set to 0', function() { var myRover = new MartianRover(0,0, 'N', 'FRF') expect(myRover.yAxis).to.equal(0) }) it('Test to check roverOffcourse is set to false', function() { var myRover = new MartianRover(0,1, 'N', 'FRF') expect(myRover.roverOffcourse).to.equal(false) }) }) describe('#TurnLeft', function() { it('When North rover moves West', function() { var myRover = new MartianRover(0,1, 'N', 'FRF') myRover.TurnLeft() expect(myRover.rotation).to.equal('W') }) it('When West rover moves South', function() { var myRover = new MartianRover(0,1, 'W', 'FRF') myRover.TurnLeft() expect(myRover.rotation).to.equal('S') }) it('When South rover moves East', function() { var myRover = new MartianRover(0,1, 'S', 'FRF') myRover.TurnLeft() expect(myRover.rotation).to.equal('E') }) it('When East rover moves North', function() { var myRover = new MartianRover(0,1, 'E', 'FRF') myRover.TurnLeft() expect(myRover.rotation).to.equal('N') }) it('When West rover moves South', function() { var myRover = new MartianRover(0,1, 'W', 'FRF') myRover.TurnLeft() expect(myRover.rotation).to.equal('S') }) }) describe('#TurnRight', function() { it('When North rover moves East', function() { var myRover = new MartianRover(0,1, 'N','FRF') myRover.TurnRight() expect(myRover.rotation).to.equal('E') }) it('When East rover moves South', function() { var myRover = new MartianRover(0,1, 'E', 'FRF') myRover.TurnRight() expect(myRover.rotation).to.equal('S') }) it('When South rover moves West', function() { var myRover = new MartianRover(0,1, 'S', 'FRF') myRover.TurnRight() expect(myRover.rotation).to.equal('W') }) it('When West rover moves North', function() { var myRover = new MartianRover(0,1, 'W', 'FRF') myRover.TurnRight() expect(myRover.rotation).to.equal('N') }) }) describe('#GoForward', function() { it('Testing yAxis, when rover moves North', function() { var myRover = new MartianRover(0,0, 'N', 'FRF') myRover.GoForward() expect(myRover.yAxis).to.equal(1) }) it('Testing yAxis, when rover moves South', function() { var myRover = new MartianRover(0,0, 'S', 'FRF') myRover.GoForward() expect(myRover.yAxis).to.equal(-1) }) it('Testing xAxis, when rover moves East', function() { var myRover = new MartianRover(0,0, 'E', 'FRF') myRover.GoForward() expect(myRover.xAxis).to.equal(1) }) it('Testing xAxis, when rover moves West', function() { var myRover = new MartianRover(0,0, 'W', 'FRF') myRover.GoForward() expect(myRover.xAxis).to.equal(-1) }) }) describe('#commandMoves', function() { it('Testing command Moves', function() { var myRover = new MartianRover(0,0, 'N', 'FRF') myRover.commands() expect(myRover.xAxis).to.equal(1) && expect(myRover.yAxis).to.equal(1) }) }) })<file_sep># MartianRover-Challange # MartianRover-Challange # MartianRover-Challange <file_sep>class MartianRover{ constructor(xAxis, yAxis, rotation, commandMoves){ this.rotation = rotation; this.xAxis = xAxis; this.yAxis = yAxis; this.travelLog = []; // Just for myself to keep track of the rover's travel this.roverOffcourse = false; this.commandMoves = commandMoves.split(''); } // ====================== TurnLeft() { console.log('TurnLeft was called!'); switch (this.rotation) { case (this.rotation = 'N'): this.rotation = 'W'; break; case (this.rotation = 'W'): this.rotation = 'S'; break; case (this.rotation = 'S'): this.rotation = 'E'; break; case (this.rotation = 'E'): this.rotation = 'N'; break; } console.log(this.rotation); } TurnRight() { console.log('TurnRight was called!'); switch (this.rotation) { case (this.rotation = 'N'): this.rotation = 'E'; break; case (this.rotation = 'E'): this.rotation = 'S'; break; case (this.rotation = 'S'): this.rotation = 'W'; break; case (this.rotation = 'W'): this.rotation = 'N'; break; } console.log(this.rotation); } GoForward() { console.log('Go Forward was called'); switch (this.rotation) { case (this.rotation = 'N'): this.yAxis++; break; case (this.rotation = 'E'): this.xAxis++; break; case (this.rotation = 'S'): this.yAxis--; break; case (this.rotation = 'W'): this.xAxis--; break; } console.log('Rover now in: x: ' + this.xAxis + ' y: ' + this.yAxis); this.travelLog.push('[' + this.xAxis + ',' + this.yAxis + ']'); console.log('Final Position of the Martian Rover ' + this.xAxis + ',' + this.yAxis); } commands() { for (var i = 0; i <this.commandMoves.length; i++) { switch (this.commandMoves[i]) { case (this.commandMoves[i] = 'R'): this.TurnRight(); break; case (this.commandMoves[i] = 'L'): this.TurnLeft(); break; case (this.commandMoves[i] = 'F'): this.GoForward(); break; default: continue; break; } } console.log('Travel log: ' + this.travelLog); } } module.exports = MartianRover //5 3 //1 1 E //RFRFRFRF //3 2 N //FRRFLLFFRRFLL //0 3 W //LLFFFLFLFL
22deaa25fa03fb89290aba6edda2f280285d3d28
[ "JavaScript", "Markdown" ]
3
JavaScript
harmankalair123/MartianRover-Challange
2aa2c7d19e367a3e050563bfe954937fc69dd0cc
be48ea8eb21b3df3a4764d3222e30a38df4e645c
refs/heads/master
<repo_name>akshaykhatter/inventory-mgmt-system<file_sep>/resources/js/script_datetime.js $(document).ready(function(){ $(':date').datepicker(); $(':time').timepicker(); });
6eeb89243a8fe97a35bb7d82aa25ca21cabb3975
[ "JavaScript" ]
1
JavaScript
akshaykhatter/inventory-mgmt-system
19702bc71a32ff7ff3a2975940b7c25bc40c044c
820fd973b16c01c583368a97eedc7ed284546c05
refs/heads/master
<repo_name>z89993281/sample<file_sep>/app/Http/Controllers/StaticPagesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class StaticPagesController extends Controller { public function home() { return view('static_pages/home'); } public function help() { return view('static_pages/help'); } public function about() { return view('static_pages/about'); } public function test() { echo "<pre>"; var_dump(getenv('IS_TEST')); var_dump(getenv('IS_IN_HEROKU')); var_dump(getenv('DATABASE_URL')); var_dump(parse_url(getenv("DATABASE_URL"))); phpinfo(); //return view('static_pages/test', $myvar); } }
0e961778d040592883eefd0efdebd269e1f11f6f
[ "PHP" ]
1
PHP
z89993281/sample
cd3328d872624c2993261794d14ed4fbe43cb6de
030b692374e8fe9ddc6a75a336abf59fda8e692e
refs/heads/main
<file_sep>const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') canvas.width = window.innerWidth canvas.height = window.innerHeight class Container{ constructor(x, y, width, length){ this.x = x; this.y = y; this.length = length; this.width = width; } draw(){ ctx.fillStyle = "lightblue" ctx.beginPath() ctx.rect(this.x, this.y, this.width, this.length) ctx.fillStyle = "lightblue" ctx.fill() } } const container1 = new Container(100, 200, 200, 300); const container2 = new Container(350, 200, 200, 300); const container3 = new Container(600, 200, 200, 300); const container4 = new Container(850, 200, 200, 300); const container5 = new Container(1100, 200, 200, 300) var containers = [container1, container2, container3, container4, container5] let animationId function animate(){ animationId = requestAnimationFrame(animate); ctx.fillStyle = 'rgba(0, 0, 0, 1)' ctx.fillRect(0, 0, canvas.width, canvas.height) ctx.font = "25px Courier" ctx.fillStyle = "white" ctx.fillText("Why couldn't we delete and print properly using the FOR loop?", (canvas.width/2)-450, 100) containers.forEach((container, idx) => { container.draw(); ctx.fillStyle = "black" ctx.fillText("index:" + idx, (container.x + 50), (container.y + (container.y + container.length))/2) }); } window.addEventListener('click', (e)=> { containers.forEach((container, idx) => { if((e.clientX > container.x) && (e.clientX < (container.x + container.width))){ containers.splice(idx, 1); } }) }) animate()
e0b580176e815d3654697f38b4264f0cad3e01e2
[ "JavaScript" ]
1
JavaScript
jjliewie/teaching_for_loop
342549047779ce59127240fdc46a85ecac2100d3
5765eb06d3e24b6158aa082e8bd89da02a8aced4
refs/heads/master
<file_sep>import React, { Fragment } from "react"; import "./MovieCard.css"; export default function MovieCard(props) { // console.log(props); return ( <Fragment> <div className="card"> <img src={props.imgu} alt="gg" className="card-img-top" /> <div className="card-body"> <h5 className="card-title">{props.tit}</h5> <p className="card-text">{props.desc}</p> <h2 className="card-text"> {"☆".repeat(props.rt)} </h2> <a href="#home" className="btn btn-primary"> More </a> </div> </div> </Fragment> ); }
677619d1bb186768e3fcb3bde8944bf2b5fae2dc
[ "JavaScript" ]
1
JavaScript
MedHedii/React_hooks_checkpoint
6c11bcb7d90bdc978fbd3ee9008691a2b7e33eac
e596042928b17d18649ef1d1c3546e16887f1aeb
refs/heads/main
<file_sep>"use strict"; //materials const mat0 = new THREE.MeshBasicMaterial({ color: "black", side: THREE.DoubleSide }); const mat00 = new THREE.MeshBasicMaterial({ color: "black" }); const mat1 = new THREE.MeshBasicMaterial({ color: 0x25383c }); //postholder outside color const mat2 = new THREE.MeshBasicMaterial({ color: 0x4863a0, side: THREE.DoubleSide }); //bluegray const mat3 = new THREE.MeshBasicMaterial({ color: "red" }); const mat4 = new THREE.MeshBasicMaterial({ color: 0xbcc6cc }); // postcolor const mat5 = new THREE.MeshBasicMaterial({ color: 0x736F6E }); //grey const mat7 = new THREE.MeshBasicMaterial({ color: 0x25383c, side: THREE.DoubleSide }); //postholder outside color const mat8 = new THREE.MeshBasicMaterial(); const mat10 = new THREE.MeshBasicMaterial({ color: 0xc9dbdc, transparent: true, opacity: 0.8 }); //lens material grey //define global variables related to mouse action let rotate = false; //should the mouse rotate the view or drag the object? let dragItem, dragItem0, dragItem1, dragItem2; //the object to be dragged let active; //element selected by the mouse let intersects; //the objects intersected by raycaster let dragging = false; // is an object being dragged? let deltax, deltaz, deltay; //difference in the world coordinates of the object and the intersection point let startX, startY, prevX, prevY; //used for determining the rotation direction const raycaster = new THREE.Raycaster(); //add the raycaster for picking objects with the mouse const targetForDragging = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshBasicMaterial()); targetForDragging.rotation.x = -Math.PI * 0.5; targetForDragging.material.visible = false; //# of bases for elements const elements = 2; //arrays, so that an element can have the same index as its base const base = new Array(elements); const posthold = new Array(elements); const plaque = new Array(3); const lens = new Array(3); const lensholder = new Array(3); const newholder = new Array(3); let angle; let basetexture; let baseangle = 0; <file_sep>"use strict"; function laserhit() { //clear the screen ctx1.fillStyle = "#ffffff"; ctx1.fillRect(0, 0, canv1.width, canv1.height); ctx1.fillStyle = "#000000"; ctx1.beginPath(); ctx1.strokeStyle = "black"; for (let i = 16; i < 128; i += 16) { ctx1.moveTo(i, 0); ctx1.lineTo(i, 16); } ctx1.stroke(); screentexture.needsUpdate = true; render(); let intersects; // start the beam at the laser const raystart = new THREE.Vector3(-0.5, 4.6, 25); const raydirect = new THREE.Vector3(0, 0, -1); let raydirect1 = new THREE.Vector3(0, 0, -1); let canvradius = beamradius * 32; let screenhit = 0; let hit = false; //follow the beam do { hit = false; raycaster.set(raystart, raydirect); intersects = raycaster.intersectObjects(world.children, true); if (intersects.length != 0) { let item = intersects[0]; let objectHit = item.object; if (objectHit == screen) { intersectscreen(); } if (objectHit == slit[1]) { intersectslit1(); } if (objectHit == slit[2]) { intersectslit2(); } if (objectHit == slit[3]) { intersectslit3(); } if (objectHit == slit[4]) { intersectslit4(); } } } while (hit == true); function intersectscreen() { let coord = new THREE.Vector3(); coord.copy(intersects[0].point); let d = intersects[0].distance + 0.01; screen.worldToLocal(coord); //the screen dimensions are 4 by 2, the screencanvas is 128 px by 64 px if (screenhit == 0) { let cx = 32 * coord.x + 64; ctx1.fillStyle = "#ff0000"; ctx1.beginPath(); ctx1.ellipse(cx, 32, canvradius, canvradius, 0, 0, 2 * Math.PI); ctx1.fill(); } else if (screenhit == 1) { //single slit, width w = 20 micron, I ∝ sin^2(πw(sinθ)/λ)/(πw(sinθ)/λ)^2 for (let i = 0; i < 128; i++) { ctx1.beginPath(); let a = (i - 64) / 32 - coord.x; let b = 1; if (a != 0) { b = 4.963 * 20 * a / Math.sqrt(a * a + d * d); //πw(sinθ)/λ b = Math.sin(b) / b; b = b * b; b = Math.pow(b, 1 / 3); //approximating the response of the eye } // b sets the opacity of the color let col = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctx1.strokeStyle = col; ctx1.moveTo(i, 28); ctx1.lineTo(i, 36); ctx1.stroke(); } } else if (screenhit == 2) { //double slit, spacing d = 60 micron, I ∝ cos^2(πd(sinθ)/λ) * sin^2(πw(sinθ)/λ)/(πw(sinθ)/λ)^2 for (let i = 0; i < 128; i++) { ctx1.beginPath(); let a = (i - 64) / 32 - coord.x; let b = 1; if (a != 0) { b = 4.963 * 20 * a / Math.sqrt(a * a + d * d); //πw(sinθ)/λ let double = b * 3; //πd(sinθ)/λ b = Math.sin(b) / b; double = Math.cos(double) * Math.cos(double); b = b * b * double * double; b = Math.pow(b, 1 / 3); //approximating the response of the eye } let col = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctx1.strokeStyle = col; ctx1.moveTo(i, 28); ctx1.lineTo(i, 36); ctx1.stroke(); } } else if (screenhit == 3) { //hair width w = 50 micron, same as single slit but add bright spot in the center let cx = 32 * coord.x + 64; ctx1.fillStyle = "#ff0000"; ctx1.beginPath(); ctx1.ellipse(cx, 32, canvradius, canvradius, 0, 0, 2 * Math.PI); ctx1.fill(); for (let i = 0; i < 128; i++) { ctx1.beginPath(); let a = (i - 64) / 32 - coord.x; let b = 1; if (a != 0) { b = 4.963 * 50 * a / Math.sqrt(a * a + d * d); //πw(sinθ)/λ b = Math.sin(b) / b; b = b * b; b = Math.pow(b, 1 / 3); } let col = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctx1.strokeStyle = col; ctx1.moveTo(i, 28); ctx1.lineTo(i, 36); ctx1.stroke(); } } else if (screenhit == 4) { //four slits, slit spacing d = 60 micron for (let i = 0; i < 128; i++) { ctx1.beginPath(); let a = (i - 64) / 32 - coord.x; let b = 1; if (a != 0) { b = 4.963 * 20 * a / Math.sqrt(a * a + d * d); let quad = 2 * b * 3; //2πd(sinθ)/λ b = Math.sin(b) / b; b = b * b; let quad1 = 1 + Math.cos(quad) + Math.cos(2 * quad) + Math.cos(3 * quad); let quad2 = Math.sin(quad) + Math.sin(2 * quad) + Math.sin(3 * quad); quad = (quad1 * quad1 + quad2 * quad2) / 16; b = b * quad; b = Math.pow(b, 1 / 3); } let col = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctx1.strokeStyle = col; ctx1.moveTo(i, 28); ctx1.lineTo(i, 36); ctx1.stroke(); } } screentexture.needsUpdate = true; render(); } //check if one of the slit slides intersects the beam function intersectslit1() { if (screenhit == 0) { raystart.copy(intersects[0].point); raystart.add(raydirect1.multiplyScalar(0.01)); raycaster.set(raystart, raydirect); hit = true; screenhit = 1; render(); } } function intersectslit2() { if (screenhit == 0) { raystart.copy(intersects[0].point); raystart.add(raydirect1.multiplyScalar(0.01)); raycaster.set(raystart, raydirect); hit = true; screenhit = 2; render(); } } function intersectslit3() { if (screenhit == 0) { raystart.copy(intersects[0].point); raystart.add(raydirect1.multiplyScalar(0.01)); raycaster.set(raystart, raydirect); hit = true; screenhit = 3; render(); } } function intersectslit4() { if (screenhit == 0) { raystart.copy(intersects[0].point); raystart.add(raydirect1.multiplyScalar(0.01)); raycaster.set(raystart, raydirect); hit = true; screenhit = 4; render(); } } }<file_sep># 3D_optics_labs Source code for the laboratory environments at http://labman.phys.utk.edu/3D%20Physics/optics.html <file_sep>"use strict"; //materials const mat0 = new THREE.MeshBasicMaterial({ color: "black", side: THREE.DoubleSide }); const mat00 = new THREE.MeshBasicMaterial({ color: "black" }); const mat1 = new THREE.MeshBasicMaterial({ color: 0x25383c }); //postholder outside color const mat2 = new THREE.MeshBasicMaterial({ color: 0x4863a0, side: THREE.DoubleSide }); //bluegray const mat3 = new THREE.MeshBasicMaterial({ color: "red" }); const mat4 = new THREE.MeshBasicMaterial({ color: 0xbcc6cc }); // postcolor const mat5 = new THREE.MeshBasicMaterial({ color: 0x736F6E }); //grey //how to change colors //mat1.color.setHex( 0xff0000) //mat1.needsUpdate = true //define global variables related to mouse action const zero = 0; let selected = 1; let rotate = false; //should the mouse rotate the view or drag the object? let dragItem, dragItem0, dragItem1, dragItem2; //the object to be dragged let active; //element selected by the mouse let intersects; //the objects intersected by raycaster let dragging = false; // is an object being dragged? let deltax, deltaz, deltay, deltay1; //difference in the world coordinates of the object and the intersection point let startX, startY, prevX, prevY; //used for determining the rotation direction const raycaster = new THREE.Raycaster(); //add the raycaster for picking objects with the mouse const targetForDragging = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshBasicMaterial()); targetForDragging.rotation.x = -Math.PI * 0.5; targetForDragging.material.visible = false; //# of bases for elements const elements = 7; //arrays, so that an element can have the same index as its base const base = new Array(elements); const angle = new Array(elements); const basetexture = new Array(elements); const baseangle = new Array(elements); const posthold = new Array(elements); const ppost = new Array(elements); const polarizer = new Array(elements); const poltexture = new Array(elements); const polangle = new Array(elements); const polplaque = new Array(elements); //define the up direction const yvector = new THREE.Vector3(0, 1, 0); <file_sep>"use strict"; //plaque canvas const canvp = document.createElement('canvas'); const ctxp = canvp.getContext('2d'); canvp.width = 128; canvp.height = 32; ctxp.fillStyle = "#ffffff"; ctxp.fillRect(0, 0, canvp.width, canvp.height); ctxp.font = '12px Arial'; ctxp.fillStyle = 'black'; ctxp.fillText('He-Ne Laser', 3, 12); ctxp.fillText('with Beam Expander', 3, 28); const plaquetexture = new THREE.CanvasTexture(canvp); plaquetexture.needsUpdate = true; const plaquematerial = new THREE.MeshBasicMaterial({ map: plaquetexture }); //angle canvas const canv = document.createElement('canvas'); const ctx = canv.getContext('2d'); canv.width = 32; canv.height = 16; ctx.font = '12px Arial'; ctx.fillStyle = 'white'; ctx.fillText(zero.toFixed(1), 1, 12); for (let i = 0; i < elements; i++) { basetexture[i] = new THREE.CanvasTexture(canv); basetexture[i].needsUpdate = true; } for (let i = 0; i < elements; i++) { angle[i] = new THREE.Mesh(new THREE.PlaneGeometry(1.6, 0.8), new THREE.MeshBasicMaterial({ map: basetexture[i] })); angle[i].rotation.x = -Math.PI * 0.5; angle[i].position.y = 0.5; angle[i].position.z = 1; } //polarizer canvas const canvpol = document.createElement('canvas'); const ctxpol = canvpol.getContext('2d'); canvpol.width = 32; canvpol.height = 16; ctxpol.fillStyle = '#25383c'; ctxpol.fillRect(0, 0, 32, 16); ctxpol.font = '12px Arial'; ctxpol.fillStyle = 'white'; ctxpol.fillText(zero.toFixed(1), 1, 12); for (let i = 4; i < elements; i++) { poltexture[i] = new THREE.CanvasTexture(canvpol); poltexture[i].needsUpdate = true; polplaque[i] = new THREE.Mesh(new THREE.PlaneGeometry(1.4, 0.7), new THREE.MeshBasicMaterial({ map: poltexture[i] })); polplaque[i].position.z = 0.25; polplaque[i].position.y = -0.8; } //screen canvas const canv1 = document.createElement('canvas'); const ctx1 = canv1.getContext('2d'); canv1.width = 128; canv1.height = 64; const screentexture = new THREE.CanvasTexture(canv1); screentexture.needsUpdate = true; const screenmaterial = [ mat00, mat00, mat00, mat00, new THREE.MeshBasicMaterial({ map: screentexture }), mat00, ]; //viewer canvas const canv2 = document.createElement('canvas'); const ctx2 = canv2.getContext('2d'); canv2.width = 16; canv2.height = 32; const viewtexture = new THREE.CanvasTexture(canv2); viewtexture.needsUpdate = true; const viewmaterial = new THREE.MeshBasicMaterial({ map: viewtexture, side: THREE.DoubleSide, transparent: true, opacity: 0.5}); // glass slide canvas const canvs = document.createElement('canvas'); const ctxs = canvs.getContext('2d'); canvs.width = 32; canvs.height = 16 const canvstexture = new THREE.CanvasTexture(canvs); canvstexture.needsUpdate = true; const canvsmaterial = new THREE.MeshBasicMaterial({ map: canvstexture, side: THREE.DoubleSide}); <file_sep>"use strict"; function makeBoard() { const groundmesh = new THREE.Mesh(new THREE.PlaneGeometry(36, 36)); const loader = new THREE.TextureLoader(); loader.load('board.jpg', (texture) => { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.magFilter = THREE.NearestFilter; texture.repeat.set(36, 36); groundmesh.material = new THREE.MeshBasicMaterial({ map: texture }); render(); }); return groundmesh; } function makeLaser() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.87, 0.87, 7, 32); const laser0 = new THREE.Mesh(geometry0); laser0.position.z = 4.6; laser0.position.y = -1; const geometry1 = new THREE.BoxGeometry(2.8, 4.6, 4); const laser1 = new THREE.Mesh(geometry1); laser1.position.z = 2.3; laser0.updateMatrix(); laser1.updateMatrix(); singleGeometry.merge(laser1.geometry, laser1.matrix, 1); singleGeometry.merge(laser0.geometry, laser0.matrix, 2); const lasermaterial = [ mat2, mat2, mat2, mat0, mat0, mat0, ]; const lasermesh = new THREE.Mesh(singleGeometry, lasermaterial); const plaque1 = makePlaque(); lasermesh.add(plaque1); lasermesh.rotation.x = -Math.PI * 0.5; return lasermesh; } function makeBeamextender() { const geometry = new THREE.CylinderGeometry(0.8, 0.8, 3, 32); const extender = new THREE.Mesh(geometry, mat1); extender.position.z = 4.6; extender.position.y = 4; return extender; } function makeBeamexit() { const geometry = new THREE.CircleGeometry(beamradius, 32); const mat3a = new THREE.MeshBasicMaterial({ color: 0x220000 }); const bexit = new THREE.Mesh(geometry, mat3a); bexit.rotation.x = -Math.PI * 0.5; bexit.position.y = 1.505; return bexit; } function makePlaque() { const geometry = new THREE.PlaneGeometry(4, 1); const plaque = new THREE.Mesh(geometry, plaquematerial); plaque.rotation.y = -Math.PI * 0.5; plaque.rotation.x = Math.PI * 0.5; plaque.position.x = -1.51; plaque.position.z = 3; return plaque; } function makeBase(x, z) { const geometry = new THREE.BoxGeometry(4, 0.25, 4); const material = [ mat00, mat00, mat1, mat00, mat00, mat00, ]; const obj1 = new THREE.Mesh(geometry, material); obj1.position.y = 0.125; //bottom of base is at ground obj1.position.x = x; obj1.position.z = z; return obj1; } function makePostholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.25, 0.25, 2.5, 16, 1, 1); const postholder0 = new THREE.Mesh(geometry0); //inner cylinder postholder0.position.y = 1.65; //bottom of postholdertube is 0.4 units above ground const geometry1 = new THREE.CylinderGeometry(0.5, 0.5, 2.5, 16, 1, 1); const postholder1 = new THREE.Mesh(geometry1); //outer cylinder postholder1.position.y = 1.65; const geometry2 = new THREE.RingGeometry(0.25, 0.5, 16); const postholder2 = new THREE.Mesh(geometry2); postholder2.position.y = 2.9; //top cap postholder2.rotation.x = -Math.PI * 0.5; const geometry3 = new THREE.CylinderGeometry(0.25, 0.25, 0.2, 16, 1); const postholder3 = new THREE.Mesh(geometry3); //knob postholder3.position.y = 2.5; postholder3.position.z = 0.6; postholder3.rotation.x = -Math.PI * 0.5; const geometry4 = new THREE.CylinderGeometry(2, 2, 0.1, 16); const postholder4 = new THREE.Mesh(geometry4); // bottom plate to hold angle scale postholder4.position.y = 0.3; postholder0.updateMatrix(); postholder1.updateMatrix(); postholder2.updateMatrix(); postholder3.updateMatrix(); postholder4.updateMatrix(); singleGeometry.merge(postholder0.geometry, postholder0.matrix, 0); singleGeometry.merge(postholder1.geometry, postholder1.matrix, 1); singleGeometry.merge(postholder2.geometry, postholder2.matrix, 1); singleGeometry.merge(postholder3.geometry, postholder3.matrix, 3); singleGeometry.merge(postholder4.geometry, postholder4.matrix, 4); const postmaterial = [ mat0, mat1, mat1, mat2, mat5, mat5, ]; const holdermesh = new THREE.Mesh(singleGeometry, postmaterial); return holdermesh; } function makeScreenholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 3.2, 16, 1); const post0 = new THREE.Mesh(geometry0); //this is the post post0.position.y = 1.6; //the post is 3.2 units high and its bottom is at y = 0 post0.updateMatrix(); singleGeometry.merge(post0.geometry, post0.matrix); const holdermaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); const postmesh = new THREE.Mesh(singleGeometry, holdermaterial); return postmesh; } function makeScreen() { const geometry1 = new THREE.BoxGeometry(4, 2, 0.2); const screenmesh = new THREE.Mesh(geometry1, screenmaterial); return screenmesh; } <file_sep>"use strict"; //respond to wheel movement function doWheel(evt) { //zoom in or out cr = cr + evt.deltaY / 10; cr = Math.min(100, Math.max(30, cr)); camera.position.z = cr * Math.sin(cth) * Math.cos(cph); camera.position.y = cr * Math.cos(cth); camera.position.x = cr * Math.sin(cth) * Math.sin(cph); camera.lookAt(0, 0, 0); camera.updateProjectionMatrix(); render(); } //respond to mousedowm function doMouseDown(evt) { if (dragging) { return; } let x = evt.clientX let y = evt.clientY prevX = startX = x; prevY = startY = y; //check if the mouse pointer is over an object that can be dragged dragging = mouseDownFunc(x, y, evt); //true if mousepointer is over a visible object, including the ground if (dragging) { canvas.addEventListener("pointermove", doMouseMove); canvas.addEventListener("pointerup", doMouseUp); } } //decide if the mouse is over an object that can be dragged function mouseDownFunc(x, y) { if (targetForDragging.parent == world) { world.remove(targetForDragging); //the initial object should be a visible object } //cast a ray from the camera to the mouse pointer and find out if it intersects any child of the world let a = 2 * x / canvas.width - 1; let b = 1 - 2 * y / canvas.height; raycaster.setFromCamera(new THREE.Vector2(a, b), camera); let intersects = raycaster.intersectObjects(world.children, true); if (intersects.length === 0) { return false; } //the mousepointer is over a child of the world //there are children of children; ground, base postholder, post, attached element //unless the gound is intersected, dragItem2 will be the child that was actually intersected, dragItem will be the corresponding base let item = intersects[0]; let objectHit = item.object; dragItem = dragItem0 = dragItem1 = dragItem2 = objectHit; if (objectHit.parent != world) { objectHit = objectHit.parent; dragItem = objectHit; } if (objectHit.parent != world) { dragItem0 = objectHit; objectHit = objectHit.parent; dragItem = objectHit; } if (objectHit.parent != world) { dragItem1 = dragItem0; dragItem0 = objectHit; objectHit = objectHit.parent; dragItem = objectHit; } if (objectHit == world.children[0]) { dragItem = world.children[1]; //otherwise I get a weird snap of the ground rotate = true; //if the mousepointer is over the ground, we want the mouse to rotate the view, not drag an object return true; } else { //keep track of which base is selected in a global variable for (let i = 1; i < elements + 1; i++) { if (objectHit == world.children[i]) { active = i; } } //get the nominal world position of the selected base and post const itemvec = new THREE.Vector3(); const itemvec1 = new THREE.Vector3(); dragItem.getWorldPosition(itemvec); //itemvec is the world position of the base which can be dragged dragItem1.getWorldPosition(itemvec1); //itemvec1 is the world position of the post which can be raised //calculate the difference between the raycaster intersection point and the nominal world position of the object deltax = item.point.x - itemvec.x; deltaz = item.point.z - itemvec.z; deltay = item.point.y - itemvec.y; deltay1 = item.point.y - itemvec1.y; world.add(targetForDragging); //add an invisible plane at the height of the interection point targetForDragging.position.set(0, item.point.y, 0); render(); return true; } } //we only check for mouse move events if dragging is true function doMouseMove(evt) { if (dragging) { let x = evt.clientX let y = evt.clientY //which mouse action is selected? if (rotate) { //rotate the view let dx = prevX - startX; let dy = prevY - startY; cth = cth - dy / 1000; cth = Math.min(1.49, Math.max(0.08, cth)); cph = (cph - dx / 1000) % (2 * Math.PI); camera.position.z = cr * Math.sin(cth) * Math.cos(cph); camera.position.y = cr * Math.cos(cth); camera.position.x = cr * Math.sin(cth) * Math.sin(cph); camera.lookAt(0, 0, 0); camera.updateProjectionMatrix(); startX = prevX; startY = prevY; prevX = x; prevY = y; render(); } else if (selected == 2) { //lift the post mouseDragFuncUp(x, y); } else if (selected == 3) { //rotate the post mouseDragFuncRot(x); } else if (selected == 4) { //tilt the mirror mouseDragFuncTilt(y); } else { //move the base mouseDragFunc(x, y); } } } //drag in the xz plane function mouseDragFunc(x, y) { let a = 2 * x / canvas.width - 1; let b = 1 - 2 * y / canvas.height; raycaster.setFromCamera(new THREE.Vector2(a, b), camera); const intersects = raycaster.intersectObject(targetForDragging); //when the base + childeren is dragged, the intersection point has to stay the same height above the ground if (intersects.length == 0) { return; } let locationX = intersects[0].point.x; let locationZ = intersects[0].point.z; let locationY = intersects[0].point.y; let coords = new THREE.Vector3(locationX - deltax, locationY - deltay, locationZ - deltaz); //coords hold the new worl position of the base //we want to make sure that we do not drag bases off the table or into each other world.worldToLocal(coords); let cond = 1; for (let i = 1; i < elements + 1; i++) { if (i != active && Math.abs(world.children[i].position.z - coords.z) <= 4) { //check for collisions if (Math.abs(world.children[i].position.x - coords.x) <= 4) { cond = 0; break; } } } if (cond == 1) { a = Math.min(17.5, Math.max(-17.5, coords.x)); //set limits b = Math.min(17.5, Math.max(-17.5, coords.z)); dragItem.position.set(a, coords.y, b); } laserhit(); render(); } // drag in the y-direction function mouseDragFuncUp(x, y) { if (dragItem1 != dragItem0) { //if the mousepointer was over the post let a = 2 * x / canvas.width - 1; let b = 1 - 2 * y / canvas.height; raycaster.setFromCamera(new THREE.Vector2(a, b), camera); const intersects = raycaster.intersectObject(dragItem1); if (intersects.length == 0) { return; } //and if the mouse pointer stays over the post let locationY = intersects[0].point.y - deltay1; const itemvec = new THREE.Vector3(); dragItem1.getWorldPosition(itemvec); let coords = new THREE.Vector3(itemvec.x, locationY, itemvec.z); world.worldToLocal(coords); b = Math.min(1.5, Math.max(0, coords.y)); //set limits dragItem1.position.y = b; laserhit(); render(); } } function mouseDragFuncRot(x) { if (dragItem != dragItem0) { //if the mousepointer was over the postholder let rotangle = 0; let dx = prevX - startX; dragItem0.rotateY(dx / 1000); let _x = dragItem0.rotation.x; let _y = dragItem0.rotation.y; //console.log(_x, _y); weird way threejs defines rotation angles if (_x == -0) { rotangle = 2 * Math.PI + _y } else { rotangle = 2 * Math.PI - _y - _x; } let b = (rotangle * 180 / Math.PI) % 360; baseangle[active - 1] = rotangle; ctx.clearRect(0, 0, canv.width, canv.height); //ctx.fillText(`${b}`, 4, 13); ctx.fillText(b.toFixed(1), 1, 12); basetexture[active - 1].needsUpdate = true; startX = prevX; prevX = x; laserhit(); render(); } } function mouseDragFuncTilt(y) { if (dragItem1 != dragItem2 && dragItem2 == mirror[2] || dragItem2 == mirror[3]) { //if the mousepointer was over the mirror let dy = prevY - startY; dragItem2.rotateX(dy / 1000); startY = prevY; prevY = y; laserhit(); render(); } } //reset function doMouseUp() { if (dragging) { canvas.removeEventListener("pointermove", doMouseMove); canvas.removeEventListener("pointerup", doMouseUp); if (snap == true) { const a = Math.floor(dragItem.position.x) + 0.5; const b = Math.floor(dragItem.position.z) + 0.5; dragItem.position.set(a, 0.125, b); laserhit(); render(); } dragging = false; rotate = false; } } <file_sep>"use strict"; function makeBoard() { const groundmesh = new THREE.Mesh(new THREE.PlaneGeometry(36, 36)); const loader = new THREE.TextureLoader(); loader.load('board.jpg', (texture) => { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.magFilter = THREE.NearestFilter; texture.repeat.set(36, 36); groundmesh.material = new THREE.MeshBasicMaterial({ map: texture }); render(); }); return groundmesh; } function makeLaser() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.87, 0.87, 7, 32); const laser0 = new THREE.Mesh(geometry0); laser0.position.z = 4.6; laser0.position.y = -1; const geometry1 = new THREE.BoxGeometry(2.8, 4.6, 4); const laser1 = new THREE.Mesh(geometry1); laser1.position.z = 2.3; laser0.updateMatrix(); laser1.updateMatrix(); singleGeometry.merge(laser1.geometry, laser1.matrix, 1); singleGeometry.merge(laser0.geometry, laser0.matrix, 2); const lasermaterial = [ mat2, mat2, mat2, mat0, mat0, mat0, ]; const lasermesh = new THREE.Mesh(singleGeometry, lasermaterial); const plaque1 = makePlaque(); lasermesh.add(plaque1); lasermesh.rotation.x = -Math.PI * 0.5; return lasermesh; } function makeBeamextender() { const geometry = new THREE.CylinderGeometry(0.8, 0.8, 3, 32); const extender = new THREE.Mesh(geometry, mat1); extender.position.z = 4.6; extender.position.y = 4; return extender; } function makeBeamexit() { const geometry = new THREE.CircleGeometry(beamradius, 32); const mat3a = new THREE.MeshBasicMaterial({ color: 0x220000 }); const bexit = new THREE.Mesh(geometry, mat3a); bexit.rotation.x = -Math.PI * 0.5; bexit.position.y = 1.505; return bexit; } function makePlaque() { const geometry = new THREE.PlaneGeometry(4, 1); const plaque = new THREE.Mesh(geometry, plaquematerial); plaque.rotation.y = -Math.PI * 0.5; plaque.rotation.x = Math.PI * 0.5; plaque.position.x = -1.51; plaque.position.z = 3; return plaque; } function makeBase(x, z) { const geometry = new THREE.BoxGeometry(4, 0.25, 4); const material = [ mat00, mat00, mat1, mat00, mat00, mat00, ]; const obj1 = new THREE.Mesh(geometry, material); obj1.position.y = 0.125; //bottom of base is at ground obj1.position.x = x; obj1.position.z = z; return obj1; } function makePostholder(height) { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.25, 0.25, height, 16, 1, 1); const postholder0 = new THREE.Mesh(geometry0); //inner cylinder postholder0.position.y = 0.4 + height / 2; //bottom of postholdertube is 0.4 units above ground const geometry1 = new THREE.CylinderGeometry(0.5, 0.5, height, 16, 1, 1); const postholder1 = new THREE.Mesh(geometry1); //outer cylinder postholder1.position.y = 0.4 + height / 2; const geometry2 = new THREE.RingGeometry(0.25, 0.5, 16); const postholder2 = new THREE.Mesh(geometry2); postholder2.position.y = height + 0.4; //top cap postholder2.rotation.x = -Math.PI * 0.5; const geometry3 = new THREE.CylinderGeometry(0.25, 0.25, 0.2, 16, 1); const postholder3 = new THREE.Mesh(geometry3); //knob postholder3.position.y = height; postholder3.position.z = 0.6; postholder3.rotation.x = -Math.PI * 0.5; const geometry4 = new THREE.CylinderGeometry(2, 2, 0.1, 16); const postholder4 = new THREE.Mesh(geometry4); // bottom plate to hold angle scale postholder4.position.y = 0.3; postholder0.updateMatrix(); postholder1.updateMatrix(); postholder2.updateMatrix(); postholder3.updateMatrix(); postholder4.updateMatrix(); singleGeometry.merge(postholder0.geometry, postholder0.matrix, 0); singleGeometry.merge(postholder1.geometry, postholder1.matrix, 1); singleGeometry.merge(postholder2.geometry, postholder2.matrix, 1); singleGeometry.merge(postholder3.geometry, postholder3.matrix, 3); singleGeometry.merge(postholder4.geometry, postholder4.matrix, 4); const postmaterial = [ mat0, mat1, mat1, mat2, mat5, mat5, ]; const holdermesh = new THREE.Mesh(singleGeometry, postmaterial); return holdermesh; } function makeMeterholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 3.2, 16, 1); const meterholder0 = new THREE.Mesh(geometry0); //this is the post meterholder0.position.y = 1.6; //the post is 3.2 units high and its bottom is at y = 0 const geometry1 = new THREE.CylinderGeometry(0.75, 0.75, 1, 16); const meterholder1 = new THREE.Mesh(geometry1); meterholder1.position.y = 3.9; meterholder1.rotation.x = -Math.PI * 0.5; meterholder0.updateMatrix(); meterholder1.updateMatrix(); singleGeometry.merge(meterholder0.geometry, meterholder0.matrix); singleGeometry.merge(meterholder1.geometry, meterholder1.matrix); const loader = new THREE.TextureLoader(); const mat6 = new THREE.MeshBasicMaterial({ map: loader.load('bluetooth.jpg'), }); //const holdermaterial = new THREE.MeshBasicMaterial({ color: 0x657383 }); const holdermaterial = [ mat00, mat6, mat1, ]; const mholdermesh = new THREE.Mesh(singleGeometry, holdermaterial); return mholdermesh; } function makeMeter() { const geometry = new THREE.CylinderGeometry(0.25, 0.4, 0.4, 16, 1); const metermesh = new THREE.Mesh(geometry); metermesh.rotation.x = -Math.PI * 0.5; metermesh.position.z = 0.385; return metermesh; } function makeScreenholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 3.2, 16, 1); const post0 = new THREE.Mesh(geometry0); //this is the post post0.position.y = 1.6; //the post is 3.2 units high and its bottom is at y = 0 post0.updateMatrix(); singleGeometry.merge(post0.geometry, post0.matrix); const holdermaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); const postmesh = new THREE.Mesh(singleGeometry, holdermaterial); return postmesh; } function makeScreen() { const geometry1 = new THREE.BoxGeometry(4, 2, 0.2); const screenmesh = new THREE.Mesh(geometry1, screenmaterial); return screenmesh; } function makeViewerpostholder() { const singleGeometry = new THREE.Geometry(); const geometry1 = new THREE.CylinderGeometry(0.5, 0.5, 1, 16); const postholder1 = new THREE.Mesh(geometry1); postholder1.position.y = 0.9; //bottom of postholder tube is 0.4 units above ground //the top is 1.4 units above ground const geometry4 = new THREE.CylinderGeometry(2, 2, 0.1, 16); const postholder4 = new THREE.Mesh(geometry4); postholder4.position.y = 0.3; postholder1.updateMatrix(); postholder4.updateMatrix(); singleGeometry.merge(postholder1.geometry, postholder1.matrix, 0); singleGeometry.merge(postholder4.geometry, postholder4.matrix, 1); const postmaterial = [ mat1, mat5, mat5, ]; const holdermesh = new THREE.Mesh(singleGeometry, postmaterial); return holdermesh; } function makeViewerpost() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 0.4, 16); const post0 = new THREE.Mesh(geometry0); post0.position.y = 1.2; //the viewerpost is essentially invisible //the top is 1.4 units above ground post0.updateMatrix(); singleGeometry.merge(post0.geometry, post0.matrix); const postmesh = new THREE.Mesh(singleGeometry, mat1); return postmesh; } function makeViewer() { const geometry1 = new THREE.PlaneGeometry(3, 6); const viewer1 = new THREE.Mesh(geometry1, viewmaterial); viewer1.position.y = 4.4; return viewer1; } function makePolarizerpost() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 2.8, 16); const post0 = new THREE.Mesh(geometry0); post0.position.y = 1.4; //the top is 2.2 units above ground post0.updateMatrix(); singleGeometry.merge(post0.geometry, post0.matrix); const postmesh = new THREE.Mesh(singleGeometry, mat00); return postmesh; } function makePolarizer() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.5, 0.5, 0.25, 16, 1, 1); const pol0 = new THREE.Mesh(geometry0); //inner cylinder pol0.rotation.x = -Math.PI * 0.5; const geometry1 = new THREE.CylinderGeometry(1.4, 1.4, 0.25, 16, 1, 1); const pol1 = new THREE.Mesh(geometry1); //outer cylinder pol1.rotation.x = -Math.PI * 0.5; const geometry2 = new THREE.RingGeometry(0.5, 1.4, 16); //top cap const pol2 = new THREE.Mesh(geometry2); pol2.position.z = 0.125 const geometry3 = new THREE.RingGeometry(0.5, 1.4, 16); //bottom cap const pol3 = new THREE.Mesh(geometry3); pol3.position.z = -0.125 const geometry4 = new THREE.CircleGeometry(0.5, 16); //polarizer const pol4 = new THREE.Mesh(geometry4); pol0.updateMatrix(); pol1.updateMatrix(); pol2.updateMatrix(); pol3.updateMatrix(); pol4.updateMatrix(); singleGeometry.merge(pol4.geometry, pol4.matrix, 0); singleGeometry.merge(pol0.geometry, pol0.matrix, 1); singleGeometry.merge(pol1.geometry, pol1.matrix, 2); singleGeometry.merge(pol2.geometry, pol2.matrix, 3); singleGeometry.merge(pol3.geometry, pol3.matrix, 3); const mat8 = new THREE.MeshBasicMaterial({ color: "black", side: THREE.DoubleSide, transparent: true, opacity: 0.5 }); const mat7 = new THREE.MeshBasicMaterial({ color: 0x25383c, side: THREE.DoubleSide }); const polmaterial = [ mat8, mat1, mat1, mat7, ]; const pmesh = new THREE.Mesh(singleGeometry, polmaterial); return pmesh; } function makeglass() { const geometry = new THREE.BoxGeometry(2.8, 1.4, 0.1); const material = [ mat0, mat0, mat0, mat0, canvsmaterial, mat0, ]; const block = new THREE.Mesh(geometry, material); return block; }<file_sep>vti_encoding:SR|utf8-nl vti_author:SR|UT-LENOVO\\Marianne vti_modifiedby:SR|UT-LENOVO\\Marianne vti_timelastmodified:TR|23 Nov 2020 23:17:04 -0000 vti_timecreated:TR|17 May 2020 20:06:44 -0000 vti_extenderversion:SR|6.0.2.8161 vti_backlinkinfo:VX|diffraction/diffraction.html vti_syncwith_labman.phys.utk.edu\:80/3d physics:TX|25 May 2020 22:07:12 -0000 vti_syncofs_labman.phys.utk.edu\:80/3d physics:TW|24 Nov 2020 00:33:49 -0000 vti_nexttolasttimemodified:TR|17 May 2020 20:06:44 -0000 vti_cacheddtm:TX|25 May 2020 22:07:12 -0000 vti_filesize:IR|5313 vti_syncwith_electron9.phys.utk.edu\:80/3d physics:TX|25 May 2020 22:07:12 -0000 vti_syncofs_electron9.phys.utk.edu\:80/3d physics:TW|24 Nov 2020 00:27:58 -0000 <file_sep>let radius = 12.7 / 10; //const lensa = [51.68 / 10, 4.585 / 10]; //const lensa = [25.943 / 10, 6.3213 / 10]; const lensa = [19.69 / 10, 7.643 / 10]; const lensb = [103.36 / 10, 3.783 / 10]; //const lensc = [102.577 / 10, 4.578 / 10]; const lensc = [50.806 / 10, 6.226 / 10]; //const lensc = [38.085/ 10, 7.360/ 10]; function makeBoard() { const groundmesh = new THREE.Mesh(new THREE.PlaneGeometry(6, 36)); const loader = new THREE.TextureLoader(); loader.load('board.jpg', (texture) => { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.magFilter = THREE.NearestFilter; texture.repeat.set(6, 36); groundmesh.material = new THREE.MeshBasicMaterial({ map: texture }); render(); }); return groundmesh; } function makeTable() { const geometry = new THREE.PlaneGeometry(26, 36); const mat = new THREE.MeshBasicMaterial({ color: 0x4d3319 }); const tablemesh = new THREE.Mesh(geometry, mat); return tablemesh; } function makeHolderblock() { const geometry = new THREE.BoxGeometry(2, 2, 24); const mat = new THREE.MeshBasicMaterial({ color: 0xc68c53 }); const box = new THREE.Mesh(geometry, mat); const cgeometry = new THREE.CircleGeometry(0.3, 32); const circle1 = new THREE.Mesh(cgeometry, mat0); circle1.rotation.x = Math.PI / 2. circle2 = circle1.clone(); circle3 = circle1.clone(); circle1.position.set(0, 1.02, 10); circle2.position.set(0, 1.02, 0); circle3.position.set(0, 1.02, -10); box.add(circle1); box.add(circle2); box.add(circle3) return box; } function holderText() { const geometry = new THREE.PlaneGeometry(2, 1); const holderplaque = new THREE.Mesh(geometry); return holderplaque; } function makeRailbox() { const geometry = new THREE.BoxGeometry(6.2, 0.25, 36); const box = new THREE.Mesh(geometry, mat0); return box; } function makeRail() { const railmesh = new THREE.Mesh(new THREE.BoxGeometry(1, 0.5, 36)); const loader = new THREE.TextureLoader(); // load a resource loader.load("scale.jpg", (texture1) => { texture1.wrapS = THREE.RepeatWrapping; texture1.wrapT = THREE.RepeatWrapping; texture1.magFilter = THREE.NearestFilter; texture1.repeat.set(1, 36); mat8.map = texture1; const railmaterial = [ mat00, mat00, mat8, mat00, mat00, mat00, ]; railmesh.material = railmaterial; render(); }); return railmesh; } function makeLaser() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.87, 0.87, 7, 32); const laser0 = new THREE.Mesh(geometry0); laser0.position.z = 4.6; laser0.position.y = -1; const geometry1 = new THREE.BoxGeometry(2.8, 4.6, 4); const laser1 = new THREE.Mesh(geometry1); laser1.position.z = 2.3; laser0.updateMatrix(); laser1.updateMatrix(); singleGeometry.merge(laser1.geometry, laser1.matrix, 1); singleGeometry.merge(laser0.geometry, laser0.matrix, 2); const lasermaterial = [ mat2, mat2, mat2, mat0, mat0, mat0, ]; const lasermesh = new THREE.Mesh(singleGeometry, lasermaterial); const plaque1 = makePlaque(); lasermesh.add(plaque1); lasermesh.rotation.x = -Math.PI * 0.5; return lasermesh; } function makeBeamextender() { const geometry = new THREE.CylinderGeometry(0.8, 0.8, 3, 32); const extender = new THREE.Mesh(geometry, mat1); extender.position.z = 4.6; extender.position.y = 4; return extender; } function makeBeamexit() { const geometry = new THREE.CircleGeometry(0.6, 32); const mat3a = new THREE.MeshBasicMaterial({ color: 0x110000 }); const bexit = new THREE.Mesh(geometry, mat3a); bexit.rotation.x = -Math.PI * 0.5; bexit.position.y = 1.505; return bexit; } function makePlaque() { const geometry = new THREE.PlaneGeometry(4, 1); const plaquematerial = makeplaquemat(); const plaque = new THREE.Mesh(geometry, plaquematerial); plaque.rotation.y = -Math.PI * 0.5; plaque.rotation.x = Math.PI * 0.5; plaque.position.x = -1.51; plaque.position.z = 3; return plaque; } function makeBase(x, z, w) { const geometry = new THREE.BoxGeometry(4, 0.25, w); const material = [ mat00, mat00, mat1, mat00, mat00, mat00, ]; const obj1 = new THREE.Mesh(geometry, material); obj1.position.y = 0.125; //bottom of base is at ground obj1.position.x = x; obj1.position.z = z; return obj1; } function makePostholder(height) { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.25, 0.25, height, 16, 1, 1); const postholder0 = new THREE.Mesh(geometry0); //inner cylinder postholder0.position.y = 0.4 + height / 2; //bottom of postholdertube is 0.4 units above ground const geometry1 = new THREE.CylinderGeometry(0.5, 0.5, height, 16, 1, 1); const postholder1 = new THREE.Mesh(geometry1); //outer cylinder postholder1.position.y = 0.4 + height / 2; const geometry2 = new THREE.RingGeometry(0.25, 0.5, 16); const postholder2 = new THREE.Mesh(geometry2); postholder2.position.y = height + 0.4; //top cap postholder2.rotation.x = -Math.PI * 0.5; const geometry3 = new THREE.CylinderGeometry(0.25, 0.25, 0.2, 16, 1); const postholder3 = new THREE.Mesh(geometry3); //knob postholder3.position.y = height; postholder3.position.z = 0.6; postholder3.rotation.x = -Math.PI * 0.5; const geometry4 = new THREE.CylinderGeometry(1, 1, 0.1, 16); const postholder4 = new THREE.Mesh(geometry4); // bottom plate to hold angle scale postholder4.position.y = 0.3; postholder0.updateMatrix(); postholder1.updateMatrix(); postholder2.updateMatrix(); postholder3.updateMatrix(); postholder4.updateMatrix(); singleGeometry.merge(postholder0.geometry, postholder0.matrix, 0); singleGeometry.merge(postholder1.geometry, postholder1.matrix, 1); singleGeometry.merge(postholder2.geometry, postholder2.matrix, 1); singleGeometry.merge(postholder3.geometry, postholder3.matrix, 3); singleGeometry.merge(postholder4.geometry, postholder4.matrix, 4); const postmaterial = [ mat0, mat1, mat1, mat2, mat5, mat5, ]; const holdermesh = new THREE.Mesh(singleGeometry, postmaterial); return holdermesh; } function makeScreenholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(0.24, 0.24, 3.2, 16, 1); const post0 = new THREE.Mesh(geometry0); //this is the post post0.position.y = 2; //the post is 3.2 units high and its bottom is at y = 0.4 post0.updateMatrix(); singleGeometry.merge(post0.geometry, post0.matrix); const holdermaterial = new THREE.MeshBasicMaterial({ color: 0xffffff }); const postmesh = new THREE.Mesh(singleGeometry, holdermaterial); return postmesh; } function makeScreen() { const geometry1 = new THREE.BoxGeometry(4, 2, 0.2); const screenmesh = new THREE.Mesh(geometry1, screenmaterial); return screenmesh; } function makeLensholder() { const singleGeometry = new THREE.Geometry(); const geometry0 = new THREE.CylinderGeometry(1.3, 1.3, 0.1, 16, 1, 1); const pol0 = new THREE.Mesh(geometry0); //inner cylinder pol0.rotation.x = -Math.PI * 0.5; const geometry1 = new THREE.CylinderGeometry(1.4, 1.4, 0.1, 16, 1, 1); const pol1 = new THREE.Mesh(geometry1); //outer cylinder pol1.rotation.x = -Math.PI * 0.5; const geometry2 = new THREE.RingGeometry(1.3, 1.4, 16); //top cap const pol2 = new THREE.Mesh(geometry2); pol2.position.z = 0.05 const geometry3 = new THREE.RingGeometry(1.3, 1.4, 16); //bottom cap const pol3 = new THREE.Mesh(geometry3); pol3.position.z = -0.05 const geometry4 = new THREE.CylinderGeometry(0.24, 0.24, 2.8, 16); const pol4 = new THREE.Mesh(geometry4); pol4.position.y = -2.8; //the post is 2.8 units high and its bottom is at y = 0.4 pol0.updateMatrix(); pol1.updateMatrix(); pol2.updateMatrix(); pol3.updateMatrix(); pol4.updateMatrix(); singleGeometry.merge(pol4.geometry, pol4.matrix, 0); singleGeometry.merge(pol0.geometry, pol0.matrix, 1); singleGeometry.merge(pol1.geometry, pol1.matrix, 1); singleGeometry.merge(pol2.geometry, pol2.matrix, 1); singleGeometry.merge(pol3.geometry, pol3.matrix, 1); const polmaterial = [ mat0, mat7, ]; const pmesh = new THREE.Mesh(singleGeometry, polmaterial); return pmesh; } function makePlanoconvex(lens) { R1 = lens[0]; Tc = lens[1]; const singleGeometry = new THREE.Geometry(); const angle = Math.asin(radius / R1); const Te = Tc - R1 * (1 - Math.cos(angle)); const position = Te / 2 const geometry0 = new THREE.SphereGeometry(R1, 32, 32, 0, Math.PI * 2, 0, angle); const plan0 = new THREE.Mesh(geometry0); //curved side plan0.rotation.x = Math.PI * 0.5; plan0.position.z = -R1 + Tc; const geometry1 = new THREE.CylinderGeometry(radius, radius, Te, 32); const plan1 = new THREE.Mesh(geometry1); //plane side plan1.rotation.x = Math.PI * 0.5; plan1.position.z = position; plan0.updateMatrix(); plan1.updateMatrix(); singleGeometry.merge(plan0.geometry, plan0.matrix); singleGeometry.merge(plan1.geometry, plan1.matrix); const planmesh = new THREE.Mesh(singleGeometry, mat10); return planmesh; } function makeBiconvex(lens) { R1 = lens[0]; Tc = lens[1]; const singleGeometry = new THREE.Geometry(); const angle = Math.asin(radius / R1); const Te = Tc - 2 * R1 * (1 - Math.cos(angle)); //const position = Te / 2 const geometry0 = new THREE.SphereGeometry(R1, 32, 32, 0, Math.PI * 2, 0, angle); const plan0 = new THREE.Mesh(geometry0); //curved side plan0.rotation.x = Math.PI * 0.5; plan0.position.z = -R1 + Tc / 2; const plan3 = new THREE.Mesh(geometry0); plan3.rotation.x = -Math.PI * 0.5; plan3.position.z = R1 - Tc / 2; const geometry1 = new THREE.CylinderGeometry(radius, radius, Te, 32); const plan1 = new THREE.Mesh(geometry1); //plane side plan1.rotation.x = Math.PI * 0.5; //plan1.position.z = position; plan0.updateMatrix(); plan1.updateMatrix(); plan3.updateMatrix(); singleGeometry.merge(plan0.geometry, plan0.matrix); singleGeometry.merge(plan1.geometry, plan1.matrix); singleGeometry.merge(plan3.geometry, plan3.matrix); const planmesh = new THREE.Mesh(singleGeometry, mat10); return planmesh; }<file_sep>"use strict"; function laserhit() { //clear all screens ctx1.fillStyle = "#ffffff"; //screen canvas ctx1.fillRect(0, 0, canv1.width, canv1.height); ctx1.fillStyle = "#000000"; ctx1.beginPath(); for (let i = 16; i < 128; i += 16) { ctx1.moveTo(i, 0); ctx1.lineTo(i, 16); } ctx1.stroke(); ctx2.fillStyle = "#c9dbdc"; //viewer canvas ctx2.fillRect(0, 0, canv2.width, canv2.height); ctxf.fillStyle = "#c9dbdc"; //glass block front canvas ctxf.fillRect(0, 0, canvf.width, canvf.height); ctxm.fillStyle = "#c9dbdc"; //mirror canvas ctxm.fillRect(0, 0, canvm.width, canvm.height); for (let i = 2; i < 4; i++) { mirrortexture[i].needsUpdate = true; } screentexture.needsUpdate = true; viewtexture.needsUpdate = true; canvftexture.needsUpdate = true; canvbtexture.needsUpdate = true; render(); let intersects; // start the beam at the laser let lpower = 1.5; const raystart = new THREE.Vector3(-0.5, 4.6, 25); const raydirect = new THREE.Vector3(0, 0, -1); let raydirect1 = new THREE.Vector3(0, 0, -1); let canvradius = beamradius * 16; let hit = false; //follow the beam do { hit = false; raycaster.set(raystart, raydirect); intersects = raycaster.intersectObjects(world.children, true); if (intersects.length != 0) { let item = intersects[0]; let objectHit = item.object; if (objectHit == viewer) { //if the beam hits the viewer restart it from there intersectviewer(); } if (objectHit == screen) { //if the beam hits the screen it terminates intersectscreen(); } if (objectHit == mirror[2]) { //if the beam hits a mirror restart it from there intersectmirror(2); } if (objectHit == mirror[3]) { intersectmirror(3); } if (objectHit == glassblock) { //if the beam hits the glass block, it may restart fom the othere side intersectglassblock(); } } } while (hit == true); function intersectscreen() { //first check if the laser beam hits the front of the screen const s = Math.sin(baseangle[1]); const c = Math.cos(baseangle[1]); const screendirect = new THREE.Vector3(-s, 0, -c); let dot = screendirect.dot(raydirect); if (dot > 0) { const cross = screendirect.cross(raydirect); cross.normalize(); const crossy = cross.y const crossangle = Math.acos(crossy); //acos yiels an anle between 0 and pi let coord = new THREE.Vector3(); coord.copy(intersects[0].point); //world coordinates of center of beam on the screen screen.worldToLocal(coord); //world coordinates of center of beem on the screen //the screen dimensions are 4 by 2, the screencanvas is 128 px by 64 px let cx = 32 * coord.x + 64; //sreencanvas coordinates of center of beam let cy = -32 * coord.y + 32; ctx1.fillStyle = "#ff0000"; ctx1.beginPath(); dot = Math.max(dot, 0.001); //the beam spot on the screencanvas will be an ellipse //scale the major axis by 1/dot, rotate it with respect to the x-axis by -crossangle ctx1.ellipse(cx, cy, 2 * canvradius / dot, 2 * canvradius, -crossangle, 0, 2 * Math.PI); ctx1.fill(); screentexture.needsUpdate = true; render() } } function intersectviewer() { const s = Math.sin(baseangle[0]); const c = Math.cos(baseangle[0]); const screendirect = new THREE.Vector3(-s, 0, -c); let dot = screendirect.dot(raydirect); const cross = screendirect.cross(raydirect); cross.normalize(); const crossy = cross.y const crossangle = Math.acos(crossy); if (dot < 0) { //the beam can pass through the viewer from both sides screendirect.set(s, 0, c); dot = screendirect.dot(raydirect); } let coord = new THREE.Vector3(); coord.copy(intersects[0].point); viewer.worldToLocal(coord); //the viewer dimensions are 3 by 6, the viewercanvas is 16 px by 32 px let cx = 8 * coord.x / 1.5 + 8; //viewercanvas coordinates of center of beam let cy = -16 * coord.y / 3 + 16; ctx2.fillStyle = "#ff0000"; ctx2.beginPath(); dot = Math.max(dot, 0.001); //the beam spot on the viewercanvas will be an ellipse //scale the major axis by 1/dot, rotate it with respect to the x-axis by -crossangle ctx2.ellipse(cx, cy, canvradius / 4 / dot, canvradius / 4, -crossangle, 0, 2 * Math.PI); ctx2.fill(); viewtexture.needsUpdate = true; render(); raystart.copy(intersects[0].point); raydirect1.copy(raydirect); raystart.add(raydirect1.multiplyScalar(0.01)); //start a new ray at the viewer exit hit = true; } function intersectmirror(i) { let screendirect1 = new THREE.Vector3(0, 0, -1); const tilt = -mirror[i].rotation.x - Math.PI / 2; const st = Math.sin(tilt); const ct = Math.cos(tilt); const s = ct * Math.sin(baseangle[i]); const c = ct * Math.cos(baseangle[i]); const screendirect = new THREE.Vector3(-s, -st, -c); screendirect.normalize(); //the normal to the mirror, into the mirror let dot = screendirect.dot(raydirect); if (dot > 0) { dot = Math.max(dot, 0.001); raystart.copy(intersects[0].point); raydirect.add(screendirect.multiplyScalar(-2 * dot)); //find the direction of the reflected beam raydirect.normalize(); raydirect1.copy(raydirect); raystart.add(raydirect1.multiplyScalar(0.01)); //start the reflected beam hit = true; dot = Math.max(dot, 0.001); screendirect1.copy(screendirect); const cross = screendirect1.cross(raydirect); cross.normalize(); const crossy = cross.y; const crossangle = Math.acos(crossy); //acos yiels an anle between 0 and pi let coord = new THREE.Vector3(); coord.copy(intersects[0].point); mirror[i].worldToLocal(coord); let cx = 16 * coord.z + 8; //mirror is rotated; should probably change mirror to single geometry let cy = 16 * coord.x + 8; let b = lpower / 100; b = Math.pow(b, 1 / 3); ctxm.fillStyle = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctxm.beginPath(); //scale the major axis by 1/dot, rotate it with respect to the x-axis by -crossangle ctxm.ellipse(cx, cy, canvradius, canvradius / dot, -crossangle, 0, 2 * Math.PI); ctxm.fill(); mirrortexture[i].needsUpdate = true; render(); } } function intersectglassblock() { //the block dimensions are 2.6 by 1.4, the block canvas is 32 px by 16 px let coord = new THREE.Vector3(); coord.copy(intersects[0].point); glassblock.worldToLocal(coord); if (Math.abs(coord.x) < 1.3995) { //check if the ray does not hit the edges if (Math.abs(coord.y) < 0.6995) { let scale = 16 / 1.4; let lray = new THREE.Vector3(); const screendirect = new THREE.Vector3(0, 0, -1); //the block coordinate system is rotated ccw by baseangle abouyt the y-axis const s = Math.sin(baseangle[4]); const c = Math.cos(baseangle[4]); lray.z = raydirect.z * c + raydirect.x * s; lray.x = -raydirect.z * s + raydirect.x * c; lray.y = raydirect.y; lray.normalize(); //the direction of the incident beam in the block coordinate system let dot = screendirect.dot(lray); if (dot > 0) { //the front dot let cx = scale * coord.x + 16; let cy = -scale * coord.y + 8; let b = lpower / 100; b = Math.pow(b, 1 / 3); ctxf.fillStyle = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctxf.beginPath(); //scale the major axis by 1/dot ctxf.ellipse(cx, cy, canvradius / dot / 1.4, canvradius / 1.4, 0, 0, 2 * Math.PI); ctxf.fill(); canvftexture.needsUpdate = true; //the back dot let rcoord = new THREE.Vector3(); let dx = - lray.x * 2.8 / lray.z; //the minus sign is there because lray.z is negative let dy = - lray.y * 2.8 / lray.z; let mult = 0; let tantheta = Math.sqrt(Math.pow(lray.x, 2) + Math.pow(lray.y, 2)) / lray.z; //the minus sign does not matter in the ratio below if (tantheta != 0) { //Snell's law let theta = Math.atan(tantheta); let thetar = Math.asin(Math.sin(theta) / 1.6); mult = Math.tan(thetar) / tantheta; } rcoord.x = coord.x + mult * dx; //these are the coordinates of the beam at the exit rcoord.y = coord.y + mult * dy; rcoord.z = -1.4; hit = false; if (Math.abs(rcoord.x) < 1.3995) { if (Math.abs(rcoord.y) < 0.6995) { glassblock.localToWorld(rcoord); raystart.copy(rcoord); raydirect1.copy(raydirect); raystart.add(raydirect1.multiplyScalar(0.01)); hit = true; } } } if (dot < 0) { //repeat with entrance and exit sides switched //the back dot let cx = -scale * coord.x + 16; let cy = -scale * coord.y + 8; let b = lpower / 100; b = Math.pow(b, 1 / 3); ctxf.fillStyle = "rgba(" + 255 + "," + 0 + "," + 0 + ", " + b + ")"; ctxf.beginPath(); //scale the major axis by 1/dot ctxf.ellipse(cx, cy, canvradius / -1 * dot / 1.4, canvradius / 1.4, 0, 0, 2 * Math.PI); ctxf.fill(); canvbtexture.needsUpdate = true; //the front dot let rcoord = new THREE.Vector3(); let dx = lray.x * 2.8 / lray.z; let dy = lray.y * 2.8 / lray.z; let mult = 0; let tantheta = Math.sqrt(Math.pow(lray.x, 2) + Math.pow(lray.y, 2)) / lray.z; if (tantheta != 0) { let theta = Math.atan(tantheta); let thetar = Math.asin(Math.sin(theta) / 1.6); mult = Math.tan(thetar) / tantheta; } rcoord.x = coord.x + mult * dx; rcoord.y = coord.y + mult * dy; rcoord.z = 1.4; hit = false; if (Math.abs(rcoord.x) < 1.3995) { if (Math.abs(rcoord.y) < 0.6995) { glassblock.localToWorld(rcoord); raystart.copy(rcoord); raydirect1.copy(raydirect); raystart.add(raydirect1.multiplyScalar(0.01)); hit = true; } } } } } } }
65684746fad1de4af641e0026272026a3397ad73
[ "JavaScript", "Markdown" ]
11
JavaScript
zjlmmm-github/3D_optics_labs
4636a68c4677fdfde209a55e03493b894453ff91
5576d0ce019493471e821f9ee1774eeec95bef58
refs/heads/master
<file_sep>window.onload = function() { let printbtn = document.getElementById("print"); printbtn.addEventListener('click', () => { let details = document.querySelectorAll("details"); details.forEach((each) => { each.setAttribute("open", "open"); }); window.print(); }); let btn = document.getElementById("toggle"); btn.addEventListener('click', () => { let details = document.querySelectorAll("details"); let opened = false; details.forEach((each) => { if (!opened) opened = each.hasAttribute("open"); }); details.forEach((each) => { if (opened) { each.removeAttribute("open"); } else { each.setAttribute("open", "open"); } }); }); }<file_sep>class Photo < ApplicationRecord belongs_to :user validates :link, :description, :user, presence: true paginates_per 2 max_paginates_per 100 end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'csv' user=User.where(:id=>1).first raise StandardError, "Project not found." if user.nil? Photo.destroy_all csv_text = File.read(Rails.root.join('lib', 'seeds', 'link.csv')) csv= CSV.parse(csv_text, :headers=>true, :encoding =>"ISO-8859-1") csv.each do |row| link_name=row['link'] description= row['description'] unless Photo.exists?(:link=>link_name) Photo.create!(:link=>link_name, :description => description, :user=>user) end end <file_sep>class UserControllerController < ApplicationController def index @users= User.first @experience= User.first.experiences @education= User.first.educations @projects=User.first.personalprojects @awards=User.first.personalawards end end <file_sep>class CreateJoinTableExperiencesAddresses < ActiveRecord::Migration[5.2] def change create_join_table :experiences, :addresses do |t| # t.index [:experience_id, :address_id] # t.index [:address_id, :experience_id] end end end <file_sep>class Experience < ApplicationRecord has_and_belongs_to_many :address belongs_to :user validates :title, :company, :start, :user_id, :address, :description, presence: true end <file_sep>class User < ApplicationRecord has_and_belongs_to_many :address has_many :experiences has_many :personalprojects has_many :personalawards has_many :educations has_many :photos validates :name, :dob, :address, presence: true validate :dob, :validate_date def validate_date unless dob<Date.current errors.add(:dob,"must be today or before") end end end <file_sep>class CreatePersonalawards < ActiveRecord::Migration[5.2] def change create_table :personalawards do |t| t.string :title t.string :issuer t.string :description t.date :from t.date :to t.integer :user_id t.timestamps end end end <file_sep>class Address < ApplicationRecord has_and_belongs_to_many :users has_and_belongs_to_many :experiences has_and_belongs_to_many :educations validates :street, :city, :state, :zipcode, :country, presence: true validate :state, :state_length_validator validates_length_of :zipcode, is: 5, message: "Zip code must be of length 5" def state_length_validator unless state.length == 2 errors.add(:state, "must always le of length 2") end end end <file_sep>class CreateJoinTableEducationsAddresses < ActiveRecord::Migration[5.2] def change create_join_table :educations, :addresses do |t| # t.index [:education_id, :address_id] # t.index [:address_id, :education_id] end end end <file_sep>class PhotoController < ApplicationController def photo @photo=Photo.order(created_at: :desc).page(params[:page]).per(15) end end <file_sep>class Education < ApplicationRecord has_and_belongs_to_many :addresses belongs_to :user validates :school, :degree, :field, :from, :user, presence: true end
cba6a4a6d21429dfb04822dfea1cb0ba265cb1ca
[ "JavaScript", "Ruby" ]
12
JavaScript
sduwal/portfolio
efeaececf8bb0bf5792fc636983b735f415eba15
6600efeca7584df698bc8310548befde3aaf82f6
refs/heads/master
<file_sep>package com.arx_era.digitalattendance; /** * Created by AaronStone on 1/15/2017. */ public class AppConfig { public static final String DATA_URL = "http://192.168.94.1/Android/College/getData.php?id="; public static final String KEY_NAME = "name"; public static final String KEY_EMAIL = "email"; public static final String KEY_VC = "vc"; public static final String JSON_ARRAY = "result"; // Server user login url public static String URL_LOGIN = "https://appcom.000webhostapp.com/DA/login.php"; // Server user register url public static String URL_REGISTER = "https://appcom.000webhostapp.com/DA/register.php"; }
0ed0c64af4b02583dd0bb45bcfba3283716fb469
[ "Java" ]
1
Java
tronix99/DigitalAttendanceR
2abf8108ee3e19702788ec3dfd7cc58e7828f7c8
ce3aea908e1f9d9bd9a19ac9e7643b8e5494537a
refs/heads/master
<repo_name>Night-Owl-La/Android-Library<file_sep>/util/DeepLinkParser.kt // Test -> scheme://host?category=상품권&detail=해피머니 fun parseDeepLinkParam(deepLink: String): Map<String, String> { val paramDelimiterIndex = deepLink.indexOf("?") + 1 val isEven = { number: Int -> number % 2 == 0 } val keyList = mutableListOf<String>() val valueList = mutableListOf<String>() deepLink.slice(paramDelimiterIndex until deepLink.length) .split("&") .asSequence() .flatMap { it.split("=") } .forEachIndexed { index, s -> if (isEven(index)) keyList.add(s) else valueList.add(s) } return keyList.zip(valueList).toMap() } <file_sep>/util/util.kt package util import android.app.Activity import android.view.inputmethod.InputMethodManager fun Activity.hideKeyBoard(): Boolean = with(this) { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow( currentFocus?.windowToken, 0 ) }<file_sep>/README.md # AndroidLibrary Android Library
036cce662bfd47fee38bfca647e2af6c84c87594
[ "Markdown", "Kotlin" ]
3
Kotlin
Night-Owl-La/Android-Library
9640b2bccab128f751f8c79f777849557f972425
c69ec2b6b55f3a6505248bc20fd176a97bf47280
refs/heads/master
<file_sep>### # app configuration # http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html ### [app:main] use = egg:sipkd reload_templates = true debug_authorization = false debug_notfound = false debug_routematch = false debug_templates = true default_locale_name = en sqlalchemy.url = postgresql://aagusti:a@192.168.56.1/sipkd #sipkd_sqlalchemy.url = mssql+pyodbc:///?odbc_connect=DRIVER%3D%7BFreeTDS%7D%3BServer%3D172.16.17.32%3BDatabase%3DV%40LID49V6_2016%3BUID%3Dsa%3BPWD%3Dm4rg0nd454!%3BPort%3D1433%3BTDS_Version%3D8.0 sipkd_sqlalchemy.url = postgresql://aagusti:a@192.168.56.1/sipkd pyramid.includes = pyramid_tm session.type = ext:database session.secret = s0s3cr3t session.cookie_expires = true session.key = WhatEver session.url = postgresql://aagusti:a@192.168.56.1/sipkd session.timeout = 3000 session.lock_dir = %(here)s/tmp timezone = Asia/Jakarta #localization = id_ID.UTF-8 localization = English_Australia.1252 static_files = %(here)s/../files [server:main] use = egg:waitress#main host = 0.0.0.0 port = 6544 # Begin logging configuration [loggers] keys = root, sipkd, sqlalchemy [handlers] keys = console [formatters] keys = generic [logger_root] level = INFO handlers = console [logger_sipkd] level = DEBUG handlers = qualname = sipkd [logger_sqlalchemy] level = INFO handlers = qualname = sqlalchemy.engine # "level = INFO" logs SQL queries. # "level = DEBUG" logs SQL queries and results. # "level = WARN" logs neither. (Recommended for production systems.) [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s # End logging configuration <file_sep>x1 = '2015-00001' x2 = '2015-00002' x3 = x2.split('/') xs = '' import re for x in x3: if xs: xs +='/' xs += x[2:] print re.sub('-','',xs) <file_sep>import locale try: from urllib.parse import (urlencode, quote, quote_plus,) except: from urllib import (urlencode, quote, quote_plus,) from types import (UnicodeType, StringType) from pyramid.config import Configurator from pyramid_beaker import session_factory_from_settings from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.events import subscriber from pyramid.events import BeforeRender from pyramid.interfaces import IRoutesMapper from pyramid.httpexceptions import ( default_exceptionresponse_view, HTTPFound, ) from pyramid.renderers import JSON import datetime, decimal, time from sqlalchemy import engine_from_config from .security import ( group_finder, get_user, ) from .models import ( DBSession, Base, init_model, Route ) from .tools import ( DefaultTimeZone, money, should_int, thousand, as_timezone, split, get_settings, dmy, ) # http://stackoverflow.com/questions/9845669/pyramid-inverse-to-add-notfound-viewappend-slash-true class RemoveSlashNotFoundViewFactory(object): def __init__(self, notfound_view=None): if notfound_view is None: notfound_view = default_exceptionresponse_view self.notfound_view = notfound_view def __call__(self, context, request): if not isinstance(context, Exception): # backwards compat for an append_notslash_view registered via # config.set_notfound_view instead of as a proper exception view context = getattr(request, 'exception', None) or context path = request.path registry = request.registry mapper = registry.queryUtility(IRoutesMapper) if mapper is not None and path.endswith('/'): noslash_path = path.rstrip('/') for route in mapper.get_routes(): if route.match(noslash_path) is not None: qs = request.query_string if qs: noslash_path += '?' + qs return HTTPFound(location=noslash_path) return self.notfound_view(context, request) # https://groups.google.com/forum/#!topic/pylons-discuss/QIj4G82j04c def has_permission_(request, perm_names): if type(perm_names) in [str]: perm_names = [perm_names] for perm_name in perm_names: if request.has_permission(perm_name): return True @subscriber(BeforeRender) def add_global(event): event['has_permission'] = has_permission_ event['urlencode'] = urlencode event['quote_plus'] = quote_plus event['quote'] = quote event['money'] = money event['should_int'] = should_int event['thousand'] = thousand event['as_timezone'] = as_timezone event['split'] = split event['allow_register'] = allow_register event['change_unit'] = change_unit def allow_register(request): settings = get_settings() allow_register = 'allow_register' in settings and settings['allow_register']=='true' or False return allow_register def change_unit(request): settings = get_settings() change_unit = 'change_unit' in settings and settings['change_unit']=='true' or False return change_unit def get_title(request): route_name = request.matched_route.name return titles[route_name] def get_company(request): settings = get_settings() company = 'company' in settings and settings['company'] or 'openSIPKD' return company.upper() def get_departement(request): settings = get_settings() departement = 'departement' in settings and settings['departement'] or 'DEPARTEMEN INFORMATION TEKNOLOGI' return departement def get_ibukota(request): settings = get_settings() ibukota = 'ibukota' in settings and settings['ibukota'] or 'BEKASI' return ibukota def get_address(request): settings = get_settings() address_1 = 'address_1' in settings and settings['address_1'] or 'ALAMAT DEPARTEMEN BARIS 1' return address_1 def get_address2(request): settings = get_settings() address_2 = 'address_2' in settings and settings['address_2'] or 'ALAMAT DEPARTEMEN BARIS 2' return address_2 def get_app_name(request): settings = get_settings() app_name = 'app_name' in settings and settings['app_name'] or 'openSIPKD Application' return app_name def get_gmap_key(request): settings = get_settings() return 'gmap_key' in settings and settings['gmap_key'] or '' main_title = 'openSIPKD' titles = {} def get_modules(request): settings = get_settings() if not settings: settings = request moduls = 'modules' in settings and settings['modules'] and settings['modules'].split(',') or [] result = {} for modul in moduls: if modul.find(':')>-1: key, val = modul.strip().split(':') else: key = modul.strip() val = '' #key.upper() result[key] = val return result def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine init_model() session_factory = session_factory_from_settings(settings) if 'localization' not in settings: settings['localization'] = 'id_ID.UTF-8' locale.setlocale(locale.LC_ALL, settings['localization']) if 'timezone' not in settings: settings['timezone'] = DefaultTimeZone config = Configurator(settings=settings, root_factory='opensipkd.models.RootFactory', session_factory=session_factory) modules = get_modules(settings) for module in modules: if module=='admin': continue module = module.replace('/','.') mfile = 'opensipkd.'+module m = __import__(mfile,globals(), locals(),'main',0) m.main(global_config, **settings) config.include('pyramid_beaker') config.include('pyramid_chameleon') authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=group_finder, hashalg='sha512') authz_policy = ACLAuthorizationPolicy() config.set_authentication_policy(authn_policy) config.set_authorization_policy(authz_policy) config.add_request_method(get_user, 'user', reify=True) config.add_request_method(get_title, 'title', reify=True) config.add_request_method(get_company, 'company', reify=True) config.add_request_method(get_departement, 'departement', reify=True) config.add_request_method(get_ibukota, 'ibukota', reify=True) config.add_request_method(get_address, 'address', reify=True) config.add_request_method(get_address2, 'address2', reify=True) config.add_request_method(get_app_name, 'app_name', reify=True) config.add_request_method(get_modules, 'modules', reify=True) #config.add_request_method(thousand, 'thousand', reify=True) config.add_notfound_view(RemoveSlashNotFoundViewFactory()) config.add_static_view('static', 'static', cache_max_age=3600) config.add_static_view('deform_static', 'deform:static') config.add_static_view('files', settings['static_files']) config.add_renderer('csv', '.tools.CSVRenderer') routes = DBSession.query(Route.kode, Route.path, Route.nama).\ filter(Route.type==0).all() #standar route for route in routes: config.add_route(route.kode, route.path) if route.nama: titles[route.kode] = route.nama ############################################################################ #Custom JSON json_renderer = JSON() json_renderer.add_adapter(datetime.datetime, lambda v, request: dmy(v)) json_renderer.add_adapter(datetime.date, lambda v, request: dmy(v)) json_renderer.add_adapter(decimal.Decimal, lambda v, request: str(v)) config.add_renderer('json', json_renderer) ############################################################################ # JSON RPC config.include('pyramid_rpc.jsonrpc') json_renderer = JSON() json_renderer.add_adapter(datetime.datetime, lambda v, request: v.isoformat()) json_renderer.add_adapter(datetime.date, lambda v, request: v.isoformat()) config.add_renderer('json_rpc', json_renderer) routes = DBSession.query(Route.kode, Route.path, Route.nama).\ filter(Route.type==1).all() # for route in routes: config.add_jsonrpc_endpoint(route.kode, route.path, default_renderer="json_rpc") ############################################################################ #config.add_jsonrpc_endpoint('ws_pbb', '/pbb/api', default_renderer="json_rpc") #config.add_jsonrpc_endpoint('ws_keuangan', '/ws/keuangan', default_renderer="json_rpc") #config.add_jsonrpc_endpoint('ws_user', '/ws/user', default_renderer="json_rpc") ############################################################################ ########################################### #MAP ########################################### if 'map' in modules: import papyrus from papyrus.renderers import GeoJSON, XSD config.add_request_method(get_gmap_key, 'gmap', reify=True) config.include(papyrus.includeme) config.add_renderer('geojson', GeoJSON()) config.add_renderer('xsd', XSD()) config.add_static_view('static_map', 'map/static', cache_max_age=3600) if 'map/aset' in modules: config.add_static_view('static_map_aset', 'map/aset/static', cache_max_age=3600) if 'map/pbb' in modules: config.add_static_view('static_map_pbb', 'map/pbb/static', cache_max_age=3600) config.scan() app = config.make_wsgi_app() from paste.translogger import TransLogger app = TransLogger(app, setup_console_handler=False) return app <file_sep>from datetime import datetime from sqlalchemy import ( Column, Integer, Text, DateTime, ForeignKey, UniqueConstraint, String, SmallInteger ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, backref ) from ..models import DefaultModel, Base, DBSession class WsUser(Base, DefaultModel): __tablename__ = 'user_ws' __table_args__ = {'extend_existing':True} user_name = Column(String(128), nullable=False) user_password = Column(String(256), nullable=False) email = Column(String(100), nullable=False) status = Column(SmallInteger, nullable=False) last_login_date = Column(DateTime(timezone=False)) registered_date = Column(DateTime(timezone=False)) @classmethod def query(cls): return DBSession.query(cls) @classmethod def query_name(cls, user_name): return cls.query().filter_by(user_name=user_name) @classmethod def query_email(cls, email): return cls.query().filter_by(email=email) @classmethod def query_identity(cls, identity): if identity.find('@') > -1: return cls.query_email(identity) return cls.query_name(identity) @classmethod def by_id(cls, user_id, db_session=None): """ .. deprecated:: 0.8 :param user_id: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_id(user_id=user_id, db_session=db_session) @classmethod def by_user_name(cls, user_name, db_session=None): """ .. deprecated:: 0.8 :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_user_name(user_name=user_name, db_session=db_session) @classmethod def by_user_name_and_security_code(cls, user_name, security_code, db_session=None): """ .. deprecated:: 0.8 :param user_name: :param security_code: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_user_name_and_security_code( user_name=user_name, security_code=security_code, db_session=db_session) @classmethod def by_user_names(cls, user_names, db_session=None): """ .. deprecated:: 0.8 :param user_names: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_user_names(user_names=user_names, db_session=db_session) @classmethod def user_names_like(cls, user_name, db_session=None): """ .. deprecated:: 0.8 :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.user_names_like(user_name=user_name, db_session=db_session) @classmethod def by_email(cls, email, db_session=None): """ .. deprecated:: 0.8 :param email: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_email(email=email, db_session=db_session) @classmethod def by_email_and_username(cls, email, user_name, db_session=None): """ .. deprecated:: 0.8 :param email: :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.by_email_and_username(email=email, user_name=user_name, db_session=db_session) @classmethod def users_for_perms(cls, perm_names, db_session=None): """ .. deprecated:: 0.8 :param perm_names: :param db_session: :return: """ db_session = get_db_session(db_session) return UserService.users_for_perms(perm_names=perm_names, db_session=db_session) @classmethod def get_by_email(cls, email): return DBSession.query(cls).filter_by(email=email).first() @classmethod def get_by_name(cls, name): return DBSession.query(cls).filter_by(user_name=name).first() @classmethod def get_by_identity(cls, identity): if identity.find('@') > -1: return cls.get_by_email(identity) return cls.get_by_name(identity) <file_sep>/home/aagusti/env-sipkd/bin/python <file_sep>../env/bin/pserve test.ini --reload <file_sep>/home/aagusti/env-sipkd/bin/pserve test2.ini --reload <file_sep>sipkd README For create Ziggurat tables run: ~/env/bin/initialize_sipkd_db development.ini <file_sep>#from sqlalchemy.sql.expression import text #from pyramid.view import view_config from hashlib import md5 from datetime import datetime from ...models import ( DBSession, User, ) import hmac import hashlib import base64 #import json #import requests from ...tools import ( get_settings, ) LIMIT = 1000 CODE_OK = 0 CODE_NOT_FOUND = -1 CODE_DATA_INVALID = -2 CODE_INVALID_LOGIN = -10 CODE_NETWORK_ERROR = -11 ######## # Auth # ######## def auth(username, signature, fkey): user = User.get_by_name(username) if not user: return value = "%s&%s" % (username,fkey); key = str(user.user_password) lsignature = hmac.new(key, msg=value, digestmod=hashlib.sha256).digest() encodedSignature = base64.encodestring(lsignature).replace('\n', '') if encodedSignature==signature: return user def auth_from_rpc(request): print request.environ user = auth(request.environ['HTTP_USERID'], request.environ['HTTP_SIGNATURE'], request.environ['HTTP_KEY']) if user: return dict(code=CODE_OK, message='OK'), user return dict(code=CODE_INVALID_LOGIN, message='Gagal login'), user def get_rpc_header(userid,password): utc_date = datetime.utcnow() tStamp = int((utc_date-datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S')).total_seconds()) value = "%s&%s" % (str(userid),tStamp) key = str(password) signature = hmac.new(key, msg=value, digestmod=hashlib.sha256).digest() encodedSignature = base64.encodestring(signature).replace('\n', '') headers = {'userid':userid, 'signature':encodedSignature, 'key':tStamp} return headers <file_sep>/home/aagusti/env-sipkd/bin/initialize_sipkd_db test2.ini
45e76442774e1ea73b8f9877963095171eee40d6
[ "Shell", "Python", "Text", "INI" ]
10
INI
aagusti/sipkd
54d07c66b65f25ba1a8bab7b4e8c5edb7d582492
695d16487001a235f639346efa0024d724c3d449
refs/heads/master
<repo_name>wangyuanyangV5/springlearn<file_sep>/src/main/java/design_patterns/command/com/LightOnCommand.java package design_patterns.command.com; import design_patterns.command.com.Command; import design_patterns.command.light.Light; /** * Created by dell on 2019/1/2. */ public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light){ this.light = light; } @Override public void execute() { light.on(); } } <file_sep>/src/main/java/design_patterns/singleton/Singleton1.java package design_patterns.singleton; /** * Created by dell on 2019/1/2. */ public class Singleton1 { private Singleton1(){ } private volatile static Singleton1 singleton1; public static Singleton1 getSingleton1(){ if(singleton1 == null){ synchronized (Singleton1.class){ if(singleton1 == null){ singleton1 = new Singleton1(); } } } return singleton1; } } <file_sep>/src/main/java/design_patterns/command/hotel_test/Waiter.java package design_patterns.command.hotel_test; import java.util.List; /** * Created by dell on 2019/1/2. */ public class Waiter { private List<CommandCook> commandCooks; public void setCommandCooks(List<CommandCook> commandCooks){ this.commandCooks = commandCooks; } public void takeOrder(){ commandCooks.forEach(commandCook -> commandCook.orderUp()); } } <file_sep>/src/main/java/design_patterns/command/hotel_test/CommandCook.java package design_patterns.command.hotel_test; /** * Created by dell on 2019/1/2. */ public interface CommandCook { void orderUp(); } <file_sep>/build.gradle group 'springframework' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() // maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } } configurations { mybatisGenerator } dependencies { compile 'org.springframework:spring-context:5.1.0.RELEASE' compile 'org.springframework:spring-aspects:5.1.0.RELEASE' compile 'org.springframework:spring-jdbc:5.1.0.RELEASE' compile 'org.springframework:spring-test:5.1.0.RELEASE' compile 'org.springframework:spring-web:5.1.0.RELEASE' compile 'org.springframework:spring-webmvc:5.1.0.RELEASE' // compile 'org.springframework:spring-websocket:3.2.6.RELEASE' // compile 'org.springframework:spring-messaging:3.2.6.RELEASE' //compile 'org.springframework:spring-webflux:3.2.6.RELEASE' compile 'javax.servlet:javax.servlet-api:4.0.1' compile 'org.mybatis:mybatis:3.4.4' compile 'org.mybatis:mybatis-spring:1.3.0' compile "org.projectlombok:lombok:1.16.6" compile 'c3p0:c3p0:0.9.1.2' compile "org.slf4j:slf4j-log4j12:1.7.16" compile 'mysql:mysql-connector-java:5.1.40' compile 'cglib:cglib:3.1' compile 'org.mybatis.generator:mybatis-generator-core:1.3.5' compile 'mysql:mysql-connector-java:5.1.40' compile 'tk.mybatis:mapper:3.3.9' mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.5' mybatisGenerator 'mysql:mysql-connector-java:5.1.40' mybatisGenerator 'tk.mybatis:mapper:3.3.9' testCompile group: 'junit', name: 'junit', version: '4.12' } def getDbProperties = { def properties = new Properties() file("src/main/resources/jdbc.properties").withInputStream { inputStream -> properties.load(inputStream) } properties } task mybatisGenerate << { def properties = getDbProperties() ant.properties['targetProject'] = projectDir.path ant.properties['driverClass'] = properties.getProperty("jdbc.driverClassName") ant.properties['connectionURL'] = properties.getProperty("jdbc.url") ant.properties['userId'] = properties.getProperty("jdbc.username") ant.properties['password'] = properties.getProperty("jdbc.password") ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path ant.properties['modelPackage'] = properties.getProperty("package.model") ant.properties['mapperPackage'] = properties.getProperty("package.mapper") ant.properties['sqlMapperPackage'] = properties.getProperty("package.xml") ant.taskdef( name: 'mbgenerator', classname: 'org.mybatis.generator.ant.GeneratorAntTask', classpath: configurations.mybatisGenerator.asPath ) ant.mbgenerator(overwrite: true, configfile: 'src/main/resources/generatorConfig.xml', verbose: true) { propertyset { propertyref(name: 'targetProject') propertyref(name: 'userId') propertyref(name: 'driverClass') propertyref(name: 'connectionURL') propertyref(name: 'password') propertyref(name: 'src_main_java') propertyref(name: 'src_main_resources') propertyref(name: 'modelPackage') propertyref(name: 'mapperPackage') propertyref(name: 'sqlMapperPackage') } } }<file_sep>/src/main/java/mybatis/Executor/DefaultExecutor.java package mybatis.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * Created by dell on 2019/1/10. */ public class DefaultExecutor implements Executor { private static Logger log = LoggerFactory.getLogger(DefaultExecutor.class); @Override public <T> T query(String statement, Object parameter) { try { DataSource dataSource = getDataSource(); Connection connection= dataSource.getConnection(); String sql = String.format(statement,parameter); PreparedStatement pstmt = connection.prepareStatement(sql); log.error(sql); ResultSet resultSet = pstmt.executeQuery(); while (resultSet.next()){ log.error(String.format("name:%s",resultSet.getString(1))); } }catch (Exception e){ e.printStackTrace(); } return null; } public DataSource getDataSource(){ DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); driverManagerDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test"); driverManagerDataSource.setUsername("root"); driverManagerDataSource.setPassword("<PASSWORD>"); return driverManagerDataSource; } } <file_sep>/src/main/java/design_patterns/command/hotel_test/DanChaoFanCommand.java package design_patterns.command.hotel_test; /** * Created by dell on 2019/1/2. */ public class DanChaoFanCommand implements CommandCook{ Cooker cooker; public void setCooker(Cooker cooker){ this.cooker = cooker; } @Override public void orderUp() { cooker.danChaoFan(); } } <file_sep>/src/main/java/design_patterns/command/hotel_test/NiuPaiCommand.java package design_patterns.command.hotel_test; /** * Created by dell on 2019/1/2. */ public class NiuPaiCommand implements CommandCook { Cooker cooker; public void setCooker(Cooker cooker){ this.cooker = cooker; } @Override public void orderUp() { cooker.niuPai(); } } <file_sep>/src/main/java/springmybatis/mapper/CityMapper.java package springmybatis.mapper; import java.util.List; import springmybatis.model.City; public interface CityMapper { int deleteByPrimaryKey(Long id); int insert(City record); City selectByPrimaryKey(Long id); List<City> selectAll(); int updateByPrimaryKey(City record); }<file_sep>/src/main/java/com/mybatis/mapper/CountryMapper.java //package com.mybatis.mapper; // //import com.mybatis.model.Country; //import java.util.List; // //public interface CountryMapper { // int deleteByPrimaryKey(Integer id); // // int insert(Country record); // // Country selectByPrimaryKey(Integer id); // // List<Country> selectAll(); // // int updateByPrimaryKey(Country record); //}<file_sep>/settings.gradle rootProject.name = 'codelearn' <file_sep>/src/main/java/beanfactory/beanFactoryPostProcessor/Bean.java package beanfactory.beanFactoryPostProcessor; import org.springframework.stereotype.Component; /** * Created by dell on 2018/12/23. */ @Component public class Bean { } <file_sep>/src/main/java/com/mybatis/copy/EnableMapper.java package com.mybatis.copy; import org.mybatis.spring.annotation.MapperScannerRegistrar; import org.springframework.context.annotation.Import; import java.lang.annotation.*; /** * Created by dell on 2018/12/24. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(WangScannerRegistrar.class) public @interface EnableMapper { } <file_sep>/src/main/java/design_patterns/strategy_pattern/Duck.java package design_patterns.strategy_pattern; /** * Created by dell on 2018/12/28. * 策略模式 */ public abstract class Duck { private Fly fly; private int age; public abstract void preform(); public void fly(){ fly.playFly();; } public int getAge(){ return age; } protected void setFly(Fly fly) { this.fly = fly; } } <file_sep>/src/main/java/leetcode/my11.java package leetcode; /** * Created by dell on 2019/2/20. */ public class my11 { public static void main(String[] args) { } public static int maxArea(int[] height) { if(height.length < 2) return 0; int left = 0; int right = 1; int hight = Math.min(height[left],height[right]); int maxhigh = Math.max(height[left],height[right]); long result = hight * (right - left); for(int i= 3; i < height.length;++ i){ if(height[i] > hight){ } } return 0; } } /** * 1,8 面积 1 * 1,8,6 */ <file_sep>/src/test/java/BeenFactorTest.java import factory.Student; import org.junit.*; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by dell on 2018/12/4. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Student.class) public class BeenFactorTest { Logger log = LoggerFactory.getLogger(BeenFactorTest.class); @Autowired private Student student; @org.junit.Test public void test(){ log.info(student.getAge() +""); } } <file_sep>/src/main/java/design_patterns/state/WinnerState.java package design_patterns.state; /** * Created by dell on 2019/1/15. */ public class WinnerState implements State { GumballMachine gumballMachine; public WinnerState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("该状态不能投币"); } @Override public void ejectQuarter() { System.out.println("该状态不能退币"); } @Override public void tumCrank() { System.out.println("该状态不能按下曲柄"); } @Override public void dispense() { System.out.println("你被评为幸运用户,奖励一个糖果"); gumballMachine.releaseBall(); if(gumballMachine.getCounter() == 0){ gumballMachine.setState(gumballMachine.getSoldOutState()); }else { gumballMachine.releaseBall(); if(gumballMachine.getCounter() > 0){ gumballMachine.setState(gumballMachine.getNoQuarterState()); System.out.println("糖果已发放,请及时取出"); }else { System.out.println("Oops,out of gumballs"); gumballMachine.setState(gumballMachine.getSoldOutState()); } } } } <file_sep>/src/main/java/design_patterns/strategy_pattern/Test.java package design_patterns.strategy_pattern; /** * Created by dell on 2018/12/28. */ public class Test { public static void main(String[] args){ Duck air = new AirDuck(); Duck rocket = new RocketDuck(); air.fly(); rocket.fly(); } } <file_sep>/src/main/java/thread/MySemaphore.java package thread; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Semaphore; /** * Created by dell on 2019/2/22. */ public class MySemaphore { public static void main(String[] args) throws InterruptedException { BoundedHashSet<String> boundedHashSet = new BoundedHashSet<>(1); boundedHashSet.add("123"); System.out.println(new Date()); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10000); boundedHashSet.remove("123"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); boundedHashSet.add("qwe"); System.out.println(new Date()); } static class BoundedHashSet<T>{ private final Set<T> set; private final Semaphore semaphore; public BoundedHashSet(int bound){ this.set = Collections.synchronizedSet(new HashSet<>()); semaphore = new Semaphore(bound); } public boolean add(T o) throws InterruptedException { semaphore.acquire(); boolean wasAdd = false; try { wasAdd = set.add(o); }finally { if(!wasAdd) semaphore.release(); } return wasAdd; } public boolean remove(Object o){ boolean wasRemove = set.remove(o); if(wasRemove) semaphore.release(); return wasRemove; } } } <file_sep>/src/main/java/design_patterns/command/hotel_test/Consumer.java package design_patterns.command.hotel_test; import java.util.ArrayList; import java.util.List; /** * Created by dell on 2019/1/2. */ public class Consumer { public static void main(String[] args){ Cooker cooker = new Cooker(); List<CommandCook> commandCooks = new ArrayList<>(); DanChaoFanCommand danChaoFanCommand = new DanChaoFanCommand(); danChaoFanCommand.setCooker(cooker); commandCooks.add(danChaoFanCommand); NiuPaiCommand niuPaiCommand = new NiuPaiCommand(); niuPaiCommand.setCooker(cooker); commandCooks.add(niuPaiCommand); Waiter waiter = new Waiter(); waiter.setCommandCooks(commandCooks); waiter.takeOrder(); } } <file_sep>/src/main/java/factory/factorybean/Contr.java package factory.factorybean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * Created by dell on 2018/12/29. */ @Controller public class Contr { @Autowired private Service service; } <file_sep>/src/main/java/factory/factorybean/ServiceImpl.java package factory.factorybean; /** * Created by dell on 2018/12/29. */ @org.springframework.stereotype.Service public class ServiceImpl implements Service { } <file_sep>/src/main/resources/my.properties dataSource = "dataSource"<file_sep>/src/main/java/aop/AopTest.java package aop; import org.aspectj.lang.ProceedingJoinPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; /** * Created by dell on 2018/12/14. */ public class AopTest{ private static Logger log = LoggerFactory.getLogger(AopTest.class); public void before(){ log.info("+++++++++before00000000000000000+++++++++"); } public void after(){ log.info("+++++++++after00000000000000+++++++++"); } public void afterReturn(){ log.info("+++++++++afterReturn0000000000+++++++++"); } public void afterThrow(){ log.info("+++++++++afterThrow00000000000+++++++++"); } public Object around(ProceedingJoinPoint pJoinPoint)throws Throwable{ log.info("+++++++++around++++++++0000000000000000+"); Object ob = pJoinPoint.proceed(); return ob; } } <file_sep>/src/main/java/design_patterns/strategy_pattern/Fly.java package design_patterns.strategy_pattern; /** * Created by dell on 2018/12/28. */ public interface Fly { void playFly(); } <file_sep>/src/main/java/factory/factorybean/WangBean.java package factory.factorybean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by dell on 2018/12/23. */ public class WangBean { private static Logger log = LoggerFactory.getLogger(WangBean.class); public WangBean(){ log.error("========WangBean=================="); } } <file_sep>/src/main/java/design_patterns/state/State.java package design_patterns.state; /** * Created by dell on 2019/1/15. */ public interface State { //投币代码 void insertQuarter(); //退钱 void ejectQuarter(); // 转动曲柄 void tumCrank(); //发送糖果 void dispense(); } <file_sep>/src/main/java/design_patterns/singleton/Singleton2.java package design_patterns.singleton; /** * Created by dell on 2019/1/2. */ public class Singleton2 { private static Singleton2 singleton2 = new Singleton2(); private Singleton2(){ } public static Singleton2 getSingleton2(){ return singleton2; } } <file_sep>/src/main/java/factory/Student.java package factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; /** * Created by dell on 2018/12/4. */ @Component public class Student { private int age; private String name; private static Logger log = LoggerFactory.getLogger(Student.class); public Student(){ name = "test"; age = 12; } public Student(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Student1 @Student2 public String getName() { log.info(name); return name; } public void setName(String name) { this.name = name; } } <file_sep>/src/main/java/question/abstractclass/MyInterface.java package question.abstractclass; /** * Created by dell on 2019/1/11. */ public interface MyInterface { void say(); int add(); } <file_sep>/src/main/java/springmybatis/mapper/UsersMapper.java package springmybatis.mapper; import java.util.List; import springmybatis.model.Users; public interface UsersMapper { int deleteByPrimaryKey(Integer userId); int insert(Users record); Users selectByPrimaryKey(Integer userId); List<Users> selectAll(); int updateByPrimaryKey(Users record); }<file_sep>/src/main/java/aop/AopTest1.java package aop; import org.aspectj.lang.ProceedingJoinPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; /** * Created by dell on 2019/1/10. */ public class AopTest1 { private static Logger log = LoggerFactory.getLogger(AopTest1.class); public void before(){ log.info("+++++++++before...........1+++++++++"); } public void after(){ log.info("+++++++++after...........1+++++++++"); } public void afterReturn(){ log.info("+++++++++afterReturn..........1+++++++++"); } public void afterThrow(){ log.info("+++++++++afterThrow...........1+++++++++"); } public Object around(ProceedingJoinPoint pJoinPoint)throws Throwable{ log.info("+++++++++around...........1+++++++++"); Object ob = pJoinPoint.proceed(); return ob; } } <file_sep>/src/main/java/question/Test.java package question; /** * Created by dell on 2019/1/11. */ public class Test { } <file_sep>/src/main/java/cglib/HelloServiceImpl.java package cglib; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by dell on 2019/1/7. */ public class HelloServiceImpl { private Logger log = LoggerFactory.getLogger(HelloServiceImpl.class); public void sayHello(){ log.error("hello"); } } <file_sep>/src/main/java/test/TestBeanFactoryPostProcessorConfig.java package test; import config.BeanFactoryPostProcessorConfig; import config.FactoryBean; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by dell on 2018/12/23. */ public class TestBeanFactoryPostProcessorConfig { public static void main(String[] args){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanFactoryPostProcessorConfig.class); Object o = applicationContext.getBean("beanTmp"); } } <file_sep>/src/main/java/mybatis/Test.java package mybatis; import mybatis.spring.Config; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Created by dell on 2019/1/10. */ public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); // Configuration configuration = new Configuration(); // DefaultExecutor defaultExecutor = new DefaultExecutor(); // SqlSession sqlSession = new SqlSession(configuration,defaultExecutor); // mybatis.mapperinterface.Test test = sqlSession.getMapper(mybatis.mapperinterface.Test.class); // test.selectNameById("1"); } } <file_sep>/src/main/java/test/Test.java package test; import factory.Student; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by dell on 2018/12/4. */ public class Test { private static Logger log = LoggerFactory.getLogger(Test.class); public static void main(String[] args){ // //定位,载入,注册 // ClassPathResource resource = new ClassPathResource("applicationContext.xml"); // DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); // XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); // reader.loadBeanDefinitions(resource); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student student = (Student) context.getBean("student"); log.info(student.getName()); student.setName("test"); // // Test test = new Test(); // log.error(test.getClass().getClassLoader() + ""); // log.error(test.getClass().getClassLoader().getParent() + ""); // log.error(test.getClass().getClassLoader().getParent().getParent() + ""); } } <file_sep>/src/main/java/design_patterns/observer/Observer.java package design_patterns.observer; import java.util.ArrayList; import java.util.List; /** * Created by dell on 2018/12/28. */ public class Observer { private String news; private List<ObserverAble> observerAbles = new ArrayList<>(); public String getNews() { return news; } public void setNews(String news) { this.news = news; change(); } public boolean addObserverAble(ObserverAble observerAble){ return observerAbles.add(observerAble); } public boolean deleteObserverAble(ObserverAble observerAble){ return observerAbles.remove(observerAble); } private void change(){ observerAbles.forEach(observerAble -> observerAble.update(this)); } } <file_sep>/src/main/java/springmybatis/SpringMybatisTest.java package springmybatis; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import springmybatis.config.ConfigBean; import springmybatis.service.SumService; /** * Created by dell on 2019/1/17. */ public class SpringMybatisTest { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConfigBean.class); applicationContext.getBean(SumService.class).test(); applicationContext.getBean(SumService.class).testTransactional(); } } <file_sep>/src/main/java/com/mybatis/model/Users.java package com.mybatis.model; import java.util.Date; public class Users { private Integer userId; private String userName; private Date brithday; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public Date getBrithday() { return brithday; } public void setBrithday(Date brithday) { this.brithday = brithday; } @Override public String toString() { return "userId:" + userId + ";姓名:" + userName + ";生日:" + brithday + super.toString(); } }<file_sep>/src/main/java/springmybatis/mapper/TestMybatisMapper.java package springmybatis.mapper; import java.util.List; import springmybatis.model.TestMybatis; public interface TestMybatisMapper { int deleteByPrimaryKey(Integer id); int insert(TestMybatis record); TestMybatis selectByPrimaryKey(Integer id); List<TestMybatis> selectAll(); int updateByPrimaryKey(TestMybatis record); }<file_sep>/src/main/java/com/mybatis/copy/WangScannerRegistrar.java package com.mybatis.copy; import com.mybatis.mapper.UsersMapper; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; /** * Created by dell on 2018/12/24. */ public class WangScannerRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(UsersMapper.class); GenericBeanDefinition beanDefinition = (GenericBeanDefinition) builder.getBeanDefinition(); beanDefinition.setBeanClass(WangMapperFactoryBean.class); beanDefinition.getConstructorArgumentValues().addGenericArgumentValue("com.mybatis.mapper.UsersMapper"); registry.registerBeanDefinition("usersMapper",beanDefinition); } }
2da89f7552ea7272299ef3800bfc36ee14c8e5e1
[ "Java", "INI", "Gradle" ]
42
Java
wangyuanyangV5/springlearn
2692c6bdc6581e9e434353bb99a0f8a8fbc08225
283507bc43ab36b218b90ef6545088f280ee021b
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; public class personel { private int pertc; private String perad; private String persoyad; private String pergorev; private int ucret; public personel(int pertc,String perad,String persoyad,String pergorev,int ucret) { this.pertc = pertc; this.perad = perad; this.persoyad = persoyad; this.pergorev = pergorev; this.ucret = ucret; } public int getPertc() { return pertc; } public void setPertc(int pertc) { this.pertc = pertc; } public String getPerad() { return perad; } public void setPerad(String perad) { this.perad = perad; } public String getPersoyad() { return persoyad; } public void setPersoyad(String persoyad) { this.persoyad = persoyad; } public String getPergorev() { return pergorev; } public void setPergorev(String pergorev) { this.pergorev = pergorev; } public int getUcret() { return ucret; } public void setUcret(int ucret) { this.ucret = ucret; } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author esref */ public class Personelbil extends javax.swing.JFrame { DefaultTableModel model; adminislemleri adminislemleri1=new adminislemleri(); public Personelbil() { initComponents(); model= (DefaultTableModel)jTable1.getModel(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); perad = new javax.swing.JTextField(); permaas = new javax.swing.JTextField(); persoyad = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); pertc = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox(); jButton5 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBounds(new java.awt.Rectangle(500, 250, 0, 0)); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setBackground(new java.awt.Color(0, 0, 0)); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("ADI :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("SOYADI :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("GÖREVİ :"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("MAAŞ :"); jButton1.setBackground(new java.awt.Color(0, 255, 255)); jButton1.setText("EKLE"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setBackground(new java.awt.Color(0, 255, 255)); jButton2.setText("SİL"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 255, 255)); jLabel6.setText("TC :"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<NAME> ", "<NAME>", "<NAME>", " " })); jButton5.setBackground(new java.awt.Color(0, 255, 255)); jButton5.setText("Güncelleme"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel6)) .addGap(45, 45, 45) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pertc, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(perad, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(72, 72, 72) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel4)) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(permaas, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(persoyad, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(110, 110, 110) .addComponent(jButton5))) .addContainerGap(57, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(67, 67, 67) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pertc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addGap(26, 26, 26) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(perad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(persoyad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(permaas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 109, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton1)) .addGap(18, 18, 18) .addComponent(jButton5) .addGap(21, 21, 21)) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, 350, 450)); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null}, {null, null, null, null, null} }, new String [] { "TC", "Ad", "Soyad", "Görevi", "Maaş" } )); jTable1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable1MouseClicked(evt); } }); jScrollPane1.setViewportView(jTable1); jButton3.setBackground(new java.awt.Color(0, 255, 255)); jButton3.setText("PERSONELLERİ GÖRÜNTÜLE"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(176, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 247, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(167, 167, 167)) .addComponent(jScrollPane1) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE)) ); getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 80, 590, 450)); jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/geri.png"))); // NOI18N jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4geri(evt); } }); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton4.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jButton4KeyPressed(evt); } }); getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, 50, 40)); jButton9.setBackground(new java.awt.Color(255, 0, 0)); jButton9.setForeground(new java.awt.Color(255, 255, 255)); jButton9.setText("X"); jButton9.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jButton9pressed_button(evt); } }); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); getContentPane().add(jButton9, new org.netbeans.lib.awtextra.AbsoluteConstraints(930, 20, 40, 40)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("PERSONEL İŞLEMLERİ"); getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 20, 460, -1)); jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/view/484717.jpg"))); // NOI18N getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1000, 560)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed int tc = Integer.valueOf(pertc.getText()); String ad = perad.getText(); String soyad = persoyad.getText(); String gorevi = jComboBox1.getSelectedItem().toString(); int maas = Integer.valueOf(permaas.getText()); adminislemleri1.personelekle(tc,ad,soyad,gorevi,maas); JOptionPane.showMessageDialog(null, "Başarılı Bir kayıt işlemi "); pergor(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed pergor(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4geri(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4geri setVisible(false); admine_ozel abc=new admine_ozel(); abc.setVisible(true); }//GEN-LAST:event_jButton4geri private void jButton9pressed_button(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton9pressed_button }//GEN-LAST:event_jButton9pressed_button private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed System.exit(0); }//GEN-LAST:event_jButton9ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed int selectedrow= jTable1.getSelectedRow(); if (selectedrow == -1) { if (model.getRowCount() == 0) { JOptionPane.showMessageDialog(null, "Öğrenci kayıt tablosunda bilgi bulanamadı...","Kayıt Bulunamadı",JOptionPane.OK_OPTION); setVisible(false); srcbil ogrenciIslemleriEkrani = new srcbil(); ogrenciIslemleriEkrani.setVisible(true); } else{ JOptionPane.showMessageDialog(null, "Lütfen silinecek bir öğrenci seçin...","Öğrenci Seçim",JOptionPane.WARNING_MESSAGE); setVisible(false); srcbil ogrenciKayitSilme = new srcbil(); ogrenciKayitSilme.setVisible(true); } } else{ int tc=(int)model.getValueAt(selectedrow, 0); //,ad,soyad,tc,dogumtarih,kresbaslangic,kangrubu,veliad,velisoyad,velitc,yakinlik,telno,adres adminislemleri1.perSil(tc); setVisible(false); Personelbil abc = new Personelbil(); abc.setVisible(true); } pergor(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton4ActionPerformed private void jButton4KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton4KeyPressed if (evt.getKeyCode()==KeyEvent.VK_ESCAPE) { setVisible(false); admine_ozel abc=new admine_ozel(); abc.setVisible(true); } }//GEN-LAST:event_jButton4KeyPressed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed String ad=perad.getText(); String soyad=persoyad.getText(); int maas=Integer.valueOf(permaas.getText()); int tc=Integer.valueOf(pertc.getText()); adminislemleri1.personelGuncelle(ad, soyad, maas, tc); adminislemleri1.personelgoruntule(); pergor(); }//GEN-LAST:event_jButton5ActionPerformed private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked int selectedRow=jTable1.getSelectedRow(); perad.setText(model.getValueAt(selectedRow, 1).toString()); persoyad.setText(model.getValueAt(selectedRow, 2).toString()); permaas.setText(model.getValueAt(selectedRow, 4).toString()); pertc.setText(model.getValueAt(selectedRow,0).toString()); }//GEN-LAST:event_jTable1MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Personelbil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Personelbil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Personelbil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Personelbil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Personelbil().setVisible(true); } }); } public void pergor() { model.setRowCount(0); ArrayList<personel> perg = new ArrayList<personel>(); perg = adminislemleri1.personelgoruntule(); if (perg != null ) { for (personel perr : perg) { Object[] jtable = {perr.getPertc(),perr.getPerad(),perr.getPersoyad(),perr.getPergorev(),perr.getUcret()}; model.addRow(jtable); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton9; private javax.swing.JComboBox jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField perad; private javax.swing.JTextField permaas; private javax.swing.JTextField persoyad; private javax.swing.JTextField pertc; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class adminislemleri { private Connection con = null; private Statement statement = null; private PreparedStatement preparedStatement = null; public boolean giris(String kullanici_adi,String parola) { String sorgu = "Select * From admin where kullaniciadi = ? and sifre = ?"; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setString(1,kullanici_adi); preparedStatement.setString(2,parola); ResultSet rs = preparedStatement.executeQuery(); return rs.next(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return false; } } public void ogrenciSil(int tc){ String sorgu = "Delete FROM musteri where tc= ?"; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setInt(1,tc); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void ogrenciSil(){ String sorgu = "Delete FROM musteri"; try { statement.executeUpdate(sorgu); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void perSil(int tc){ String sorgu = "Delete FROM personel where tc= ?"; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setInt(1,tc); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void surucuekle(int tc,String ad,String soyad,String kayitarih,String ehliyetsinif,int ucret) { String sorgu = "Insert Into musteri (tc,ad,soyad,kayıttarihi,ehliyetsinifi,ucret) VALUES(?,?,?,?,?,?)"; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setInt(1, tc); preparedStatement.setString(2, ad); preparedStatement.setString(3, soyad); preparedStatement.setString(4, kayitarih); preparedStatement.setString(5, ehliyetsinif); preparedStatement.setInt(6, ucret); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void personelekle(int tc,String ad,String soyad,String gorevi,int maas){ String sorgu = "Insert Into personel (tc,ad,soyad,gorevi,maas) VALUES(?,?,?,?,?)"; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setInt(1, tc); preparedStatement.setString(2, ad); preparedStatement.setString(3, soyad); preparedStatement.setString(4, gorevi); preparedStatement.setInt(5, maas); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void surucuGuncelle(String yeni_ad,String yeni_soyad,String yeni_kayittarihi,int yeni_ucret,int tc) { String sorgu = "Update musteri set ad = ? , soyad = ? , kayıttarihi = ? , ucret = ? where tc = ? "; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setString(1, yeni_ad); preparedStatement.setString(2, yeni_soyad); preparedStatement.setString(3, yeni_kayittarihi); preparedStatement.setInt(4, yeni_ucret); preparedStatement.setInt(5, tc); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public void personelGuncelle(String yeni_ad,String yeni_soyad,int yeni_maas,int tc) { String sorgu = "Update personel set ad = ? , soyad = ? , maas = ? where tc = ? "; try { preparedStatement = con.prepareStatement(sorgu); preparedStatement.setString(1, yeni_ad); preparedStatement.setString(2, yeni_soyad); preparedStatement.setInt(3, yeni_maas); preparedStatement.setInt(4, tc); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); } } public int surcgelir() { try { statement = con.createStatement(); String sorgum = "SELECT SUM(ucret) FROM musteri;"; ResultSet rs = statement.executeQuery(sorgum); int sum = 0; while (rs.next()) { int c = rs.getInt(1); sum = sum + c; } return sum; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return 1; } } public int pergider() { try { statement = con.createStatement(); String sorgum = "SELECT SUM(maas) FROM personel ;"; ResultSet rs = statement.executeQuery(sorgum); int top = 0; while (rs.next()) { int c = rs.getInt(1); top = top + c; } return top; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return 1; } } public ArrayList<surucu> surucugoruntu() { ArrayList<surucu> goruntu = new ArrayList<surucu>(); try { statement = con.createStatement(); String sorgu = "Select * From musteri"; ResultSet rs = statement.executeQuery(sorgu); while(rs.next()) { int tc = rs.getInt("tc"); String srcad = rs.getString("ad"); String srcsoyad = rs.getString("soyad"); String kayit = rs.getString("kayıttarihi"); String ehliyet = rs.getString("ehliyetsınıfı"); int ucret = rs.getInt("ucret"); goruntu.add(new surucu(tc,srcad,srcsoyad,kayit, ehliyet ,ucret)); } return goruntu; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return null; } } public ArrayList<gelirtab> gelirgoruntu() { ArrayList<gelirtab> tbl = new ArrayList<gelirtab>(); try { statement = con.createStatement(); String sorgu = "Select * From musteri WHERE (ucret>'0')"; ResultSet rs = statement.executeQuery(sorgu); while(rs.next()) { int tc = rs.getInt("tc"); String srcad = rs.getString("ad"); String srcsoyad = rs.getString("soyad"); int ucret = rs.getInt("ucret"); tbl.add(new gelirtab(tc,srcad,srcsoyad,ucret)); } return tbl; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return null; } } public ArrayList<gidertab> gidergoruntu() { ArrayList<gidertab> qwe = new ArrayList<gidertab>(); try { statement = con.createStatement(); String sorgu = "Select * From personel WHERE (maas>'0')"; ResultSet rs = statement.executeQuery(sorgu); while(rs.next()) { int pertc = rs.getInt("tc"); String perad = rs.getString("ad"); String persoyad = rs.getString("soyad"); int maas = rs.getInt("maas"); qwe.add(new gidertab(pertc,perad,persoyad,maas)); } return qwe; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return null; } } public ArrayList<personel> personelgoruntule() { ArrayList<personel> pergorr = new ArrayList<personel>(); try { statement = con.createStatement(); String sorguu = "Select * From personel"; ResultSet rs = statement.executeQuery(sorguu); while(rs.next()) { int tc = rs.getInt("tc"); String perad = rs.getString("ad"); String persoyad = rs.getString("soyad"); String gorevi = rs.getString("gorevi"); int ucret = rs.getInt("maas"); pergorr.add(new personel(tc,perad,persoyad,gorevi,ucret)); } return pergorr; } catch (SQLException ex) { Logger.getLogger(adminislemleri.class.getName()).log(Level.SEVERE, null, ex); return null; } } public adminislemleri() { String url = "jdbc:mysql://" + Database.host + ":" + Database.port + "/" + Database.db_ismi+ "?useUnicode=true&characterEncoding=utf8"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { System.out.println("Driver Bulunamadı...."); } try { con = DriverManager.getConnection(url, Database.kullanici_adi, Database.parola); System.out.println("Bağlantı Başarılı..."); } catch (SQLException ex) { System.out.println("Bağlantı Başarısız..."); //ex.printStackTrace(); } } } <file_sep>package parametre; public class parametre { public static void main(String[] args) { int carpim1 = carp(12, 13); int carpim2 = carp(7, 9, 123); double carp = carp(2.50, 2.75); } public static int carp(int x, int y) { return x + y; } public static int carp(int x, int y, int z) { return x + y + z; } public static double carp(double x, double y) { return x + y; } }
797171e3c1028edf453c253ec17c3739ada59eca
[ "Java" ]
4
Java
Selman81/Java-S-r-c--Kursu-Otomasyonu
45c87427574c7338630a84000fe1ed48b0b14f1d
1319ec7272b81ed7d3f58f40a67a4546f243fbdc